Skip to main content

Cost-of-Carry and Arbitrage Intelligence

Research and decision support page (sidebar: Cost of Carry, route /carry, DEVELOPER rank). It compares the annualized implied carry of Silver, Gold, NIFTY and BANK NIFTY futures against their cash benchmark, shows several expiries of one instrument, builds term structures, and screens contracts for a net-of-cost cash-and-carry edge.

It is not a signal generator. A futures premium is not an arbitrage until costs, margin, liquidity, delivery and benchmark mismatch are cleared, and the page never labels anything risk-free.

Code map​

PathRole
backend/carry/calc.pyEvery formula (pure functions, no I/O): basis, gross / net carry, interpolation, trailing percentile, z-score, rolling stats, regimes, adverse excursions, classification
backend/carry/costs.pyEffective-dated statutory schedules, execution scenario, financing proxy lookup
backend/carry/data.pyDiscovers instruments in the existing masters and reads the existing stores into one Panel per instrument
backend/carry/service.pyCarry frame, contract selection, comparative / expiries / term structure / statistics / scanner / opportunity / cross-asset, cache, JSON hygiene
backend/app/api/carry.py/api/carry/* (validation only), registered in app/main.py behind the DEVELOPER gate
frontend/src/pages/CarryDashboard.jsx, carryUi.jsxThe page; displays server numbers, never recomputes finance
backend/tests/test_carry_*.py83 tests (formulas, costs, service on synthetic fixtures, API, real-data checks)

No new tables, no migrations, no new database layer: everything is read through eq_store, fo_store, mcx_fo_store, mcx_spot_store, scr_master, scr_mcx_master, scr_indexpepb and te_price.

Data sources and coverage (local database, 14 Oct 2026)​

InstrumentCash benchmarkFuturesFutures coverage
NIFTYindex, eq_store masid 1scr_master typ 3, monthindex 0 via fo_store2000-06-12 to 2026-09-25 (321 of 322 contracts have prices), tiny gap 31 Aug to 11 Sep 2000
BANK NIFTYindex, eq_store masid 2same2005-06-13 to 2026-09-25 (266 of 266)
Goldmcx_spot_store GOLD (10 g)scr_mcx_master typ 21, monthindex 0 via mcx_fo_store2003-11-10 to 2009-02-23 and 2026-08-14 to 2026-09-30 only
Silvermcx_spot_store SILVER (1 kg)samesame two segments
  • MCX spot starts 2005-05 (silver) and 2005-06 (gold): futures days before that have no cash close and are skipped.
  • The local MCX futures store has no data from 2009-03 to 2026-07. The dashboard shows exactly what exists and warns about the gap; nothing is interpolated. Run the MCX archive import / mcx_fo_store export on this machine (or read the VPS, which holds the full 2003 onward history per mcxeod/CLAUDE.md) to fill it, then press Refresh.
  • Dividend yield (scr_indexpepb.divyie) exists from 2012-02-21. Before that the index net carry is conservative (dividends counted as zero) and flagged dividend yield unavailable.
  • Financing proxy: SBI 1-2 year retail FD rate (te_asset code in_fixed_deposit_rate), 1994 to 2025-12-31, a step series carried forward as of each observation date and flagged stale after 400 days. It is a deposit-rate proxy, not a borrowing rate; override it in Assumptions.
  • Not stored anywhere: bid / ask, margin, historical actual brokerage. These are shown as unavailable, never invented.

Always read the Data coverage and quality panel at the bottom of the page and the warnings in each chart.

Calculation methodology​

One convention everywhere: ACT/365, simple (not compounded) annualization.

S cash benchmark close F futures close, same date, one real contract
D calendar days to expiry (expiry minus date); D must be above 0
basis = F - S
basis % = (F / S - 1) * 100
gross carry % pa = (F / S - 1) * (365 / D) * 100

Invalid prices, D of 0 or less, and implausible pairs (|F/S - 1| above 25 percent) give no value (gap), never an exception and never a filled value.

Net carry is the cash-and-carry edge held to expiry (long cash, short future), only when F is above S:

edge % (to expiry) = basis % + (q - r - h) * D / 365 - costs %
net % pa = edge % * 365 / D
q dividend yield (index only, scr_indexpepb as of the date), r financing, h holding cost

Reverse carry (F below S) needs a short cash leg that is not generally executable, so net is left empty and the row is classed "Not currently actionable".

Index futures. The premium equals financing minus expected dividends. The page therefore shows the raw basis as "gross carry" and, only where a dividend yield is stored, a separate implied financing carry = gross + q.

Gold and silver. Spot and futures units are checked (GRMS per 10, KGS per 1 here: comparable). Even so the MCX spot series is a local polled benchmark, so the basis is a local-market basis estimate; the physical leg (making, GST, import duty, assay, storage, delivery centre) is not priced (Assumptions has holding cost and physical-leg bps if you want to price it).

Contract choice

  • Front month: each day the valid contract with the fewest days to expiry that is at least min_dte (default 1). Every point keeps its real contract; rollovers are marked. Nothing is back-adjusted or stitched.
  • Constant maturity: the carry of the two contracts bracketing N days (default 30) is linearly interpolated, never extrapolated. It is a smoothed comparison, labelled not executable.
  • Annualizing very short-dated contracts amplifies noise (4 days to expiry and 0.2 percent basis is 18 percent a year). The chart can clip the y-axis to the 2nd to 98th percentile, and rows under 7 days carry a warning flag.

No look-ahead. Percentile, z-score and regime of a date use only observations before it (trailing_percentile, trailing_zscore: the value itself and the future are excluded; default window 756 sessions, minimum 60). Tests prove that cutting the future off does not change any earlier value. Rolling 20 / 60 / 252 statistics are trailing and empty until the window is full. The distribution table and the "days above threshold" counts are descriptive over the chosen range and say so.

Risk. For a long-cash / short-future position the interim danger is the basis widening before expiry. The risk table pools every observed day of every contract in range (within one contract only) and reports the maximum adverse widening to expiry and within 5 / 10 / 20 sessions, in percentage points of spot. No win rate, drawdown or Sharpe is claimed: that would need an explicit trade simulation.

Cost and net-carry engine​

ComponentOriginNotes
STT or CTT, exchange charges, SEBI fee, stamp duty, GSTstatutory-referenceEffective-dated schedules in costs.SCHEDULES, chosen by the observation date, never today's rate. Hand-entered reference values: verify against exchange and broker circulars before relying on P and L
BrokerageuserFlat per order (default 20 rupees), 4 orders per round trip
Slippage and spreaduserPer leg-side in bps (index 1, MCX 2). One haircut covers bid-ask and slippage so nothing is counted twice; spread is not stored
Financingproxy or userSBI FD as of the date, or your override
Holding cost, physical leguser or not-modelled0 means not modelled
Margin and its funding costnot-modelledMargin is not stored

Both legs are charged on entry and on exit (conservative). For indices the cash leg is a delivery equity basket: delivery STT on both sides makes index cash-and-carry rarely attractive at retail cost; an ETF or institutional route is not modelled.

API​

GET /api/carry/coverage?instruments= (default: the 4 page instruments)
GET /api/carry/near?instrument=&from=&to= Dashboard tab: spot, F, DTE, carry for the 2 nearest contracts
GET /api/carry/comparative?from=&to=&mode=front|constant&instruments=
GET /api/carry/expiries?instrument=&from=&to=&expiries=
GET /api/carry/term-structure?instrument=&date=&compare=
GET /api/carry/statistics?instrument=&from=&to=&expiry=&thr_hi=&thr_lo=
GET /api/carry/scanner?date=
GET /api/carry/opportunity?instrument=&masid=&date=
GET /api/carry/cross-asset?date=
GET /api/carry/summary?instrument=&from=&to=
POST /api/carry/refresh drop cached results

Every endpoint also accepts the scenario parameters (brokerage_per_order, slippage_bps_index, slippage_bps_commodity, financing_rate_pct, dividend_yield_pct, holding_cost_pct, cash_leg_extra_bps, lots, min_net_edge_pct, scan_min_dte, min_oi, min_volume, extreme_hi, extreme_lo, min_dte, maturity_days, lookback). Responses are {success, data} with dates as ISO strings, missing values as null, flags and warnings beside the numbers, and the assumptions echoed back.

Performance: each instrument's full history is read once through the stores (about 1 s each) because trailing statistics need the past; results are cached under (endpoint, parameters, calc version, scenario hash, latest date of every store), so new data invalidates them. Only the requested range is sent to the browser (series thinned to 1500 points, rollovers kept).

Dashboard tab (multi-chart workspace)​

The page has two tabs: Analysis (everything above) and Dashboard, a TradingView-style workspace for your own cost-of-carry analysis (frontend/src/pages/carryWorkspace.jsx).

  • Layout picker: grid icon, grouped by chart count (1 to 16) like TradingView. Add graph steps to the next layout; the x on a panel removes it. Layout, per-panel settings and the period are saved in the browser's localStorage (carry.workspace.v2; the project has no per-user preferences API) - Reset layout clears it.
  • Panel settings: script (SILVERM, GOLDM, NIFTY, BANKNIFTY), analysis, display options, series toggles, y-axis clip. The period (From / To, 1M..Max) is shared by all panels; panels showing the same script share one request.
  • Two panes per script: left = chart, right = data table; each pane has a maximize button (covers the page) and a restore button. Narrow panels stack the two panes.
  • Quality series (default): annualised carry (F/S - 1) * 365 / DTE * 100 (calc.gross_annualized) of the current month, but in the current month's last 7 days (annualisation is noisy there) the next month is used instead. Contracts with no volume (settlement-type closes) and days where no next month exists are left blank, not estimated. The raw current / next lines can be switched on in the chart header; "Quality only" turns the filter off. The chart can also show Spot and futures or DTE; the metric can be basis %.
  • Data table (the report): the sheet layout Date, Spot Rate, FUT_1, EXP_1, FUT_2, EXP_2, COC_1, COC_2 (EXP = the contract's expiry date, so days to expiry = EXP - Date can be checked by hand) - FUT_1 = current month, FUT_2 = next month, COC = annualised cost of carry % (FUT / Spot - 1) x 365 / days to expiry. One row per session, sortable, CSV export in the same eight columns (COC as 15.32%). Hover a cell for the contract, days to expiry and the spot reading time; COC_1 is dimmed in the last 7 days of the current month. The chart pane keeps the quality line (next month in the last 7 days).
  • MCX spot and GST / duty: the stored MCX spot already converges to the futures price at expiry (local data: median basis within about +-1% in the last 7 days), i.e. spot and futures are on the same duty-paid basis, so by default nothing is added. The toolbar field MCX spot + tax % (API spot_adj_pct, commodities only, default 0) multiplies the spot leg before basis and CAGR are computed, so a GST / duty uplift can be tested; note that e.g. +9% turns the expiry basis into about -9%, which shows the stored spot is not ex-tax.
  • Time-aligned MCX carry (default on, aligned=0 turns it off): the stored MCX spot is the last reading MCX published that day (median 17:18 IST), while the futures EOD close is the 23:30 session close. On GOLDM / SILVERM 1-minute data (2020-2026) that gap is +0.04% / +0.17% on average but +-0.5% / +-0.8% typical per day, which is about 5-10 points of annualised carry at 30 days. So for each date: spot = the day's last reading from scr_mcxsp_tick (mcxeod/mcx_spot_ticks.py, loaded from the raw SpotArchive_*.csv and kept current by the daily spot sync), futures = the 1-minute close of the continuous series I (nearest) / II (next) at that same minute (mcxieod, 2020 onward). A row is aligned only if the series matches the listed contract (its last bar of the day within 0.5% of that contract's EOD close) and a bar exists within 10 minutes of the reading; otherwise it keeps the EOD prices and carries f_unal (shown as EOD in the Spot time column, with a flag). Before 2020 (no 1-minute futures): second tier f_mode = vwap - futures = the contract's day-average traded price (avgprice, needs volume, within 10% of the close) against the mean of that day's spot readings. Tested on 2020-2026 against the same-minute truth, mean absolute error in carry points: GOLDM 3.1 (close 6.7), SILVERM 3.3 (6.9), GOLD 2.0 (4.6), SILVER 3.5 (7.5), bias about 0. Anything else stays eod (close vs last reading, error about 5-7 points). The report marks * (vwap) and a dagger (eod); the Report selector shows Daily, Weekly or Monthly averages (carry averaged over days with at least 7 days to expiry) - the intended view for the old years. Nothing is estimated or filled.
  • API params of /api/carry/near: switch_dte (default 7), quality (default true); rows carry used_* fields.
  • Data honesty: the endpoint reuses carry_frame (so the same plausibility and spot rules); a date without spot or valid futures simply has no row, a date with one eligible contract has blank next-month values, nothing is filled. Coverage warnings (gaps, missing spot, units) are shown in the toolbar and per panel. Locally the MCX mini series (SILVERM / GOLDM) only have 2003-2009 and Aug-Sep 2026 futures and spot from 2009, so the usable MCX range is short until the 2009-2026 MCX F&O history is loaded.
  • Scripts: data.DASH_ORDER; SILVERM and GOLDM are the MCX mini underlyings (scr_mcx_master masid 26 / 12) and are registered in data.SPECS but kept out of data.ORDER, so the Analysis tab is unchanged.
  • Tests: backend/tests/test_carry_service.py (test_near_*).

Classification​

First matching rule wins: insufficient data, then expiry or delivery constraint (days to expiry below scan_min_dte), then not currently actionable (gross at or below zero), then poor liquidity (volume or open interest below your thresholds), then net at or above min_net_edge_pct means potentially attractive net carry, otherwise historical basis extreme (percentile at or beyond the extreme cut-offs) or low net edge after costs. Thresholds are scenario settings; the defaults (net edge 1 percent, open interest 100, volume 10, in the units the stores hold) are not universal. Data older than 5 days before the valuation date can never be "attractive".

Setup and usage​

cd backend
venv\Scripts\activate
pytest tests/test_carry_calc.py tests/test_carry_costs.py tests/test_carry_service.py
python -m scratch.coc_sample # prints the sample analysis below from your own data

Start the backend and frontend as usual and open Cost of Carry. Pick From / To (or 1M ... Max), the instrument for the single-instrument sections, front month or constant maturity, gross or net, and open Assumptions to change costs and thresholds (press Apply). Drag on a chart to zoom, use the arrows to pan, click legend chips to hide series, click a scanner row for the full analysis (economics, cost stack, sensitivity grid, stress, adverse basis, history).

Sample analysis (real project data, valuation 30 Sep 2026)​

Default scenario: brokerage 20 rupees per order, slippage 1 bp (index) / 2 bps (MCX) per side, financing from the SBI FD proxy (6.70 percent), one lot, minimum net edge 1 percent.

ContractDaysGross % paNet % paClassification
SILVER05MAR271569.622.69Potentially attractive net carry (physical leg not priced)
SILVER05MAY2721712.115.24Poor liquidity (open interest 29, volume 6)
GOLD05FEB271287.260.28Low net edge after costs
NIFTY29SEP26418.22-16.93Historical basis extreme (95th percentile), but 4 days to expiry: annualization noise and fixed costs
NIFTY27OCT26326.07-3.12Low net edge after costs
NIFTY23NOV26596.33-1.17Low net edge after costs
BANKNIFTY23NOV26597.59-0.42Low net edge after costs
GOLD05OCT265-73.98n/aNot currently actionable (futures 1 percent under cash, 5 days)

Worked check, SILVER05MAR27: cash 2,21,110, futures 2,30,203, 156 days, lot 30 kg: cash notional 66.3 lakh, gross edge 2.73 lakh, financing 1.90 lakh, costs 6,620 rupees (0.10 percent), net edge to expiry about 76,000 rupees (1.149 percent, 2.69 percent annualized). Break-even basis 6,552 against an actual 9,093.

NIFTY, 21 Feb 2012 to 25 Sep 2026 (3,615 sessions, front month): mean gross carry 6.26 percent, median 5.40, standard deviation 10.71 (inflated by short-dated annualization), 5th to 95th percentile -3.7 to 19.0, positive 88 percent of days. Average basis by days to expiry: 0.06 percent at 0-3 days, 0.31 percent at 15-30, 1.03 percent at 61-120 days, i.e. convergence. Maximum adverse basis widening to expiry: median 0.06, 95th percentile 0.32, worst 1.25 percentage points of spot. NIFTY term structure on 25 Sep 2026: 4d 18.2 percent, 32d 6.1 percent, 59d 6.3 percent gross; adding back the dividend yield gives financing carry 19.4, 7.3 and 7.6 percent.

Gold and silver before 2009 (only history available locally): wide dispersion (silver 5th to 95th percentile -62 to +72 percent gross) because of thin early contracts and short-dated annualization; treat as a data-quality example, not a finding.

Unavailable data, assumptions and known limitations​

  • MCX futures 2009-03 to 2026-07 missing locally; MCX spot starts 2005. Gold and silver therefore have about 950 usable days each (two segments).
  • No bid-ask, margin, or actual historical brokerage; slippage, brokerage and financing are scenario inputs.
  • Statutory schedules are hand-entered reference values (STT from 2026-04 in particular); verify them.
  • Financing is a deposit-rate proxy ending 2025-12-31 (carried forward, flagged stale). Dividend yield exists from 2012.
  • Index cash leg modelled as a delivery equity basket with STT on both sides; tracking error and ETF alternatives are not.
  • Gold and silver physical delivery, purity, GST, import duty and centre differences are not modelled.
  • Closes are end-of-day: the MCX spot and futures closes are not simultaneous, so small basis noise is expected.
  • Expiry-day observations (D = 0) are excluded; expiry shifts (holidays) follow scr_master.edate.
  • The scanner screens one valuation date; nothing here is a backtest, a signal or a guaranteed return.

Why daily COC jumps (SILVERM example) and the smooth measures​

Annualised carry = basis % x 365 / DTE, so the same basis noise is multiplied by about 10 at 37 days to expiry and by about 52 at 7 days: SILVERM 17-Jun-2026, spot 2,47,576, FUT_1 2,52,427 (SILVERM30JUN26, 13 days) = basis 1.96% x 365/13 = 55%; and when the series switches contract (e.g. 24-Apr: DTE 7 with basis 2.54% = 132%, next day the June contract, DTE 67, basis 4.77% = 26%) the level jumps by roughly 100 points with no market move. Mid-2025 to 2026, daily change (std, points): front contract DTE >= 7: 20,

= 30: 12, >= 45: 7.7; calendar spread FUT_2/FUT_1: 3.3; curve slope over all contracts: 3.1 (SILVERM; GOLDM 2.7 for the slope). The chart therefore shows two smooth measures by default (curve_coc, cal_coc in /api/carry/near, service.curve_measures; contracts with DTE >= 15 only, a day needs a single price basis): the slope of basis % against years-to-expiry over every traded contract, and the spot-free calendar-spread carry. Both sit around 10-11.5% a year for silver, i.e. an interest-rate level. The per-contract COC_1 / COC_2 in the table stay as they are (they are the exact arithmetic of the row).