CodeForFinance
Python Tutorial

Stock Sentiment Analysis with Python

Analyse financial news sentiment using NLP to gauge market mood around specific stocks.

Install

pip install textblob requests beautifulsoup4 pandas

Scrape Headlines

from bs4 import BeautifulSoup
import requests
import pandas as pd

# Scrape financial headlines (example: Yahoo Finance)
url = "https://finance.yahoo.com/quote/AAPL/news/"
headers = {"User-Agent": "Mozilla/5.0"}
resp = requests.get(url, headers=headers)
soup = BeautifulSoup(resp.text, "html.parser")

headlines = [h.text for h in soup.find_all("h3") if h.text.strip()]
print(f"Found {len(headlines)} headlines")
for h in headlines[:5]:
    print(f"  - {h}")

Sentiment Scoring

from textblob import TextBlob

results = []
for headline in headlines:
    blob = TextBlob(headline)
    results.append({
        "headline": headline[:80],
        "polarity": round(blob.sentiment.polarity, 3),
        "mood": "Bullish" if blob.sentiment.polarity > 0.1 else "Bearish" if blob.sentiment.polarity < -0.1 else "Neutral"
    })

df = pd.DataFrame(results)
print(df.to_string(index=False))
print(f"
Overall sentiment: {df['polarity'].mean():.3f}")

Developer Essentials

As an Amazon Associate we may earn from qualifying purchases.