Building a Market Sentiment Index with Python

python sentiment trading

What Is a Sentiment Index?

A sentiment index distills the health of an entire stock universe into a single number. Instead of tracking individual stocks, you scan hundreds of them — checking whether each is bullish or bearish — and then express the result as a percentage or score.

The Approach

For each stock in the universe (e.g., Nifty Total Market), compute a trend indicator like KAMA on both weekly and daily timeframes. Classify each stock:

Calculating the Index

The sentiment index is simply the ratio of bullish stocks to the total stocks scanned, expressed as a percentage. A reading above 60% suggests broad market strength; below 40% signals widespread weakness. Tracking this daily reveals shifts in market breadth before major indices react.

Why Python?

Python’s ecosystem — yfinance for data, pandas for computation, and csv for output — makes it straightforward to build this as a lightweight daily script. No heavy infrastructure needed, just a single file you can run with uv run.

Key Insight

The sentiment index acts as a leading indicator. When individual stocks quietly shift from bearish to bullish, the index picks it up days before the headline indices move — giving you an edge in timing your exposure.