Sensex Simulation Engine

Simulating BSE SENSEX with news sentiment analysis

I wanted to explore how news sentiment impacts stock market movements. The BSE SENSEX (Bombay Stock Exchange Sensitive Index) is India's benchmark index, tracking 30 of the largest companies on the BSE. I thought it would be interesting to build a simulation engine that combines historical market data with news analysis to see if sentiment-driven trading could actually work.

Simulation dashboard showing portfolio performance, SENSEX movements, sentiment scores, and trade signals

Key Market Events (2025)

The simulation captures real market events that shaped the Indian stock market in 2025:


April 2025: Market Crash

April 2025 - Sensex crashed 2000 points amid global selloff fears

What happened: The BSE Sensex experienced its biggest single-day drop in months when concerns over US tariff policies triggered a global selloff. The crash was driven by fears that new US tariffs on Chinese goods would escalate into a trade war, impacting emerging markets like India.

Trading result: The portfolio followed the market down, but the stop-loss mechanism kicked in to limit losses.


May 2025: Sensex Rejig

May 2025 - Trent and Bharat Electronics added to Sensex

What happened: BSE announced a major reshuffle of the Sensex index. Trent (Tata Group retail arm) and Bharat Electronics (defense) replaced IndusInd Bank and Nestle India. This reflected the shift toward defense and retail sectors in India's economic narrative.

Trading result: Trent surged 10% on the inclusion news. Our sentiment model correctly picked up the positive news flow, generating buying opportunities.


October 2025: RBI Rate Cut

October 2025 - RBI unexpectedly cuts repo rate, Sensex hits 85,000

What happened: In a surprise move, the Reserve Bank of India cut the repo rate by 25 basis points, signaling a shift toward growth priorities. The Sensex surged to a new all-time high of 85,000 on the rate cut decision.

Trading result: Strong positive sentiment from the rate cut decision triggered multiple buy signals, capturing the rally.


December 2025: Year-End Rally

December 2025 - Diwali festival and year-end optimism drive markets

What happened: The year ended on a high note with the Sensex gaining 9% in 2025. The Diwali festival season boosted consumer spending sentiment, while strong domestic institutional investor (DII) flows offset foreign investor selling.

Trading result: The final month showed strong positive sentiment, with the portfolio ending the year in profit.


The Core Problem

Traditional trading strategies rely on technical indicators and fundamental analysis. But in reality, market movements are heavily influenced by news and public sentiment. A single negative news story about the economy can send markets tumbling, while positive developments can fuel rallies.

This project attempts to quantify that relationship by:

  1. Fetching historical SENSEX data
  2. Collecting financial news relevant to the Indian market
  3. Analyzing news sentiment
  4. Simulating trades based on sentiment signals

Architecture

The engine is built with four main components:

  • Data Fetcher (data_fetcher.py): Retrieves historical BSE SENSEX data using Yahoo Finance's yfinance library. It handles data cleaning, date range selection, and caching to avoid repeated API calls.

  • News Fetcher (news_fetcher.py): Collects financial news articles from NewsAPI. It searches for articles related to the Indian stock market, banking sector, and economy. Results are cached locally to respect API rate limits.

  • Sentiment Analyzer (sentiment_analyzer.py): Processes news articles to determine market sentiment. This was the trickiest part - financial language is nuanced, and a negative article doesn't always mean the market will drop.

  • Simulation Engine (simulation_engine.py): The core logic that runs the trading simulation. It applies the trading strategy, tracks portfolio value, and calculates performance metrics.

Building the Sentiment Model

Analyzing financial news is surprisingly complex. I used a combination of approaches:

TextBlob provides polarity scores (-1 to 1) indicating positive or negative sentiment. It's simple but effective for a first pass.

VADER (Valence Aware Dictionary and sEntiment Reasoner) is specifically tuned for social media and news content. It handles things like capitalization (WHATEVER means more negative than whatever), exclamation marks, and modifiers like "very" or "slightly."

The final sentiment score combines both:

sentiment_impact = sentiment * sentiment_impact_factor
adjusted_return = base_return * (1 + sentiment_impact)

The sentiment_impact_factor is configurable (default 0.05), allowing you to control how much weight sentiment has on price movements.

Trading Strategy

