"The stock market is filled with individuals who know the price of everything, but the value of nothing." - Philip Fisher
Python has been growing significantly in popularity and is used in a wide range of applications, from basic computations to advanced statistical analysis for stock market data. In this article we will look at a Python script which exemplifies the growing dominance of Python in the financial world. Its ability to seamlessly integrate with data, perform complex calculations, and automate tasks makes it an invaluable tool for financial professionals.
This script demonstrates how Python can be used to analyze news headlines and extract valuable insights into market sentiment. By leveraging the power of Natural Language Processing (NLP) libraries, the script analyzes the emotional tone of news articles related to a specific stock. This analysis can provide crucial information for investors, helping them:
- Make more informed investment decisions: By understanding the prevailing market sentiment, investors can identify potential opportunities and mitigate risks.
- Develop more effective trading strategies: Sentiment analysis can be integrated into trading algorithms to improve timing and potentially enhance returns.
- Gain a competitive edge: Python's versatility allows for the development of sophisticated financial models and the analysis of vast datasets, providing a significant advantage in the competitive financial landscape
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}.")
Output:
Imports
-
requests
: Used to make HTTP requests to fetch data from a web API. -
pandas
: A data manipulation library used to create and manage data in DataFrame format. -
SentimentIntensityAnalyzer
fromnltk.sentiment.vader
: A tool for sentiment analysis that provides sentiment scores for text.
Setup
-
NLTK Setup: The script includes a comment indicating that the VADER lexicon needs to be downloaded using NLTK. This is done with
nltk.download('vader_lexicon')
.
Functions
get_news_headlines(ticker)
- Purpose: Fetches news headlines related to a given stock ticker symbol.
-
Parameters:
-
ticker
: A string representing the stock ticker symbol (e.g., 'AAPL' for Apple).
-
- Returns: A list of news headlines as strings.
-
Implementation:
- Constructs a URL for a hypothetical news API using the provided ticker.
- Sends a GET request to the API and checks for successful response status.
- Parses the JSON response to extract headlines.
- Handles potential errors in parsing with a try-except block.
analyze_sentiment(headlines)
- Purpose: Performs sentiment analysis on a list of news headlines.
-
Parameters:
-
headlines
: A list of strings, each representing a news headline.
-
- Returns: A pandas DataFrame containing the headlines and their sentiment scores (compound, positive, negative, neutral).
-
Implementation:
- Initializes the SentimentIntensityAnalyzer.
- Iterates over each headline, calculates sentiment scores, and stores them in a list.
- Converts the list of sentiment data into a pandas DataFrame.
Main Execution
- The script prompts the user to input a stock ticker symbol.
- It calls
get_news_headlines
to fetch headlines for the given ticker. - If headlines are found, it performs sentiment analysis using
analyze_sentiment
. - The resulting DataFrame is printed, showing each headline with its sentiment scores.
- It calculates and prints the average compound sentiment score for the headlines.
- If no headlines are found, it prints a message indicating this.
Conclusion
Python's versatility and powerful libraries make it an indispensable tool for modern data analysis and computational tasks. Its ability to handle everything from simple calculations to complex stock market analyses underscores its value across industries. As Python continues to evolve, its role in driving innovation and efficiency in data-driven decision-making is set to expand even further, solidifying its place as a cornerstone of technological advancement
note: AI assisted content
Top comments (0)