“股票市场上充满了知道所有东西价格但不知道任何东西的价值的人。” - 菲利普·费舍尔
Python 的受欢迎程度显着提高,并被用于广泛的应用,从基本计算到股票市场数据的高级统计分析。在本文中,我们将研究一个 Python 脚本,它体现了 Python 在金融领域日益增长的主导地位。它能够与数据无缝集成、执行复杂的计算和自动执行任务,这使其成为金融专业人士的宝贵工具。
此脚本演示了如何使用 Python 分析新闻标题并提取有关市场情绪的宝贵见解。通过利用自然语言处理 (NLP) 库的强大功能,该脚本可以分析与特定股票相关的新闻文章的情绪基调。该分析可以为投资者提供重要信息,帮助他们:
import requests import pandas as pd from nltk.sentiment.vader import SentimentIntensityAnalyzer # THIS NEEDS TO BE INSTALLED # --------------------------- # import nltk # nltk.download('vader_lexicon') # Function to fetch news headlines from a free API def get_news_headlines(ticker): """ Fetches news headlines related to the given stock ticker from a free API. Args: ticker: Stock ticker symbol (e.g., 'AAPL', 'GOOG'). Returns: A list of news headlines as strings. """ # We are using the below free api from this website https://eodhd.com/financial-apis/stock-market-financial-news-api url = f'https://eodhd.com/api/news?s={ticker}.US&offset=0&limit=10&api_token=demo&fmt=json' response = requests.get(url) response.raise_for_status() # Raise an exception for bad status codes try: data = response.json() # Extract the 'title' from each article headlines = [article['title'] for article in data] return headlines except (KeyError, ValueError, TypeError): print(f"Error parsing API response for {ticker}") return [] # Function to perform sentiment analysis on headlines def analyze_sentiment(headlines): """ Performs sentiment analysis on a list of news headlines using VADER. Args: headlines: A list of news headlines as strings. Returns: A pandas DataFrame with columns for headline and sentiment scores (compound, positive, negative, neutral). """ sia = SentimentIntensityAnalyzer() sentiments = [] for headline in headlines: sentiment_scores = sia.polarity_scores(headline) sentiments.append([headline, sentiment_scores['compound'], sentiment_scores['pos'], sentiment_scores['neg'], sentiment_scores['neu']]) df = pd.DataFrame(sentiments, columns=['Headline', 'Compound', 'Positive', 'Negative', 'Neutral']) return df # Main function if __name__ == "__main__": ticker = input("Enter stock ticker symbol: ") headlines = get_news_headlines(ticker) if headlines: sentiment_df = analyze_sentiment(headlines) print(sentiment_df) # Calculate average sentiment average_sentiment = sentiment_df['Compound'].mean() print(f"Average Sentiment for {ticker}: {average_sentiment}") # Further analysis and visualization can be added here # (e.g., plotting sentiment scores, identifying most positive/negative headlines) else: print(f"No news headlines found for {ticker}.")
输出:
Python 的多功能性和强大的库使其成为现代数据分析和计算任务不可或缺的工具。它处理从简单计算到复杂股票市场分析的一切能力凸显了其跨行业的价值。随着 Python 的不断发展,其在推动数据驱动决策的创新和效率方面的作用将进一步扩大,巩固其作为技术进步基石的地位
注:AI辅助内容
以上是用于股票情绪分析的 Python 脚本的详细内容。更多信息请关注PHP中文网其他相关文章!