Financial Sentiment Analysis and Stock Information Retrieval with Python

SR
5 min readJan 2, 2024

--

Full Code :

import yfinance as yf
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import requests

# Download NLTK data for sentiment analysis
nltk.download('vader_lexicon')

# Function to analyze sentiment of a text
def analyze_sentiment(text):
sia = SentimentIntensityAnalyzer()
sentiment_score = sia.polarity_scores(text)['compound']
return sentiment_score

# Function to get stock information using yfinance
def get_stock_info(ticker):
stock_data = yf.Ticker(ticker)
return stock_data.info

# Function to get financial news and analyze sentiment
def get_news_sentiment(ticker):
news_url = f'https://newsapi.org/v2/everything?q={ticker}&apiKey=your-api-key' # Replace 'your-api-key' with an actual API key if needed

response = requests.get(news_url)
news_data = response.json()

if 'articles' in news_data:
for article in news_data['articles']:
title = article['title']
description = article.get('description', '')

# Analyze sentiment of title and description
title_sentiment = analyze_sentiment(title)
description_sentiment = analyze_sentiment(description)

print(f"Title: {title}")
print(f"Title Sentiment: {title_sentiment}")
print(f"Description: {description}")
print(f"Description Sentiment: {description_sentiment}")
print("\n")

# Example usage
if __name__ == "__main__":
stock_ticker = 'AAPL' # Replace with the desired stock ticker
get_news_sentiment(stock_ticker)
stock_info = get_stock_info(stock_ticker)
print("Stock Information:")
display(stock_info)

Let’s break down the code part by part:

  1. Importing necessary libraries/modules:

Use Case: You are building a financial analysis tool that requires fetching stock information, analyzing sentiment in news articles, and making HTTP requests to external APIs. These libraries/modules are essential for handling these tasks efficiently.

import yfinance as yf
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import requests

Explanation:

  • The code imports necessary libraries and modules for financial data retrieval (yfinance), natural language processing with VADER sentiment analysis (nltk), and making HTTP requests (requests).

Here, the code imports the `yfinance` library for fetching stock information, the `nltk` library for natural language processing tasks, specifically using the VADER sentiment analysis tool, and the `requests` module for making HTTP requests.

2. Downloading NLTK data for sentiment analysis:

Use Case: You are developing a sentiment analysis application and want to use the VADER sentiment analysis tool from NLTK. Downloading the VADER lexicon is necessary for accurate sentiment analysis.

nltk.download('vader_lexicon')

Explanation:

  • This line downloads the VADER lexicon, which is essential for performing sentiment analysis using the VADER sentiment analysis tool from the NLTK library.

This line downloads the VADER lexicon, which is a pre-trained sentiment analysis tool provided by NLTK.

3. Defining a function to analyze sentiment:

Use Case: You have a large dataset of text data, such as customer reviews or social media comments, and you want to analyze the sentiment of each text. The analyze_sentiment function provides a way to quickly calculate sentiment scores for each piece of text.

def analyze_sentiment(text):
sia = SentimentIntensityAnalyzer()
sentiment_score = sia.polarity_scores(text)['compound']
return sentiment_score

Explanation:

  • This function, analyze_sentiment, takes a text input and uses the VADER sentiment analysis tool to calculate a compound sentiment score. The compound score represents the overall sentiment of the text.

This function takes a text input and uses the VADER sentiment analysis tool to calculate a compound sentiment score.

4. Defining a function to get stock information using yfinance:

Use Case: You are creating a financial dashboard or application that requires real-time stock information. The get_stock_info function allows you to easily retrieve detailed information about a specific stock using the Yahoo Finance API.

def get_stock_info(ticker):
stock_data = yf.Ticker(ticker)
return stock_data.info

Explanation:

  • The function get_stock_info takes a stock ticker symbol as input and uses the yfinance library to fetch and return detailed information about the specified stock.

This function takes a stock ticker symbol as input and uses the `yfinance` library to fetch and return the information about the stock.

5. Defining a function to get financial news and analyze sentiment:

Use Case: You want to stay informed about the latest news related to a particular stock and understand the sentiment of the news articles. The get_news_sentiment function fetches news articles using the News API, analyzes the sentiment of titles and descriptions, and prints the results.

def get_news_sentiment(ticker):
news_url = f'https://newsapi.org/v2/everything?q={ticker}&apiKey=your-api-key' # Replace 'your-api-key' with an actual API key if needed

response = requests.get(news_url)
news_data = response.json()
if 'articles' in news_data:
for article in news_data['articles']:
title = article['title']
description = article.get('description', '')
# Analyze sentiment of title and description
title_sentiment = analyze_sentiment(title)
description_sentiment = analyze_sentiment(description)
print(f"Title: {title}")
print(f"Title Sentiment: {title_sentiment}")
print(f"Description: {description}")
print(f"Description Sentiment: {description_sentiment}")
print("\n")

Explanation:

  • The get_news_sentiment function takes a stock ticker as input and constructs a URL to fetch news related to the stock using the News API.
  • It then makes an HTTP request to the News API, retrieves the JSON response, and iterates through the articles, printing the title, description, and their respective sentiment scores (calculated using the analyze_sentiment function).

This function takes a stock ticker as input, constructs a URL to fetch news related to the stock using the News API, and then iterates through the articles in the response, printing the title, description, and their respective sentiment scores.

6. Example usage:

Use Case: You are interested in analyzing the sentiment of news articles related to a specific stock (e.g., ‘AAPL’) and simultaneously fetching and displaying detailed stock information. The example usage in the main block demonstrates how to use the previously defined functions for this purpose.

if __name__ == "__main__":
stock_ticker = 'AAPL' # Replace with the desired stock ticker
get_news_sentiment(stock_ticker)
stock_info = get_stock_info(stock_ticker)
print("Stock Information:")
display(stock_info)

Explanation:

  • The main block sets the stock ticker symbol (in this case, ‘AAPL’).
  • It then calls the get_news_sentiment function to fetch and analyze news sentiment for the specified stock.
  • The get_stock_info function is called to fetch and print detailed stock information.
  • Note: The display function is mentioned but not defined; you may need to replace it with a suitable print or display function based on your needs.

In the main block, it sets the stock ticker symbol (in this case, ‘AAPL’), calls the `get_news_sentiment` function to fetch and analyze news sentiment, and then calls the `get_stock_info` function to get and print stock information using `yfinance`. Note that there is a `display` function call at the end, which seems to be missing its definition; you may want to replace it with a suitable print or display function based on your needs.

--

--

SR

15-year-old enthusiast passionate about tech, code, and creative writing. Sharing my journey on Medium. 🚀 | Code | Tech | Writing | Malaysian |