Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

smartapi-algo — an honest algo-trading research pipeline for Indian markets

A complete, working framework for Angel One SmartAPI (NSE F&O) plus crypto research — built around one idea most trading code avoids: make it impossible to fool yourself.

Five strategy families went through this pipeline's pre-committed gates. All five failed. That is the deliverable. The same machinery that produced a seductive +375% / Sharpe 1.72 ten-year backtest also proved the strategy lost -22% over 16 months of data the research had never seen — before a single rupee was risked.

The scoreboard (all walk-forward, full costs, pre-committed gates)

Family Data In-sample story Honest out-of-sample verdict
ORB intraday (NIFTY futures, 15-min) 2015-2026 +375%, Sharpe 1.72, maxDD -7.6% -22.5% over 16 unseen months; win rate 41%→33%, maxDD -26%
Cross-sectional stock momentum (78 NSE large caps) 2007-2026 "Beats NIFTY" (Sharpe 0.77 vs 0.61) Loses to the equal-weight basket (1.04) — the "alpha" was survivorship + EW tilt
Index/sector rotation (18 NSE indices) 2007-2026 +66%, +46%, +33% years in 2021-24 Sharpe 0.42 vs 0.62 benchmark, maxDD -67% — the hot streak was regime luck
Crypto momentum (43 coins, XS + trend) 2018-2026 Negative gross (XS -13%/yr); after India's no-offset tax, everything deeply negative
Crypto funding carry (10 majors, delta-neutral) 2019-2026 Sharpe 6-9 gross, 8-11%/yr Real yield, but 5.6-7.3%/yr after Indian tax — FD-class return carrying exchange tail risk (SOL: one -17% funding day)

Benchmark that beat them all: NIFTY buy & hold — Sharpe 0.71, 11.2%/yr over the test window. Even deliberately overfit "hindsight best" configurations could not beat it. SEBI's studies agree from the other side: 91% of individual F&O traders lost money in FY25 (₹1.05 lakh crore net); 93% over FY22-24.

Why this pipeline is different

  • Anti-lookahead engine. Decisions use information through close[t], execution at open[t+1], returns measured open-to-open. Lookahead bias is structurally impossible, not just avoided.
  • Walk-forward everything. Parameters are re-picked each test year from prior data only. Nothing is judged on data it was fit to.
  • Overfitting is measured, not hidden. Every study also reports its "hindsight best" configuration — a deliberate overfit upper bound — so you can see exactly how much of a backtest is mirage.
  • Real Indian frictions. Brokerage, STT, exchange fees, GST, stamp duty, slippage — and for crypto, the Section 115BBH layer: 30% on every gain with no loss offset, which makes holding structurally beat trading in India. This pipeline quantifies that.
  • Pre-committed gates. Pass/fail criteria are printed by the runners before results exist, and never softened afterward.
  • Survivorship-aware benchmarks. Stock/coin universes are judged against their own equal-weight basket (same bias), not just the index.

Battle scars (production details that took real debugging)

  • Client-side rate limiting tuned to Angel One's published caps (orders 20/s, 500/min, 1,000/hr; quotes 10/s; candles 3/s).
  • Survives the April 2026 SmartAPI portal migration: legacy apps silently deleted, static-IP bindings orphaned ("Primary static IP is already associated with another app"), and keys that still pass login but fail every data call with AG8004 — because generateSession does not validate the API key. Complete fix path documented in this repo's history.
  • Mock-session guard: NSE Saturday DR-drill sessions serve dummy prices (~10% off) through the candle API as if real. The fetcher detects and drops them while keeping genuine Muhurat/Budget-day weekend sessions.
  • Windows-first UX: every step is a double-clickable .bat with a log.

Project layout

smartapi-algo/
├── config.yaml            # every setting: capital, strategy, risk, costs
├── .env.example           # credential template -> copy to .env (never commit)
├── run_backtest.py        # offline backtest, no credentials needed
├── run_paper.py           # live data, fake money (market hours)
├── run_live.py            # real money — double safety-catch (see below)
├── run_research.py        # full walk-forward study, 6 families + ML
├── run_research_xs.py     # cross-sectional stock momentum study
├── run_research_rot.py    # index/sector rotation study
├── run_research_crypto.py # crypto momentum + funding carry, India after-tax
├── fetch_recent.py/.bat   # NSE index + current future, 15-min candles
├── fetch_universe.py/.bat # 78 NSE large caps, daily
├── fetch_indices.py/.bat  # 18 NSE indices, daily
├── fetch_crypto.py/.bat   # Binance spot + funding (public API, no keys)
├── validate_orb.py        # run any CSV through the LIVE event engine
├── verify_setup.bat       # one-click: deps → backtest → API test → data
│                          #   → out-of-sample validations, all logged
├── src/                   # broker wrapper, risk manager (kill switch),
│                          #   costs, event engine, data, paper/live engine
└── research/              # vectorized engine, walk-forward, cross-
                           #   sectional, crypto + after-tax layer

Setup

python3 -m venv venv && source venv/bin/activate   # Windows: venv\Scripts\activate
pip install -r requirements.txt

The three-stage discipline

1. Backtest (run_backtest.py, zero risk, zero credentials) — synthetic data proves the machinery; real fetched history judges the strategy.

2. Paper trade (run_paper.py, live market, fake money) — 3-4 weeks minimum. If paper diverges from backtest, the strategy or cost assumptions are wrong; go back. That outcome is the system working.

3. Live (run_live.py) — two deliberate safety catches: hand-edit live.enabled: true in config.yaml, then type the confirmation phrase. Nothing in this repository has passed the gates that would justify this step. The risk manager (1% per-trade sizing, max lots, 6-trade/day cap, -3% daily kill switch, forced 15:15 square-off) behaved exactly as designed in every test.

Adding your own strategy

Subclass Strategy in src/strategy.py, implement on_bar() returning -1/0/+1, register in make(), select in config.yaml. Then walk the stages in order — and write your pass/fail gate down before you look at results.

Disclaimer

Educational and research software. Not investment advice and not a recommendation; no warranty. F&O trading can lose more than your capital; Indian tax and SEBI/NSE regulations apply to any live use. The author's research conclusion: for a retail trader, nothing tested here beat holding the index — and knowing that before deploying capital is the product.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages