「股票市場上充滿了知道所有東西價格但不知道任何東西的價值的人。」 - 菲利普·費舍爾
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中文網其他相關文章!