# backtest-lab

Adopt this skill: https://proskills.md/skills/other/shubhamkumartrichy-claude-trading-skills-india-skills-backtest-lab

Page: https://proskills.md/skills/other/shubhamkumartrichy-claude-trading-skills-india-skills-backtest-lab
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skills/backtest-lab/SKILL.md
size: 10598
sha: 3c197bf57b2075522656cb0069c0585f41e86f0c
upstream: https://github.com/shubhamkumartrichy/claude-trading-skills-india/blob/main/skills/backtest-lab/SKILL.md

````text
---
name: backtest-lab
description: |
  Backtests rule-based swing ideas on NSE/BSE daily bars with Indian frictions built in: decide on
  the close and fill at the next open, gap-through stops, slippage, exact per-trade charges by
  segment and broker (STT, stamp duty, GST, DP), whole shares or lots, circuit-band no-fills,
  futures-only shorts and an optional STCG/LTCG estimate. Six built-in strategies; CAGR vs
  buy-and-hold, drawdown, Sharpe/Sortino, profit factor, expectancy in ₹ and R; parameter sweeps
  with a plateau-or-spike read, walk-forward and Monte Carlo. backtest.py, stdlib only, offline.

  Use when the user asks: "backtest this strategy", "would a 20/50 crossover have worked on X",
  "is this edge real or curve-fit", "optimise my parameters", "walk-forward test", "Monte Carlo my
  trades", "what drawdown should I expect", "do charges kill this idea", "does a NIFTY 200-DMA
  filter help", or before putting real money behind any mechanical rule.
---

# Backtest Lab

A backtest cannot prove an idea works. It can show quickly that an idea does not. Judge a rule set
by how little it degrades when Indian charges, overnight gaps, unseen years and bad luck are piled
on, and treat a spectacular first run as a reason for suspicion.

## Commands

```bash
python3 scripts/backtest.py strategies                                  # rules and defaults
python3 scripts/backtest.py run --csv tcs.csv --strategy sma-cross --params fast=20 slow=50
python3 scripts/backtest.py run --symbol POLYCAB --strategy 52w-high --risk-pct 1 --tax --trades-csv t.csv
python3 scripts/backtest.py run --csv hdfcbank.csv --strategy donchian-breakout --regime-csv nifty.csv
python3 scripts/backtest.py run --csv nifty.csv --strategy sma-cross --segment futures --lot-size 65 \
    --allow-short --leverage 3 --size-pct 300
python3 scripts/backtest.py sweep --csv tcs.csv --strategy sma-cross --grid fast=10,20,30 slow=50,100,200
python3 scripts/backtest.py walkforward --csv tcs.csv --strategy donchian-breakout \
    --grid entry_n=20,40,55 exit_n=10,20 --is-bars 756 --oos-bars 252
python3 scripts/backtest.py montecarlo --csv tcs.csv --strategy ema-pullback --sims 2000 --seed 7
python3 scripts/backtest.py montecarlo --from-trades t.csv --ruin-dd 25
```
Inputs follow `technical-analysis`: `--csv`, `--candles` (broker-MCP JSON, null candles skipped) or
`--symbol` (yfinance, `--period 10y`). `--start` sets the first trading day while earlier bars still
warm up the indicators. `--grid` also takes ranges (`fast=10:50:10`). Every command takes `--json`.
Bad input exits 2 with one `error:` line.

## Strategies (`--strategy`, override with `--params key=value`)

| Name | Rule (long side; shorts mirror it) | Defaults |
|---|---|---|
| sma-cross | fast SMA crosses above slow; out when back below | fast 20, slow 50, stop 3×ATR |
| ema-pullback | close above a rising trend EMA, low tags the EMA, close back above it | ema 20, trend 100, 2×ATR, target 2R, 20 bars |
| **rsi-reversion** | RSI(period) below buy_below while above the trend SMA; out above sell_above | 2, 10, 70, trend 200, 10 bars |
| donchian-breakout | close above the prior entry_n high; out below the prior exit_n low | 20 / 10, 2×ATR |
| bollinger-reversion | close below the lower band; out at the middle band | 20, k 2, trend 0 (off), 20 bars |
| 52w-high | close above the prior lookback-bar high; out below the exit SMA | 252, exit_ma 50, 2.5×ATR |

