Skip to content

Repository files navigation

NIFTY Calendar Spread Backtesting Engine

Live Demo

Launch the NIFTY Calendar Spread Backtesting Dashboard

A Python-based quantitative research and backtesting framework for evaluating NIFTY Futures Calendar Spread strategies.

The project compares a Benchmark Monthly Roll Strategy with a Z-Score-based mean-reversion strategy and provides performance analytics, trade-level analysis, parameter sensitivity testing, transaction-cost stress testing, and year-wise validation through an interactive Streamlit dashboard.

Research project: All results are historical backtest results generated under the assumptions implemented in the code. Historical performance does not guarantee future results.


Overview

Calendar spreads involve offsetting futures positions across different expiries. This project studies the behavior of NIFTY Futures calendar spreads and evaluates whether statistically extreme spread values can provide mean-reversion opportunities.

The framework covers the complete workflow:

  • Historical NIFTY Futures data processing
  • Calendar spread construction
  • Rolling statistical feature engineering
  • Benchmark strategy evaluation
  • Z-Score mean-reversion strategy
  • Dynamic historical NIFTY lot-size handling
  • Transaction-cost modelling
  • Look-ahead bias mitigation
  • Performance and risk analytics
  • Trade-level analysis
  • Parameter sensitivity analysis
  • Transaction-cost stress testing
  • Year-wise validation
  • Interactive Streamlit dashboard

Strategy Methodology

Calendar Spread

The framework constructs a calendar spread between NIFTY Futures contracts with different expiries.

The resulting spread is treated as a time series and used for statistical analysis and strategy generation.

Z-Score Mean Reversion

The strategy uses a rolling Z-Score to measure how far the current spread is from its recent mean.

The standard Z-Score formulation is:

[ Z = \frac{x-\mu}{\sigma} ]

where:

  • x = current spread value
  • μ = rolling mean
  • σ = rolling standard deviation

Extreme deviations from the rolling mean are treated as potential mean-reversion opportunities.

Entry Rule

Z-Score <= Entry Threshold

Exit Rule

Z-Score >= Exit Threshold

Entry and exit thresholds, as well as the rolling lookback period, can be configured through the Streamlit dashboard.


Benchmark Strategy

The project includes a benchmark monthly calendar-spread roll strategy.

The benchmark provides a baseline against which the statistical Z-Score strategy can be evaluated.

This makes it possible to compare:

  • Profitability
  • Win rate
  • Profit factor
  • Sharpe ratio
  • Maximum drawdown
  • Number of trades

Look-Ahead Bias Mitigation

The backtesting engine uses historical signal information and the following-day execution logic implemented in the strategy code.

This is intended to prevent the strategy from using future market information that would not have been available at the time the trading decision was made.


Dynamic NIFTY Lot Size

The backtesting engine applies the historical NIFTY Futures lot size associated with the trade date.

This prevents the entire historical dataset from being incorrectly evaluated using a single fixed contract size.

The gross P&L calculation follows the general structure:

Spread Price Difference × Applicable Lot Size

Transaction costs are then deducted to obtain Net P&L.


Transaction Costs

Transaction costs are incorporated directly into trade-level P&L calculations.

The framework also provides a transaction-cost stress test that evaluates how strategy profitability changes as brokerage assumptions increase.

This helps assess whether the strategy's profitability is highly dependent on optimistic transaction-cost assumptions.


Streamlit Dashboard

The project includes an interactive Streamlit dashboard with four major sections.

1. Overview

The Overview page provides a high-level strategy performance summary.

Key performance metrics

  • Net Profit
  • Win Rate
  • Sharpe Ratio
  • Profit Factor

Strategy comparison

Benchmark and Z-Score results are compared across:

  • Net Profit
  • Win Rate
  • Sharpe Ratio
  • Profit Factor
  • Maximum Drawdown
  • Trades

Visual analysis

  • Z-Score Equity Curve
  • Z-Score Drawdown
  • Benchmark vs Z-Score Equity Comparison

Strategy Summary

The dashboard dynamically summarizes the selected Z-Score strategy results.


2. Analytics

The Analytics section provides deeper performance analysis.

