/india-trading-skills:pair-tradingfrom india-trading-skills
Tests cointegration and computes hedge ratios, half-life, and z-scores for NSE stock pairs. Plans Indian futures execution with lot sizes, margin, and F&O rules. Use for market-neutral long/short pair trades.
Ships in india-trading-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Two stocks that share the same economics (two private banks, two oil marketing companies) can drift apart for weeks, then close the gap. A pair trade is long the cheap one and short the rich one, sized so the market move cancels out. This works only if the gap is statistically mean-reverting (cointegrated). A high correlation is not enough.
python3 scripts/pairs.py test HDFCBANK ICICIBANK --csv-dir stocks/ # one pair, full statistics
python3 scripts/pairs.py screen --members members.csv --csv-dir stocks/ # all same-sector pairs
python3 scripts/pairs.py signal BPCL HPCL --csv-dir stocks/ --exit 0.5 # rules + in-sample trades
python3 scripts/pairs.py plan BPCL HPCL --csv-dir stocks/ --lots-csv fo_mktlots.csv \
--ban-list fo_secban.csv --margin-a 120000 --margin-b 110000 # India execution
Without --csv-dir, prices come from Yahoo (pip install yfinance). Create offline CSVs with
../technical-analysis/scripts/ta.py fetch --symbol TCS --out stocks/TCS.csv. Only a date and a
close column are needed; a volume column turns on the liquidity filter. Use split and bonus-adjusted
closes. --members is a symbol,sector CSV. Common options: --lookback 500 sessions (0 = all),
--end YYYY-MM-DD (re-test an earlier window), --window 60 (z-score), --entry 2 --exit 0 --stop 3.5, --adf-lag N or --max-lag N, --splits 3, --max-half-life 40, --json.
Screen adds --min-bars 250 --min-turnover 10 (₹ crore a day) --min-corr 0.5 --top 20.
| Statistic | How |
|---|---|
| Correlation | Pearson correlation of daily log returns on common dates |
| Hedge ratio β | OLS of ln A on ln B. Hold ₹β of B against each ₹1 of A. Also reverse OLS and total least squares |
| Cointegration | Engle-Granger: ADF (no constant) on the OLS residuals, lag by AIC (Schwert maximum) or fixed |
| Critical values | MacKinnon (2010) Table 2, N = 2 with constant: ≈ −3.90 / −3.34 / −3.04 (1/5/10%) plus a T-adjustment. These are stricter than plain Dickey-Fuller values (≈ −2.86 at 5%) because β was fitted |
| p-value | MacKinnon (1994) asymptotic surface. Use it for ranking; the critical values decide |
| Half-life | AR(1) on the spread: s_t = c + φ·s_{t−1}; half-life = ln 0.5 / ln φ sessions |
| z-score | (spread − 60-session mean) / 60-session sd |
| Stability | β in 3 consecutive sub-periods; drift ≤ 25% of β = stable, > 50% = unstable |
Both regression directions are tested. A pair counts only if both reject the unit root.
--max-half-life;
3–20 fits a monthly futures cycle best) and β stable. Then look at the z-score.signal enters at |z| ≥ 2 once |z| has reset inside the band. It exits when z returns to 0 (or
±0.5 with --exit 0.5), stops at |z| ≥ 3.5, and time-stops after 2× the half-life
(--max-hold, --time-stop-mult). Each trade is returned as % of gross notional. The trade list
is in-sample: β, the test and the half-life all come from the same data, so the hit rate is an
optimistic upper bound and excludes costs. Check out of sample: run test with --end six
months back, then see whether the pair still holds on the newer data.
plan)--legs cash-long to buy the long leg for delivery and short
the other leg in futures. SLB (stock lending) exists but is thin.plan rounds the B leg, reports the residual mismatch in % and ₹, and lists the lot combinations
with the tightest hedge. With --legs cash-long, the delivery leg is sized in shares.--lot-a/--lot-b, or --lots-csv with NSE's fo_mktlots.csv (one column per
contract month). NSE revises lot sizes periodically, and corporate actions adjust them. If the
file shows a different size in a later month, the plan flags it: re-size the hedge when you roll.--margin-a/--margin-b (₹ per lot from your broker), otherwise --margin-pct 25 of
contract value per leg. Margin is summed leg by leg. A long/short across two different stocks is
not a recognised spread, so do not count on a hedge margin benefit. Futures are marked to market
daily, so keep a buffer.../trading-costs/scripts/charges.py (futures STT 0.05% on the sell side
since Apr 2026). The plan counts one round trip per leg plus one per roll, and futures carry (the
long leg pays it, the short earns it).../fno-options-analysis/scripts/options.py). They are physically
settled. The plan lists roll-by dates within the expected hold (2× half-life). Near expiry, it
switches to the next month.--ban-list (NSE fo_secban.csv), --banned SYM, or --mwpl-a/--mwpl-b (%). See
indian-market-structure.HDFCBANK/ICICIBANK, KOTAKBANK/AXISBANK, SBIN/BANKBARODA, TCS/INFY, HCLTECH/WIPRO, BPCL/HPCL (IOC as a third), ULTRACEMCO/SHREECEM, TATASTEEL/JSWSTEEL. They share sector, regulation and macro drivers. That makes them worth testing, not cointegrated by default. Re-test every quarter.
screen reports, and confirm on a later window.Size the risk-to-stop rupee figure with position-sizing; compare broker costs in trading-costs;
ban and margin rules in indian-market-structure; expiries in fno-options-analysis; sector
backdrop in sector-rotation.
Pair A / B: N sessions [from → to] | corr r | β (OLS / TLS) | EG t = x vs 5% crit y → reject? p≈
Half-life H sessions | z now Z → zone | β stability: stable/drifting/unstable | verdict
Signal (in-sample): trades n, hit rate h%, avg r% | now: flat / open / signal
Plan: SELL A fut n lots / BUY B fut m lots | mismatch ±x% | margin ₹ | charges ₹ | roll by date
Risks: F&O ban, lot revision, results dates, structural break
Educational analysis, not investment advice.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub shubhamkumartrichy/claude-trading-skills-india --plugin india-trading-skills35 skills in this plugin
/backtest-labBacktests 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.
/breakout-plannerStage-2 breakout setups on NSE/BSE stocks: a trend-template check (rising 200 DMA, 50>150>200
stack, distance from 52-week high/low, relative strength vs NIFTY), base detection (volatility
contraction with successively tighter pullbacks, or a flat base) with pivot, depth, duration,
volume dry-up and a grade, then an order-ready plan: trigger, chase limit, capped stop, size,
Indian charges, R targets, GTT/SL templates, circuit-band and NSE tick-size checks. breakout.py
scans a folder of CSVs or yfinance symbols and ranks them, offline-capable.
Use when the user asks: "is X in a Stage 2 uptrend", "find VCP setups", "where is the pivot on X",
"plan a breakout trade in X", "breakout buy point and stop", "scan these stocks for breakouts",
"Minervini trend template for NSE stocks", "how do I place a GTT for a breakout", or any question
about buying stocks as they clear a base.
/broker-integrationConnect Claude to Indian brokers and use them safely: official MCP servers for Groww, Zerodha
Kite, Dhan, Upstox, Fyers and Kotak Neo (endpoints, auth, read vs order capabilities as of Oct 2026),
tool discovery and capability mapping, saving candles for the analysis scripts, a mandatory
order-confirmation protocol, SEBI retail-algo/static-IP rules, and data fallbacks (yfinance, CSV).
Use when the user asks to connect or set up Groww/Zerodha/Kite/Dhan/Upstox/Fyers/Angel One, "fetch my
holdings/positions", "get live price", "place/modify/cancel an order", "set a GTT", "why was my order
rejected", or when another skill needs live data.
/event-calendarOffline calendar of the dates that move Indian markets: NSE/BSE F&O expiries (holiday-shifted),
exchange holidays, long weekends and special sessions, results-season windows (SEBI LODR),
trader tax dates, India macro releases (CPI, WPI, IIP, GDP, PMI, auto sales, GST, AMFI), RBI MPC,
Union Budget, US FOMC/CPI/jobs, NIFTY and MSCI rebalances, plus your own results, board-meeting,
ex-date and lock-in events. Every date is labelled computed, expected-by-rule, verified (with
source) or unverified. events.py exports .ics and answers "is there event risk in my holding
window?".
Use when the user asks: "what's on this week", "economic calendar India", "when is the next RBI
policy", "when is expiry", "is Monday a holiday", "events before my exit date", "any event risk
in this trade", "Fed meeting date", "when is CPI", "Budget date", "results season dates",
"advance tax due date", "export market calendar to Google Calendar", or before any multi-day trade.
/exhaustion-reversalWhen a move on NSE/BSE has run out of buyers or sellers. exhaustion.py scores a vertical run-up
0-100 (stretch above the 20/50/200 DMA, acceleration, run length, range/volume blow-off, late
gaps, upper-circuit streaks, price-band cuts), labels it extended, climax or reversal confirmed,
and plans the exit: scale out and trail with a GTT if you hold, or short only via stock futures or
puts on F&O names after a trigger, sized in lots. Also finds selling-exhaustion hammers for long
entries, judges whether a stock failed to react to news, and scans a universe with F&O tags.
Use when the user asks: "is this stock parabolic", "has the rally topped", "my stock hit upper
circuit five days running, should I sell", "how do I book profit on a multibagger", "can I short
this", "short a stock that ran up 80%", "capitulation or hammer setup", "selling exhaustion",
"results were good but the stock fell, what does it mean", or wants a blow-off top scan.
/fibonacci-tradingFibonacci retracement entry zones and extension targets for NSE/BSE stocks and indices, with
automatic swing detection (ta.py fib), trend-based extensions from the pullback point, and
confluence with moving averages, support/resistance, round numbers and option OI strikes.
Use when the user asks: "fib levels for X", "Fibonacci retracement", "where to buy the pullback",
"golden ratio / 61.8%", "Fib extension targets", "how far can NIFTY fall/rise from here", or gives
a swing high and low to compute levels.
2 plugins ship this exact skill · first indexed Nov 4, 2026
Other plugins' skills for the same job