yahoo_fin
Library
First, install the yahoo_fin
and TextBlob
libraries using pip:
pip install yahoo_fin textblob
This script uses yahoo_fin
to fetch the latest news articles for a given stock ticker symbol, then uses TextBlob
to analyze the sentiment of these news articles.
from yahoo_fin import stock_info as si
from yahoo_fin import news as nf
from textblob import TextBlob
import pandas as pd
# Define the stock ticker symbol
ticker = "AAPL" # Example: Apple Inc.
# Fetch latest news articles for the stock
news = nf.get_yf_rss(ticker)
# Extract news titles and links
news_data = []
for article in news:
news_data.append({
"title": article["title"],
"link": article["link"],
})
# Convert news data to a DataFrame
news_df = pd.DataFrame(news_data)
# Function to analyze sentiment
def analyze_sentiment(text):
blob = TextBlob(text)
return blob.sentiment.polarity
# Apply sentiment analysis to news titles
news_df['sentiment'] = news_df['title'].apply(analyze_sentiment)
# Display news with sentiment scores
print(news_df)
# Calculate the average sentiment
average_sentiment = news_df['sentiment'].mean()
print(f"\nAverage Sentiment for {ticker}: {average_sentiment:.2f}")
nf.get_yf_rss(ticker)
fetches the latest news articles for the specified ticker from Yahoo Finance.
TextBlob
to analyze the sentiment of each news title. TextBlob(text).sentiment.polarity
returns a sentiment polarity score ranging from -1 (very negative) to 1 (very positive).
TextBlob
may not be very accurate for financial news. More advanced models trained specifically on financial text data might provide better results.
This script provides a good starting point for building a sentiment analysis tool based on news data fetched from Yahoo Finance using the unofficial yahoo_fin
API.