Performance Overview

Displays:

  • Net Profit
  • Sharpe Ratio
  • Maximum Drawdown

Monthly Performance

A Year × Month heatmap is used to visualize monthly Net P&L.

  • Green indicates positive performance.
  • Red indicates negative performance.
  • Neutral cells represent zero or no recorded monthly P&L.

Yearly Performance

Yearly Net Profit is displayed through a bar chart with year-level performance insights.

Yearly Performance Insights

The dashboard highlights:

  • Best Year
  • Lowest Yearly Profit
  • Average Yearly Profit
  • Profitable Years

Cumulative Equity Curve

Shows the cumulative Net P&L of the Z-Score strategy over time.

Equity Curve Insights

Displays:

  • Final Equity
  • Peak Equity
  • Maximum Equity Drawdown

Drawdown Analysis

Shows the decline from previous cumulative equity peaks.

Trade Statistics

Displays:

  • Total Trades
  • Winning Trades
  • Losing Trades
  • Average Trade P&L
  • Best Trade
  • Worst Trade
  • Average Holding Period

3. Trade Log

The Trade Log provides detailed trade-level information.

Available fields include:

  • Strategy
  • Entry Date
  • Exit Date
  • Entry Spread
  • Exit Spread
  • Gross P&L
  • Transaction Cost
  • Net P&L
  • Lot Size
  • Holding Days

Strategy Filter

The trade log can be filtered by:

All Trades
Benchmark
Z-Score

The summary cards automatically update according to the selected strategy.

Trade Log Summary

The dashboard provides:

  • Total Trades
  • Winning Trades
  • Losing Trades
  • Net P&L

Export

The filtered Trade Log can be downloaded as a CSV file.


4. Strategy Validation

The Validation section evaluates strategy robustness from multiple perspectives.

Parameter Sensitivity

Multiple Entry Z-Score values are evaluated to understand how changes in the entry threshold affect strategy performance.

Metrics include:

  • Trades
  • Win Rate
  • Net Profit
  • Profit Factor
  • Sharpe Ratio
  • Maximum Drawdown

The dashboard also provides an Entry Z-Score vs Net Profit chart and automatically identifies key parameter results.

Transaction Cost Stress Test

The strategy is evaluated under different brokerage assumptions.

Metrics include:

  • Brokerage
  • Trades
  • Net Profit
  • Profit Factor
  • Sharpe Ratio
  • Maximum Drawdown

A Brokerage vs Net Profit chart illustrates the impact of increasing trading costs.

Year-wise Validation

The strategy is independently evaluated across historical calendar years.

The dashboard displays:

  • Trades
  • Win Rate
  • Net Profit
  • Profit Factor
  • Sharpe Ratio
  • Maximum Drawdown

It also provides year-wise performance visualization and summary insights.

Methodology note: The current implementation performs independent year-by-year strategy evaluations. It is therefore described as Year-wise Validation, rather than a formal rolling train/test walk-forward optimization framework.


Performance Metrics

The project calculates and/or displays several trading performance measures, including:

  • Trades
  • Win Rate
  • Gross Profit
  • Gross Loss
  • Net Profit
  • Average Trade
  • Largest Win
  • Largest Loss
  • Profit Factor
  • Sharpe Ratio
  • Maximum Drawdown
  • Holding Period Statistics

Example Backtest Results

The following values represent an example Z-Score strategy run shown in the dashboard:

Metric Z-Score Strategy
Trades 32
Win Rate 75.00%
Net Profit ₹21,838.78
Profit Factor 6.91
Sharpe Ratio 3.44
Maximum Drawdown ₹1,248.56

These values depend on the selected strategy parameters, historical dataset, transaction-cost assumptions, and historical lot-size rules.

They should be interpreted as backtest results under the implemented assumptions, not as expected future returns.


Project Structure

