Historical Data for Backtesting¶

Open In Colab

Pull 2 years of NIFTY daily closes for the backtests that follow.

Part 13 of 20 in the ServLoci algo/options trading notebook series — full index in notebooks/README.md.

Setup¶

# Get your dedicated static IPv6 + SOCKS5 credentials free:
#   https://comm.servloci.in/register        (or /auth/google?free=1 for an instant trial)
# Your api_key / api_secret pair shows up in the portal after signup:
#   https://comm.servloci.in/user
!pip install -q "requests[socks]"
!curl -sL https://comm.servloci.in/sdk/servloci.py -o servloci.py

import os
from servloci import ServLoci

SERVLOCI_API_KEY = os.environ.get("SERVLOCI_API_KEY", "dhan:1000000001")   # broker:client_id
SERVLOCI_API_SECRET = os.environ.get("SERVLOCI_API_SECRET", "")            # from the portal — leave blank to run this notebook in demo mode

sl = None
if SERVLOCI_API_SECRET:
    sl = ServLoci(api_key=SERVLOCI_API_KEY, api_secret=SERVLOCI_API_SECRET)
    print("ServLoci configured:", sl.host, sl.port)
else:
    print("SERVLOCI_API_SECRET not set — running in demo mode (no live proxy calls).")

Pulls historical NIFTY closes for the backtesting notebooks that follow. No ServLoci proxy needed — Yahoo Finance is publicly reachable.

!pip install -q yfinance
import yfinance as yf

nifty = yf.download("^NSEI", period="2y", interval="1d", progress=False)
nifty.to_csv("nifty_2y.csv")
print(nifty.tail())

nifty_2y.csv is reused by notebooks 14 and 17 — re-run this cell first if you're opening those standalone.


« Previous: Implied Volatility Skew
Next: Backtest: Weekly Short Straddle »

Try the concepts above interactively: Options Strategy Builder · Docs · Get your static IP