Every strategy also takes `stop_atr` (k × ATR14 from the fill), `stop_pct` (overrides it),
`target_r` and `max_hold` (bars), where 0 turns each one off. There is no custom-code hook: new
rules are added to the script as reviewed code.

## How orders and costs are simulated

- **No look-ahead.** Signals use bars up to and including the signal bar's close. The order fills at
  the next bar's open, never at the close that produced it.
- **Stops and targets** rest in the market. A gap through the level fills at the open (a stop at ₹101
  after a ₹96 open books ₹96). If one bar touches both, the stop is assumed to have filled first.
- **Slippage** `--slippage-bps` (default 5) on every fill. Use 15–30 for small caps.
- **Charges** come from `trading-costs` (charges.py) for each round trip, by `--segment
  delivery|intraday|futures` and `--broker`. A delivery buy sold the same day is charged as intraday.
- **Sizing**: `--size-pct` (default 100% of equity), `--risk-pct` (risk to the initial stop, the
  `position-sizing` method) or `--fixed-inr`. The size is set on the signal close, capped by the cash
  available at the fill, and rounded down to whole shares or whole `--lot-size` lots (futures, SME).
- **Intraday** turns each signal into a next-session open-to-close MIS trade.
- **Shorts** need `--segment futures --allow-short`. An Indian cash-market short has to be bought
  back the same session (SLB aside), so a multi-day short only exists as futures. Futures notional ≤
  equity × `--leverage`. Rollover, basis and margin calls are not modelled.
- **Circuits**: with `--circuit-band 2|5|10|20`, an open at the band limit gets no fill. The entry is
  skipped; an exit or stop waits for the next unlocked open. Each case is listed under order events.
- **Regime filter**: `--regime-csv nifty.csv` (or `--regime-symbol NIFTY`) allows longs only while the
  benchmark closes above its `--regime-ma` (200) SMA on the signal day, and shorts only below it.
- **Cash** earns nothing. Sharpe and Sortino subtract `--rf` (default 6.5% a year, about a liquid
  fund or T-bill; change it).
- **`--tax`** applies `indian-tax-for-traders` rates for a rough post-tax view: STCG 20% (held ≤12
  months), LTCG 12.5% above ₹1.25 lakh per FY, intraday and futures at `--slab-pct`, plus 4% cess.
  It is approximate: losses are not carried forward and STT is treated as deductible, which it is not.

## Reading the output

- **Versus buy-and-hold** (delivery, one round trip). A rule earns its keep with a better Sharpe or
  Calmar, or a much smaller drawdown, not just a higher return in a bull market.
- **Max drawdown and longest underwater stretch**: would you have kept following the rules through it?
- **Profit factor** (after charges) below 1.2 is thin. Above 2 on fewer than 30 trades is suspicious.
- **Expectancy**: about +0.2R or more after costs is worth a closer look. Breakeven trades (net ₹0)
  count as neither wins nor losses and do not end a losing streak.
- **Charges as % of gross profit** above 25% means costs, not the market, own the result.
- **Yearly table**: one great year carrying the whole test is regime luck.
- **Sweep**: *plateau* (neighbours keep ≥75% of the best score) is what you want. *Slope* means pick
  the middle of the good zone. *Spike* means curve-fit. The luck hurdle is the Sharpe the best of N
  zero-edge variants would show by chance; the best cell should clear it comfortably.
- **Walk-forward**: efficiency = out-of-sample CAGR ÷ mean in-sample CAGR. ≥0.5 holds up; below 0
  fails. Frequent parameter changes mean the "optimum" is noise.
- **Monte Carlo**: size for the 95th-percentile drawdown, not the backtest's one path. *bootstrap*
  varies the outcome; *shuffle* only reorders the trades (final equity is fixed, the path is not).

## Checklist: try to break the idea before it breaks your account

1. **Look-ahead**: can every input be known before the order? Today's high/low or close cannot
   trigger an entry today. Dividend-adjusted closes are not prices anyone traded at.