The simulation uses a rule-based trading strategy with several components:

Position Sizing: Uses 10% of total portfolio value per trade, with a maximum 70% market exposure to maintain diversification.

Buy Signals: When sentiment is positive (> 0.1) and we have sufficient cash reserves (> 20%), the strategy buys SENSEX units.

Sell Signals: Negative sentiment (< -0.1) triggers selling, with the sell percentage proportional to how negative the sentiment is (up to 50% of holdings).

Risk Management:

  • Trailing Stop Loss: If portfolio value drops more than 5% from the peak, 30% of holdings are sold
  • Take Profit: When gains exceed 10%, 20% of holdings are sold to lock in profits
  • Cash Reserve: Maintains at least 20% in cash at all times

Performance Metrics

The simulation calculates comprehensive metrics:

  • Total Return — Overall percentage gain/loss
  • Annualized Return — Return normalized to yearly basis
  • Volatility — Standard deviation of daily returns (annualized)
  • Sharpe Ratio — Risk-adjusted return (assuming 4% risk-free rate)
  • Max Drawdown — Largest peak-to-trough decline
  • Win Rate — Percentage of profitable days

Actual Results

Running a 1-year simulation (Feb 2025 - Feb 2026) with real SENSEX data and sentiment-driven trading:

  • Initial Investment: ₹10,00,000
  • Final Portfolio: ₹1,022,097
  • Total Return: +2.21%
  • Max Drawdown: -2.62%
  • Volatility: 4.79%
  • Total Trades: 25 (13 buys, 12 sells)
  • News Articles Analyzed: 83

Sample Output

Running the simulation generates two output files:

CSV Results (simulation_results.csv): Contains daily data including price, sentiment, portfolio value, holdings, and returns.

Interactive HTML Plot (simulation_results.html): A Plotly visualization with four panels:

  1. Portfolio value over time with initial investment reference
  2. SENSEX price movements with buy/sell markers
  3. Sentiment scores (green = positive, red = negative)
  4. Trade actions timeline

Running the Simulation

# Clone and setup
git clone https://github.com/Araon/Sensex-Simulation-Engine
cd Sensex-Simulation-Engine

# Create virtual environment
python -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Add your NewsAPI key
echo "NEWS_API_KEY=your_key_here" > .env

# Run with defaults (30 days, 10 lakh INR)
python main.py

# Run custom simulation
python main.py --days 90 --initial 2000000 --sentiment-impact 0.1

# Compare: run without sentiment analysis
python main.py --no-news

Interesting Findings

A few things I discovered while running simulations:

  1. Sentiment alone isn't enough: The pure sentiment strategy underperforms in volatile markets. Combining it with technical stop-losses improves results significantly.

  2. News latency matters: By the time news becomes "news," the market may have already priced it in. Real-time sentiment analysis would be more effective.

  3. Source weighting helps: Not all news sources are equal. Weighting by source reliability improves prediction accuracy.

  4. The 5% rule: A 5% drawdown trigger works well for Indian markets - aggressive enough to protect gains, but not so sensitive that it triggers false alarms.

Future Enhancements

There are several directions this could go:

  • Machine Learning: Replace the rule-based strategy with an LSTM or transformer model trained on historical sentiment data
  • Real-time API: Add WebSocket support for live sentiment analysis
  • Multi-asset Support: Extend to NIFTY 50, sector-specific indices, or individual stocks
  • Backtesting Framework: Add proper statistical backtesting with confidence intervals
  • Sentiment Aggregation: Include social media (Twitter/X, Reddit) for more comprehensive sentiment tracking

Tech Stack

  • Python 3.7+: Core language
  • yfinance: Historical market data
  • NewsAPI: Financial news fetching
  • TextBlob & NLTK: Sentiment analysis
  • pandas & numpy: Data processing
  • plotly: Interactive visualizations

The project is a starting point for exploring algorithmic trading based on sentiment analysis. It's not production-ready (would need more robust risk management, real-time data feeds, and proper backtesting), but it's a solid foundation for experimentation.

Tags

Python
Financial Analysis
Sentiment Analysis
Trading

Contact

Need more project details, or interested in working together? Reach out to me directly at ayy.soumik@gmail.com. I'd be happy to connect!

← All Projects