Nifty-Calendar-Spread-Backtesting/
│
├── app.py
├── main.py
├── README.md
├── LICENSE
├── requirements.txt
├── .gitignore
│
├── data/
│   └── NIFTY_MASTER_MERGED.csv
│
├── charts/
│   ├── benchmark_equity_curve.png
│   ├── benchmark_drawdown.png
│   ├── z-score_equity_curve.png
│   └── z-score_drawdown.png
│
├── outputs/
│   ├── benchmark_results.csv
│   ├── monthly_performance.csv
│   ├── parameter_sensitivity.csv
│   ├── strategy_comparison.csv
│   ├── stress_test.csv
│   ├── trade_log.csv
│   ├── walk_forward_validation.csv
│   ├── yearly_performance.csv
│   └── zscore_results.csv
│
└── src/
    ├── config.py
    ├── data_loader.py
    ├── feature_engineering.py
    ├── metrics.py
    ├── plots.py
    ├── strategies.py
    ├── utils.py
    └── validation.py

The current implementation may also generate certain CSV outputs at the repository root.


Technologies Used

  • Python
  • Pandas
  • NumPy
  • Matplotlib
  • Plotly
  • Streamlit
  • nsepython
  • yfinance

Installation

1. Clone the repository

git clone https://github.com/kaustubhmakashir24/Nifty-Calendar-Spread-Backtesting.git

2. Navigate to the project directory

cd Nifty-Calendar-Spread-Backtesting

3. Install dependencies

pip install -r requirements.txt

4. Launch the Streamlit dashboard

python -m streamlit run app.py

The dashboard will open in your browser.


Using the Dashboard

Configure the strategy from the sidebar using:

  • Entry Z-Score
  • Exit Z-Score
  • Lookback Period
  • Brokerage

Then select:

Run Backtest

The dashboard recalculates the strategy and updates all performance, analytics, trade-log, and validation views.


Validation Framework

The project uses multiple validation perspectives rather than relying on a single historical performance number.

Parameter Sensitivity

Tests whether results remain attractive across different Entry Z-Score values.

Transaction Cost Stress Testing

Tests whether profitability survives higher brokerage assumptions.

Year-wise Validation

Evaluates strategy behavior independently across historical calendar years.

These analyses help identify whether performance is concentrated around a single parameter or historical period.


Results and Interpretation

The main purpose of the framework is not simply to maximize historical profit.

The dashboard evaluates the strategy across multiple dimensions:

Profitability
     +
Risk-adjusted performance
     +
Drawdown
     +
Trade behavior
     +
Parameter sensitivity
     +
Transaction costs
     +
Historical consistency

A strategy should therefore be evaluated using the complete set of metrics rather than Net Profit alone.


Limitations

This is a quantitative research and backtesting project. It has several limitations.

  • Historical performance does not guarantee future performance.
  • Slippage is not modelled as a dedicated execution component.
  • Market impact is not explicitly modelled.
  • Real-world execution may differ from the assumptions used in the backtest.
  • Brokerage and transaction costs may differ across brokers and market conditions.
  • The current year-wise validation method is not a formal rolling train/test walk-forward optimization framework.
  • The strategy is evaluated using historical NIFTY Futures data.

Future Improvements

Potential extensions include:

  • Formal rolling walk-forward optimization
  • Slippage modelling
  • Market-impact modelling
  • Position sizing
  • Portfolio-level risk management
  • Monte Carlo simulation
  • Parameter optimization
  • Multi-asset calendar spread strategies
  • Risk-adjusted portfolio optimization
  • More realistic execution modelling

Key Learnings

This project provided practical experience in:

  • Quantitative trading strategy development
  • Calendar spread construction
  • Statistical mean-reversion modelling
  • Time-series feature engineering
  • Backtesting methodology
  • Look-ahead bias mitigation
  • Transaction-cost modelling
  • Dynamic contract sizing
  • Performance analytics
  • Strategy comparison
  • Robustness testing
  • Interactive financial dashboard development

Author

Kaustubh Makashir

GitHub:
https://github.com/kaustubhmakashir24

LinkedIn:
https://www.linkedin.com/in/kaustubh-makashir-bb1198219/


License

This project is released under the MIT License.

About

Python-based quantitative backtesting framework for NIFTY Futures Calendar Spread strategies with benchmark comparison, statistical mean-reversion, parameter sensitivity analysis, transaction cost stress testing, and year-wise walk-forward evaluation.

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Contributors

Languages