2. **Survivorship**: today's NIFTY 50 or a current screener list are winners by construction. Ten
   years on them flatters every long strategy. Add names that were dropped, delisted or merged, or
   test the index itself.
3. **Overfitting**: each extra grid cell is another lottery ticket. Keep grids coarse, insist on a
   plateau, walk forward, and leave the last 1–2 years untouched until the very end.
4. **Costs**: a delivery round trip at Zerodha costs about 0.24% of the position (STT 0.1% a side,
   stamp duty, DP charge). 100 full-size round trips a year is about 24% of capital before any edge.
   High-turnover ideas die here. Rerun at 2–3× slippage and on a costlier broker.
5. **Regime**: does it only work in 2020–21-style rallies? Check the yearly rows, add `--regime-csv`,
   and include a bad phase (2008, 2015–16, 2018 small caps, March 2020, late 2024–early 2025).
6. **Data**: Yahoo history usually adjusts splits and bonuses, but not always. Moves of 25% or more
   overnight are flagged; check them. Dividends are left out for both the strategy and buy-and-hold.
7. **Small samples**: under 30 trades is an anecdote. Run the same rules on several stocks and look
   at the spread of results, not the best one.
8. **Execution**: thin names lock at circuits and slip more (`--circuit-band`, higher slippage). Stop
   orders are DAY-only on exchanges, so a real system needs GTTs (see `breakout-planner`).

## Workflow with other skills

1. `market-regime` (../market-regime/scripts/regime.py): test whether a NIFTY trend filter
   (`--regime-csv`) cuts drawdown more than it cuts return before using it live.
2. Run `run` → `sweep` → `walkforward` → `montecarlo`, and stop at the first red flag.
3. `position-sizing` (../position-sizing/scripts/risk.py): choose a `--risk-pct` that keeps the Monte
   Carlo 95th-percentile drawdown survivable.
4. `trading-discipline`: `--trades-csv` writes journal columns, so
   `python3 ../trading-discipline/scripts/discipline.py review t.csv` breaks the backtest down by
   weekday and setup. Compare it with your live journal later; a large gap is a warning.
5. `breakout-planner`: 52w-high and donchian-breakout are rough stand-ins for its Stage-2 entries.
   They tell you whether breakout buying pays on a stock at all, not whether a given VCP will work.

Limits: one symbol and one position at a time (no portfolio rotation), daily or weekly bars, no
options, no tick rounding.

## Output

```
NAME: strategy (params) | segment on NSE via broker | capital | sizing | slippage
start → end | bars (years) | signal on close, fill next open | charges as of <date>
Strategy vs Buy & hold: total return, CAGR, max DD, volatility, Sharpe (rf), Sortino, Calmar
Trades N: W / L / BE | win rate | avg win / loss | PF | expectancy ₹ (R) | payoff | losing streak
Exposure | avg hold | max DD dates | longest underwater | charges (% of gross profit) | slippage
Year table | last trades | order events | red flags | data notes
```

_Educational analysis, not investment advice. A backtest describes the past, not your next trade._
````

## File: skills/backtest-lab/scripts/backtest.py
size: 86487
sha: 73e9c6a7db68c19858694cc34ab163dd352ead53
upstream: https://github.com/shubhamkumartrichy/claude-trading-skills-india/blob/main/skills/backtest-lab/scripts/backtest.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/shubhamkumartrichy/claude-trading-skills-india/blob/main/skills/backtest-lab/scripts/backtest.py

## File: README.md
upstream: https://github.com/shubhamkumartrichy/claude-trading-skills-india/blob/main/README.md

````text
<div align="center">

<img src="docs/assets/banner.png" alt="India Trading Skills for Claude: an AI stock-market analyst for NSE and BSE" width="100%">

# India Trading Skills for Claude

**Turn Claude into a Dalal Street analyst that gets the maths right.**

35 skills · 22 tested calculators · NSE/BSE · NIFTY F&O · exact STT & charges · Indian tax · Groww / Zerodha / Dhan / Upstox

