"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:
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:
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
The above is the detailed content of Python Script for Stock Sentiment Analysis. For more information, please follow other related articles on the PHP Chinese website!