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.
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
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.
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.
Z-Score <= Entry Threshold
Z-Score >= Exit Threshold
Entry and exit thresholds, as well as the rolling lookback period, can be configured through the Streamlit dashboard.
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
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.
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 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.
The project includes an interactive Streamlit dashboard with four major sections.
The Overview page provides a high-level strategy performance summary.
- Net Profit
- Win Rate
- Sharpe Ratio
- Profit Factor
Benchmark and Z-Score results are compared across:
- Net Profit
- Win Rate
- Sharpe Ratio
- Profit Factor
- Maximum Drawdown
- Trades
- Z-Score Equity Curve
- Z-Score Drawdown
- Benchmark vs Z-Score Equity Comparison
The dashboard dynamically summarizes the selected Z-Score strategy results.
The Analytics section provides deeper performance analysis.
Displays:
- Net Profit
- Sharpe Ratio
- Maximum Drawdown
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 Net Profit is displayed through a bar chart with year-level performance insights.
The dashboard highlights:
- Best Year
- Lowest Yearly Profit
- Average Yearly Profit
- Profitable Years
Shows the cumulative Net P&L of the Z-Score strategy over time.
Displays:
- Final Equity
- Peak Equity
- Maximum Equity Drawdown
Shows the decline from previous cumulative equity peaks.
Displays:
- Total Trades
- Winning Trades
- Losing Trades
- Average Trade P&L
- Best Trade
- Worst Trade
- Average Holding Period
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
The trade log can be filtered by:
All Trades
Benchmark
Z-Score
The summary cards automatically update according to the selected strategy.
The dashboard provides:
- Total Trades
- Winning Trades
- Losing Trades
- Net P&L
The filtered Trade Log can be downloaded as a CSV file.
The Validation section evaluates strategy robustness from multiple perspectives.
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.
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.
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.
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
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.
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.
- Python
- Pandas
- NumPy
- Matplotlib
- Plotly
- Streamlit
- nsepython
- yfinance
git clone https://github.com/kaustubhmakashir24/Nifty-Calendar-Spread-Backtesting.gitcd Nifty-Calendar-Spread-Backtestingpip install -r requirements.txtpython -m streamlit run app.pyThe dashboard will open in your browser.
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.
The project uses multiple validation perspectives rather than relying on a single historical performance number.
Tests whether results remain attractive across different Entry Z-Score values.
Tests whether profitability survives higher brokerage assumptions.
Evaluates strategy behavior independently across historical calendar years.
These analyses help identify whether performance is concentrated around a single parameter or historical period.
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.
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.
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
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
Kaustubh Makashir
GitHub:
https://github.com/kaustubhmakashir24
LinkedIn:
https://www.linkedin.com/in/kaustubh-makashir-bb1198219/
This project is released under the MIT License.