[![Claude Code plugin](https://img.shields.io/badge/Claude_Code-plugin-D97757?logo=claude&logoColor=white)](#quick-start)
[![Skills](https://img.shields.io/badge/skills-35-2563EB)](#skills)
[![Tests](https://github.com/Shubhamkumartrichy/claude-trading-skills-india/actions/workflows/tests.yml/badge.svg)](https://github.com/Shubhamkumartrichy/claude-trading-skills-india/actions/workflows/tests.yml)
[![Python](https://img.shields.io/badge/python-3.10%2B-3776AB?logo=python&logoColor=white)](#calculators)
[![Dependencies](https://img.shields.io/badge/dependencies-0-22C55E)](#calculators)
[![License: MIT](https://img.shields.io/badge/license-MIT-22C55E)](LICENSE)
[![Made in India](https://img.shields.io/badge/made_in-India-FF9933)](#)

[Quick start](#quick-start) · [What you can ask](#what-you-can-ask) · [See it work](#see-it-work) · [Skills](#skills) · [Brokers](#brokers) · [FAQ](#faq) · [हिंदी में पढ़ें](README.hi.md)

</div>

---

Ask a chatbot about Indian markets and you get confident arithmetic with stale numbers: last year's
STT, the old NIFTY lot size, an expiry on the wrong weekday, and tax set-off rules that don't exist.

**India Trading Skills** gives Claude the 2026 rulebook for NSE and BSE, plus calculators that do the
maths instead of guessing. Some of what it knows that most tools get wrong:

- 💸 A delivery round trip costs **about 0.23%** to break even, not the "~0.1%" most guides quote.
- 📉 After the April 2026 STT hike, a NIFTY futures lot needs **about 14 points** just to cover charges.
- 📅 NIFTY weeklies expire on **Tuesday**, but 2026 had six Tuesday holidays. The expiry calendar shifts them for you.
- 🧾 An F&O loss can offset your capital gains but **never your salary**, and only if you file on time.

<p align="center">
  <img src="docs/assets/demo.svg" alt="Animated demo: broker charges comparison, holiday-adjusted NIFTY expiries and an Indian tax estimate, from the bundled calculators" width="100%">
</p>

> Works in **Claude Code** as a plugin. The skills use the standard `SKILL.md` format, so any agent
> that supports Agent Skills can load them.

<a id="quick-start"></a>

## ⚡ Quick start

**1. Install** (inside Claude Code):

```
/plugin marketplace add Shubhamkumartrichy/claude-trading-skills-india
/plugin install india-trading-skills@india-trading-skills
```

**2. Optionally connect your broker** for live data:

```bash
claude mcp add --transport http groww https://mcp.groww.in/mcp
# then run /mcp inside Claude Code and log in
```

**3. Ask in plain English (or Hinglish):**

```
Analyze HDFCBANK. I hold 300 shares at ₹1,620 since March 2026.
```

No broker? Run `pip install yfinance` and the skills fetch NSE data themselves. No Python packages
are needed for anything else.

<details>
<summary><b>Other ways to install</b></summary>

**skills CLI**

```bash
npx skills add Shubhamkumartrichy/claude-trading-skills-india
```

**Manual (project-level symlinks)**

```bash
git clone https://github.com/Shubhamkumartrichy/claude-trading-skills-india.git
mkdir -p .claude/skills
for d in claude-trading-skills-india/skills/*/; do ln -s "$(cd "$d" && pwd)" ".claude/skills/$(basename "$d")"; done
```

Install the whole pack. Several skills call scripts that live in sibling skills (for example,
`rsi-divergence` uses `technical-analysis/scripts/ta.py`).

</details>

<a id="what-you-can-ask"></a>

## 💬 What you can ask

| You ask | Claude does |
|---|---|
| "Analyze RELIANCE. Buy, sell or wait?" | Weekly→daily view, levels, indicator dashboard, scenarios with odds, an action table with stops and targets |
| "How many NIFTY lots can I trade with ₹8 lakh and a 150-point stop?" | Lot-rounded sizing with costs, margin headroom, and a clear "skip it" when one lot is too big |
| "Charges to buy 200 INFY at 1,480 and sell at 1,520 on Groww vs Zerodha?" | Exact STT, exchange, SEBI, stamp, GST and DP charges, breakeven price, cheapest broker |
| "Build a NIFTY iron condor for Tuesday's expiry" | Expected move from India VIX, strikes beyond it, max loss, breakevens, probability of profit, Greeks |
| "Read this option chain: PCR, max pain, walls?" | Parses NSE's CSV download: PCR, max pain, OI walls, fresh writing, straddle range, IV skew |
| "₹2.4L LTCG, ₹60k STCG, ₹1.1L F&O loss, ₹18L salary. My tax?" | New-regime estimate with set-off steps, the ₹1.25L exemption, 87A rules, ITR form, carry-forward |
| "Which holdings should I sell before March for the LTCG exemption?" | Tax-harvesting plan from your holdings CSV, including lots that turn long-term soon |
| "Pre-market brief" | GIFT Nifty, FII/DII flows, India VIX, NIFTY levels, ban list, events, with a regime label |
| "Is NIFTY in a confirmed uptrend? How much should I deploy?" | Distribution days, follow-through status, risk score, exposure ceiling and max new positions |
| "Is POLYCAB setting up for a breakout?" | Stage 2 checklist, VCP contractions, pivot, and a GTT order plan sized to your risk |
| "Review my portfolio" | Stock, sector and group concentration, LTCG countdown, beta, drawdown, tax-aware rebalance |
| "Are FIIs buying or selling? What's the FII long/short ratio?" | Flow streaks, DII absorption, FII index-futures long % from NSE's participant OI file, extremes flagged |
| "Backtest a 20/50 SMA cross on RELIANCE with Zerodha charges" | Next-bar fills, exact charges, CAGR vs buy-and-hold, drawdown, walk-forward and Monte Carlo checks |
| "Is HDFCBANK vs ICICIBANK a tradable pair?" | Cointegration test, hedge ratio, half-life, z-score, and a whole-lot futures plan |
| "Any RBI, Fed or CPI events before my trade? When's the next expiry?" | Holiday-adjusted expiries, verified RBI/FOMC dates, results windows, a yes/no event-risk answer |
| "Is the market expensive right now?" | NIFTY P/E percentile, yield gap vs G-sec, market cap to GDP, froth score and posture |
| "Find quality compounders in my Screener.in export" | Preset screens with every rule shown, near-misses, pledge and small-cap gates |
| "Should I apply for this IPO?" | RHP checklist, valuation vs peers, subscription reading, allotment odds, lock-in dates |
| "Where do I put my stop, GTT or SL?" | Structure/ATR stop plus Indian execution realities: DAY validity, GTT limits, circuits, gaps |

<a id="see-it-work"></a>

## 🖥️ See it work

Real output from the bundled calculators. The RELIANCE dashboard uses NSE data from 30 Oct 2026.

<table>
<tr>
<td width="50%"><img src="docs/assets/demo-charges.png" alt="Charges comparison across five Indian brokers"></td>
<td width="50%"><img src="docs/assets/demo-options.png" alt="NIFTY iron condor payoff with probability of profit and Greeks"></td>
</tr>
<tr>
<td width="50%"><img src="docs/assets/demo-tax.png" alt="Indian tax estimate with F&O loss set off against capital gains"></td>
<td width="50%"><img src="docs/assets/demo-expiries.png" alt="Holiday-adjusted NIFTY expiry calendar"></td>
</tr>
</table>

<details>
<summary><b>Technical dashboard on live NSE data (RELIANCE)</b></summary>
<br>
<img src="docs/assets/demo-ta.png" alt="Technical analysis dashboard for RELIANCE">
</details>

<a id="skills"></a>

## 🧩 The 35 skills

| Group | Skill | What it does |
|---|---|---|
| **Analyst** | `india-market-analyst` | Orchestrator: full analysis, routing, ground rules, output template |
| | `market-pulse` | Pre-market and post-market brief: GIFT Nifty, FII/DII, VIX, breadth, sectors, regime |
| **Market timing** | `market-regime` | NIFTY distribution days, follow-through days, top-risk score, exposure ceiling |
| | `sector-rotation` | NSE sectoral indices vs NIFTY: relative strength, RRG quadrants, risk-on vs defensiv
````
