Leveraging Python for Sentiment Analysis of Financial News

Kenneth Gordon
4 min readJan 25, 2024

--

In the realm of financial markets, where news travels at the speed of light and every piece of information could be the key to your next big decision, wouldn’t it be great if you could quickly gauge the mood of the financial world? Imagine having a little assistant that reads through the lines of complex financial news and tells you, “Hey, things are looking up!” or perhaps, “Hmm, the outlook isn’t too bright.” Well, guess what? With a pinch of Python programming, you can create just that!

Why Sentiment Analysis?

Sentiment analysis is like having a weather forecast for market trends. Just as you’d carry an umbrella on a cloudy day, understanding market sentiment helps you prepare for your financial journey. It’s not about predicting the future; it’s about understanding the present mood — whether it’s optimism in the air or a bit of skepticism.

The Magic Behind the Curtain

To make this happen, we’re going to use some fantastic tools from the world of Python programming. Don’t worry if you’re not a tech wizard; think of this as a simple recipe we’re following. Our ingredients? A dash of feedparser to grab news from the vast internet ocean, and a generous helping of transformers (not the robots, but almost as cool) for our sentiment analysis.

Fetching News Like a Pro

First things first, we need to get our hands on the latest financial news. With feedparser, it's like subscribing to your favorite magazine, but instead of waiting for the mail, the news comes directly to our script:

import feedparser

def fetch_news_from_rss(feed_url):
# Imagine opening a treasure chest of news articles
news_feed = feedparser.parse(feed_url)
news_items = []
for entry in news_feed.entries:
# For each precious article, we save the title and where to find it
news_items.append({'title': entry.title, 'link': entry.link})
return news_items

Deciphering Sentiments

Now, onto the exciting part: figuring out the mood of each article with transformers. We're using a special model called ProsusAI/finbert — think of it as a highly educated parrot that can read text and tell you if it's happy, sad, or meh:

from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch

def analyze_sentiment(news_text):
# We introduce our text to FinBERT, our friendly sentiment analyzer
model_name = "ProsusAI/finbert"
model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)

# Like magic, it reads and understands the mood
inputs = tokenizer(news_text, return_tensors="pt", padding=True, truncation=True, max_length=512)
with torch.no_grad():
outputs = model(**inputs)
prediction = torch.argmax(outputs.logits, dim=1)
sentiment_labels = ['positive', 'negative', 'neutral']
sentiment = sentiment_labels[prediction.item()]

return sentiment

Let’s put our script to work. We’ll fetch some news and see what our sentiment analyzer thinks about them. Here’s how we tie everything together:

# Where we get our news from
feed_url = 'http://feeds.marketwatch.com/marketwatch/topstories/'
news_items = fetch_news_from_rss(feed_url)

# Let's check the sentiment of the first 5 news items
for item in news_items[:5]:
sentiment = analyze_sentiment(item['title'])
print(f"Title: {item['title']}\nSentiment: {sentiment}\nLink: {item['link']}\n")
Title: IBM’s ‘accelerating’ AI demand helps power stock higher after earnings
Sentiment: positive
Link: https://www.marketwatch.com/story/ibms-accelerating-ai-demand-helps-power-stock-higher-after-earnings-6d501f8c?mod=mw_rss_topstories

Title: ServiceNow’s stock dips despite strong subscription sales, revenue jump as AI products gain hold
Sentiment: negative
Link: https://www.marketwatch.com/story/servicenows-stock-rises-on-strong-subscription-sales-revenue-jump-as-ai-products-gain-hold-48e9e187?mod=mw_rss_topstories

Title: FAA halts production expansion of Boeing’s Max jets — but clears inspection process to resume Max 9 flights
Sentiment: negative
Link: https://www.marketwatch.com/story/faa-halts-production-expansion-on-boeings-max-jets-9c441139?mod=mw_rss_topstories

Title: I asked my elderly father to quitclaim his home so I can refinance it — and take out a $200,000 annuity for my sister and me. Is this a good idea?
Sentiment: neutral
Link: https://www.marketwatch.com/story/i-want-my-father-to-quitclaim-his-home-so-i-can-refinance-it-and-take-out-a-200-000-annuity-for-my-sister-and-me-is-this-wise-0265aaff?mod=mw_rss_topstories

Title: My Tinder match asked if I ‘rent or own’ my apartment. Is it gauche to ask financial questions before a first date?
Sentiment: neutral
Link: https://www.marketwatch.com/story/my-tinder-match-asked-if-i-rent-or-own-my-apartment-is-it-gauche-to-ask-financial-questions-before-a-first-date-240ddd3d?mod=mw_rss_topstories

Wrap-Up

And there you have it! A simple yet effective way to keep a finger on the pulse of the financial world’s mood. This guide isn’t just about coding; it’s about empowering yourself with knowledge, making informed decisions, and maybe having a little fun along the way. Dive in, play around with the code, and see what insights you can uncover. Who knows? Your next great investment decision might just be a sentiment analysis away!

--

--

Kenneth Gordon

Data lover solving problems with Python, Power Platform & data science. Always seeking challenges & turning data into actionable insights.