income-desk

April 1, 2026 · View on GitHub

The brain behind your trading desk.

Every trade suggestion is bespoke to your portfolio, your risk profile, your capital. This isn't a signal service — it's a personal trading intelligence system for income-first options traders.

PyPI Tests License: MIT Python 3.11+

pip install income-desk
income-desk --trader us       # See it in action immediately
income-desk --trader india    # India market version

Quick Start: Workflow Harness

The fastest way to understand income-desk. One command walks you through every API — with real broker data or seamless simulated fallback.

python -m income_desk.trader
+------------------------------------------------------------------+
|                         WORKFLOW HARNESS                         |
+------------------------------------------------------------------+
| Market: US                                                       |
| Broker: tastytrade (LIVE)                                        |
| Data:   Broker connected (market closed)                         |
| Tickers (16): AAPL, AMZN, DIA, GLD, GOOGL, IWM + 10 more       |
| Account: NLV USD 32,635  |  BP USD 30,555                       |
+------------------------------------------------------------------+

What it does

Exercises all 15 workflow APIs across 7 phases that mirror a real trading day. Each workflow prints:

  • API signature with all Pydantic request fields and values
  • CLI equivalent (analyzer-cli> rank SPY QQQ ...)
  • Tabular results — regimes, ranked trades, gate scorecards, stress scenarios, Greeks

Data source handling

ConditionWhat happens
Market open + broker credentialsLive quotes from TastyTrade (US) or Dhan (India)
Market closed + broker credentialsAccount data live, quotes from simulated presets
No broker credentialsFull simulated mode — works out of the box

Pricing data is clearly flagged when simulated: ** SIMULATED QUOTES — not tradeable **

Usage

# Interactive — pick market, walk through each phase
python -m income_desk.trader

# Non-interactive — run all phases, get pass/fail summary
python -m income_desk.trader --all --market=US
python -m income_desk.trader --all --market=India

# Single phase
python -m income_desk.trader --phase=2 --market=US    # Scanning only
python -m income_desk.trader --phase=5 --market=India  # Portfolio Risk

# Verbose — show library warnings and tracebacks
python -m income_desk.trader --all --market=US --verbose

7 Phases, 15 Workflows

PhaseTrading QuestionWorkflowsKey Output
1. Pre-MarketIs it safe to trade?health check, daily plan, snapshotCrash sentinel (GREEN/RED), regime map, ticker snapshots
2. ScanningWhat should I trade?scan universe, rank opportunitiesScreened candidates, ranked proposals with POP/score/credit
3. Trade EntryIs this trade ready?validate, size, priceGate scorecard, Kelly sizing, leg quotes with bid/ask
4. MonitoringHow are positions?monitor, adjust, overnight riskExit signals, adjustment recommendations, overnight risk levels
5. Portfolio RiskWhat's my exposure?Greeks aggregation, stress testNet delta/gamma/theta/vega, 18-scenario stress results
6. CalendarAny expiries today?expiry day checkExpiry index, position urgency/deadlines
7. ReportingHow did today go?daily reportTrade counts, P&L, win rate summary

Workflow chaining

Phases feed into each other naturally:

  • Phase 2 rank_opportunities produces trade proposals with real strikes
  • Phase 3 validate_trade + size_position + price_trade use that top proposal
  • Phase 4-6 use demo positions (since harness doesn't manage real positions)

Pass/fail summary

After running all phases, the harness prints a summary:

  HARNESS SUMMARY
+-----------------+----------------------------+----------+
| Phase           | Workflow                   | Status   |
+-----------------+----------------------------+----------+
| 1-PreMarket     | check_portfolio_health     | OK       |
| 1-PreMarket     | generate_daily_plan        | OK       |
| ...             | ...                        | ...      |
| 7-Reporting     | generate_daily_report      | OK       |
+-----------------+----------------------------+----------+
  Total: 15  |  Passed: 15  |  Failed: 0

Files

FilePurpose
income_desk/trader/trader.pyMain script — phase menu, workflow calls, tabular output (~1100 lines)
income_desk/trader/support.pyBroker setup, data source detection, demo positions, formatting (~560 lines)

v2.0: Markdown-Driven Trading (trader_md)

Define your entire trading strategy in markdown. No Python needed.

income-desk v2 introduces trader_md — a declarative trading platform where .workflow.md files ARE the strategy, .risk.md files ARE the risk rules, and .universe.md files ARE the ticker lists. The Python engine runs underneath, but you never touch it.

# Validate your workflow
python -m income_desk.trader_md validate workflows/daily_us.workflow.md

# See what would execute (no API calls)
python -m income_desk.trader_md dry-run workflows/daily_us.workflow.md

# Execute the full trading workflow
python -m income_desk.trader_md run workflows/daily_us.workflow.md

# Interactive mode — pause between steps
python -m income_desk.trader_md run workflows/daily_us.workflow.md --interactive

How it works

Your entire trading platform is a set of markdown files:

trader_md/
  workflows/
    daily_us.workflow.md          <- your strategy
    daily_india.workflow.md
  broker_profiles/
    tastytrade_live.broker.md     <- broker config (no secrets)
    dhan_live.broker.md
    simulated.broker.md
  universes/
    us_large_cap.universe.md      <- ticker lists
    india_fno.universe.md
  risk_profiles/
    conservative.risk.md          <- risk rules
    moderate.risk.md
    aggressive.risk.md
  scenarios/
    black_monday.scenario.md      <- 18 stress test scenarios
    ...
  .env.trading                    <- credentials (gitignored)

The workflow format

---
name: daily_us_income
broker: tastytrade_live
universe: us_large_cap
risk_profile: moderate
---

## Phase 1: Market Assessment

### Step: Market Pulse
workflow: check_portfolio_health
inputs:
  tickers: $universe
  capital: $capital
outputs:
  pulse: $result.sentinel_signal
gate:
  - pulse != "RED"
on_fail: HALT "Market pulse {pulse} -- trading halted"

### Step: Rank Opportunities
workflow: rank_opportunities
inputs:
  tickers: $universe
  capital: $capital
  min_pop: $risk.min_pop
gate:
  - len(proposals) > 0
on_fail: SKIP "No opportunities"

Variable bindings

SyntaxResolves to
$universeTickers from .universe.md
$capitalAccount NLV from broker
$risk.min_popField from .risk.md
$result.sentinel_signalCurrent step's response field
$phase1.iv_rank_mapOutput from a previous phase
$phase2.proposals[0].tickerIndexed access into list output
$positionsLive/demo positions for monitoring

Gate actions

ActionBehavior
HALTStop entire workflow
SKIPSkip this step, continue
BLOCKBlock this step, continue to next phase
ALERTLog warning, continue
WARNSoft warning, continue

5 file types, 1 runner

File TypeWhat it definesExample
.workflow.mdPhases, steps, gates, bindingsdaily_us.workflow.md
.broker.mdBroker type, mode, credentials sourcetastytrade_live.broker.md
.universe.mdTicker lists with descriptionsus_large_cap.universe.md
.risk.mdPosition limits, POP filters, regime rulesmoderate.risk.md
.scenario.mdStress test scenarios with factor shocksblack_monday.scenario.md

Why markdown?

  • A portfolio manager edits min_pop: 0.50 to min_pop: 0.60 in the risk file. Behavior changes. No Python.
  • A new developer reads the workflow file and understands the entire trading pipeline in 5 minutes.
  • An auditor gets the .workflow.md file — it IS the complete trading logic. Every gate, every threshold.
  • Git diff shows exactly what changed in a strategy. PR review catches "you removed the overnight risk gate."
  • AI generates strategies — describe in English, Claude produces the .workflow.md.

Two paths, same engine

# v1: Python path (interactive harness)
python -m income_desk.trader --all --market=US          # 15/15 workflows

# v2: MD path (declarative workflows)
python -m income_desk.trader_md run daily_us.workflow.md  # same engine, defined in markdown

Both call the same 15 workflow APIs. Choose your style.


The Trading Workflow

Trading doesn't start with placing an order. It starts with setting up your desk.

income-desk supports the complete lifecycle — from portfolio construction to AI/ML learning. Each step below shows what the library provides and what you can build on top.


Step 1: Set Up Your Portfolio & Investment Capital

Define your starting capital and risk tolerance. The library models your account and recommends how to structure it.

Library FeaturesPlatform Ideas
recommend_desk_structure(capital, risk_tolerance)Onboarding wizard that creates portfolio on signup
PortfolioAllocation model with asset class breakdownDashboard showing capital allocation pie chart
SimulatedAccount(nlv, cash, bp) for demoPaper trading mode with virtual capital
Account providers for 6 brokersAuto-fetch real account balance
income-desk --demo           # Creates \$100K simulated portfolio
> desk 100000 --risk moderate

Step 2: Set Up Your Desks — Allocate Capital & Risk Limits

Split capital across trading desks, each with its own mandate. Desks are the organizational unit — income desk, 0DTE desk, wheel desk, directional desk.

Library FeaturesPlatform Ideas
Asset class allocation: Options, Stocks, Metals, FuturesVisual desk builder with drag-and-drop allocation
compute_desk_risk_limits(desk, capital, regime)Dynamic risk limits that adjust with market conditions
Regime-aware allocation (R4 → +15% cash reserve)Auto-rebalance alert when regime shifts
India-specific: desk_expiry_day for weekly expirySeparate India desk with lot-size awareness
> portfolio    # View all desks with capital allocation

Step 3: Define Asset Types Per Desk

Each desk has a strategy whitelist, DTE range, and instrument type. The 0DTE desk only takes same-day expiries. The income desk only takes 21-60 DTE defined-risk structures.

Library FeaturesPlatform Ideas
Per-desk strategy whitelist (IC, credit spread, calendar...)Strategy selector dropdown per desk
DTE ranges per desk (0DTE desk: 0-1, income desk: 21-60)Trade routing engine based on DTE
suggest_desk_for_trade(desks, dte, strategy)Auto-route trades to correct desk
Instrument type per desk (options, equities, mixed)Desk-level P&L tracking

Step 4: Define Risk Profile — Defined vs Undefined Risk

Choose how much of your capital can be in undefined-risk positions. This controls what structures the system will suggest.

Library FeaturesPlatform Ideas
Conservative: 100% defined risk (no naked options)Risk profile selector during onboarding
Moderate: 80% defined, 20% undefinedPer-desk risk type enforcement
Aggressive: 60% defined, 40% undefinedWarning when undefined risk allocation exceeded
compute_margin_buffer(trade_spec, regime)Margin utilization dashboard
compute_margin_analysis(trade_spec, nlv, bp)Cash vs margin comparison before every trade
> margin_buffer SPY    # Margin impact preview
> margin SPY 35000     # Full margin analysis

Step 5: Define Universe of Underlyings

Pick what you trade. Built-in presets get you started. Broker watchlists sync automatically.

Library FeaturesPlatform Ideas
Built-in presets: income (12 tickers), nifty50, sector_etfUniverse manager with save/load
ma.registry.get_universe(preset="income")Custom watchlist builder
Broker watchlists via WatchlistProviderSync from broker app
85+ instruments with sector, liquidity ratingFilter by sector, options liquidity, market
> scan_universe income
> watchlist --list          # Show broker watchlists

Step 6: Screen the Universe

Filter your universe down to actionable candidates. Multiple screen types catch different setups.

Library FeaturesPlatform Ideas
4 screens: breakout, momentum, mean reversion, incomeMulti-screen dashboard
ma.screening.scan(tickers, min_score, top_n)Daily auto-scan with email alerts
Liquidity filter (ATR < 0.3% auto-removed)Candidate pipeline with scoring
Correlation dedup (same-regime, same-RSI deduplicated)Heatmap of correlated candidates
> screen SPY QQQ IWM GLD TLT
> screen --watchlist income_etfs

Step 7: Rank Tickers

Rank surviving candidates by composite score: regime alignment, phase, IV rank, income bias. Every score is explainable.

Library FeaturesPlatform Ideas
ma.ranking.rank(tickers) — 11 strategies per tickerRanked trade table with sort/filter
Composite score: regime alignment + phase + income biasScore breakdown tooltip
IV rank map integrationIV rank overlay on ranking
Data gaps tracked per entryData quality indicator per candidate
> rank SPY QQQ IWM GLD TLT --debug
> rank --watchlist income_etfs --account 35000

Candlestick Pattern Detection

Read raw price bars like a day trader. 19 classical candlestick patterns detected from OHLCV data, scored by context (trend, volume, support/resistance proximity). Timeframe-agnostic — works on daily bars or intraday.

> candles SPY                    # Scored patterns (daily, last 10 bars)
> candles SPY --lookback 20      # Scan last 20 bars
> candles SPY --raw              # All detections, no conviction filter
CANDLESTICK PATTERNS: SPY (daily, last 10 bars)
──────────────────────────────────────────────────
  2026-03-28  BULLISH_ENGULFING  bullish  conviction: 78
              bullish_engulfing: after bearish trend, volume 1.8x avg, near key level

  Strongest: BULLISH_ENGULFING (78) — bullish
  Summary: 1 bullish, 0 bearish

Composable API — use at any level:

from income_desk.features.patterns.candles import (
    detect_candlestick_patterns,    # Layer 1: raw geometric detection
    score_candlestick_patterns,     # Layer 2: context scoring (0-100)
    compute_candlestick_patterns,   # Convenience: detect + score + summarize
)

# Raw detection (for backtesting)
patterns = detect_candlestick_patterns(ohlcv_df, lookback_bars=10)

# Scored (for live decisions)
scored = score_candlestick_patterns(ohlcv_df, patterns)

# All-in-one
summary = compute_candlestick_patterns(ohlcv_df)
summary.strongest   # highest conviction pattern
summary.bullish_count, summary.bearish_count

Auto-included in TechnicalSnapshot — patterns appear alongside RSI, MACD, VCP, Smart Money:

snap = ma.technicals.snapshot("SPY")
snap.candlestick_patterns.strongest.pattern   # CandlePatternType.BULLISH_ENGULFING
snap.candlestick_patterns.strongest.conviction  # 78
CategoryPatterns
Single-bar (7)Hammer, Inverted Hammer, Hanging Man, Shooting Star, Doji, Dragonfly Doji, Spinning Top
Double-bar (4)Bullish/Bearish Engulfing, Tweezer Top/Bottom
Triple-bar (6)Morning/Evening Star, Morning/Evening Doji Star, Three White Soldiers, Three Black Crows
Five-bar (2)Rising Three, Falling Three

Conviction scoring (0-100): Trend alignment (30), body conviction (20), volume confirmation (20), S/R proximity (20), pattern complexity (10). All thresholds configurable via candle_* settings.


Step 8: Build Scenario Trades (No Checks)

Generate trade structures for top candidates. These are proposals — not yet validated against your portfolio.

Library FeaturesPlatform Ideas
assess_iron_condor(ticker, regime, tech, vol)Trade builder with structure selector
assess_calendar(), assess_diagonal(), etc.Visual payoff diagram
11 option play assessorsSide-by-side structure comparison
TradeSpec with legs, strikes, DTE, exit rulesTrade spec preview card
select_skew_optimal_strike()Skew heatmap for strike selection
select_optimal_dte() from vol surfaceDTE comparison chart
> opportunity SPY
> opportunity IWM --debug    # Full commentary trace

Step 9: Promote to What-If Trade — Full Checks

This is where income-desk's validation engine kicks in. The scenario trade gets tested against your portfolio, risk limits, and real market data.

Library FeaturesPlatform Ideas
run_daily_checks() — 10-check profitability gatePre-trade compliance dashboard
run_adversarial_checks() — gamma stress, vega shock, breakeven spreadStress test visualization
audit_decision() — 4-level scoring (leg/trade/portfolio/risk)Decision report card UI
compute_position_size() — Kelly + correlation + marginPosition sizer with slider
compute_trust_report() — data quality + context qualityTrust badge on every trade
assess_crash_sentinel() — market health signalTraffic light dashboard widget
score_entry_level() — enter now vs waitEntry timing indicator
compute_limit_entry_price() — patient/normal/aggressiveLimit order price suggestion
compute_pullback_levels() — where trade gets betterAlert manager for pullback levels
assess_assignment_risk() — US american / India europeanAssignment warning badge
compute_margin_analysis() + compute_margin_buffer()Margin impact preview
assess_rate_risk() — interest rate sensitivityRate risk overlay
> validate SPY              # 10-check profitability gate
> audit SPY 35000           # 4-level decision audit
> kelly SPY 35000           # Position sizing
> sentinel                  # Crash sentinel status

Step 10: Execute & Book Trade

The validated trade becomes a real position. TradeSpec carries everything the broker needs — legs, strikes, expiration, order type, chase limit.

Library FeaturesPlatform Ideas
TradeSpec with complete legs, strikes, expirationOne-click order from trade spec
build_closing_trade_spec() for exit ordersPre-built close orders
suggest_desk_for_trade() — routes to correct deskAuto-routing with confirmation
Demo portfolio: add_demo_position()Paper trading execution
max_entry_price — chase limitFill quality monitoring
Entry window (time of day gates)Execution window enforcement
> trade SPY                 # Place trade in demo portfolio
> close_trade abc123        # Close position and record P&L

Step 11: Monitor Trades

Ongoing position monitoring with actionable signals. Every check returns a concrete action — hold, close, or adjust — with a closing TradeSpec when needed.

Library FeaturesPlatform Ideas
compute_monitoring_action() — hold/close/adjust with closing TradeSpecPosition dashboard with action buttons
monitor_exit_conditions() — profit target, stop loss, DTE exit, regime changeReal-time P&L with exit trigger alerts
compute_regime_stop() — R1=2x, R2=3x, R3=1.5x, R4=1.5xDynamic stop visualization
compute_time_adjusted_target() — close early if profitable fastTrailing profit target chart
compute_remaining_theta_value() — hold vs close vs redeployTheta decay curve
run_position_stress() — ongoing adversarial stressPosition stress heatmap
check_trade_health() — unified health with overnight riskPosition health cards
assess_assignment_risk() — ITM warning before expiryAssignment countdown alert
> health SPY                           # Position health check
> monitor SPY                          # Exit condition scan
> exit_intelligence SPY 10 0.30        # Exit analysis with DTE and P&L
> assignment_risk SPY                  # Assignment risk assessment

Step 12: Adjust Trades & Manage Lifecycle

When a position is tested, income-desk returns a deterministic adjustment decision — not a menu of options. Roll, convert, or close, with the exact TradeSpec to execute.

Library FeaturesPlatform Ideas
recommend_action() — deterministic adjustment decisionOne-click adjustment execution
CONVERT_TO_DIAGONAL — strategy switching on regime changeStrategy conversion wizard
handle_assignment() — sell/wheel/hold decision with TradeSpecAssignment handler workflow
analyze_cash_secured_put() — CSP/wheel analysisWheel strategy tracker
analyze_covered_call() — CC after assignmentPost-assignment action plan
rebalance_desks() — periodic desk rebalancingMonthly rebalance scheduler
evaluate_desk_health() — desk performance scoringDesk performance dashboard
> adjust SPY                           # Get adjustment recommendation
> assignment SPY 570 put               # Handle assignment scenario
> csp IWM 240 2.50                     # Cash-secured put analysis
> covered_call IWM 240                 # Covered call after assignment

Step 13: Feed AI/ML for Learning

Close the loop. Every trade outcome flows back into the system. Ranking weights calibrate, gate thresholds tune, and the system gets sharper over time.

Library FeaturesPlatform Ideas
calibrate_weights(outcomes) — adjusts ranking from real resultsWeekly auto-calibration job
analyze_adjustment_effectiveness(outcomes) — which adjustments workAdjustment analytics dashboard
analyze_gate_effectiveness(gate_history, shadow, actual) — are gates too tight?Gate tuning interface
TradeOutcome model — captures entry, exit, regime, P&LTrade journal with tagging
PerformanceReport — by strategy, by regimePerformance analytics
Shadow portfolio tracking — blocked trades' hypothetical P&L"What if" tracker for rejected trades
> performance                          # Performance report
> sharpe                               # Sharpe ratio analysis
> drift                                # Portfolio drift detection

Try It Now

pip install income-desk

# Full US trading simulation
income-desk --trader us

# Full India trading simulation
income-desk --trader india

# Interactive demo with \$100K portfolio
income-desk --demo

# Offline (weekends/after hours)
income-desk --sim income      # Ideal income day (elevated IV, R1)
income-desk --sim recovery    # Post-crash rich premiums (R2, IV rank 80%+)
income-desk --sim crash       # Test crash playbook

Supported Brokers

BrokerMarketCost
AlpacaUSFree (delayed)
TastyTradeUSAccount required
IBKRUS/GlobalAccount required
Schwab / thinkorswimUSAccount required
DhanIndiaFree API
ZerodhaIndiaAccount required

Note: thinkorswim is Schwab's trading platform. The Schwab broker integration covers both — connecting via the Schwab API gives you access to thinkorswim accounts. No separate integration needed.

income-desk --setup    # Connect your broker

Works without any broker (yfinance free data). Connect a broker for real-time quotes, Greeks, and HIGH trust analysis.

Multi-Account Consolidation

Many traders have accounts across multiple brokers — TastyTrade for options, Schwab for equities, Fidelity for retirement. income-desk treats ALL your accounts as one portfolio.

Library FeaturesPlatform Ideas
Pluggable broker ABCs — connect multiple simultaneouslyUnified portfolio dashboard across brokers
PortfolioExposure aggregates across all positionsCross-broker risk dashboard
compute_position_size() considers ALL open positionsSizing that knows about your Fidelity IRA AND your TastyTrade options
CSV import from any brokerConsolidate without API — just upload trade exports
Correlation checks across all tickers regardless of accountOne correlation matrix, all accounts
Crash sentinel monitors all positionsSingle alert for all accounts

Example: You have 3 accounts:

  • TastyTrade: 2 iron condors (API connected)
  • Schwab IRA: 5 equity positions (API connected)
  • Fidelity 401K: index funds (CSV import)

income-desk sees all 10 positions as ONE portfolio. Kelly sizing accounts for the Fidelity positions. Correlation checks catch SPY IC + SPY index fund overlap. The crash sentinel monitors everything.

CSV import for non-API brokers:

> import_trades ~/Downloads/fidelity_trades.csv
Detected: fidelity | Imported: 12 positions | Skipped: 2

Supported formats: thinkorswim, TastyTrade, Schwab, IBKR, Fidelity, Webull, generic.

Trust Framework

Every output tells you how much to trust it:

TRUST: 85% HIGH
  Data: 90% HIGH (broker_live) | Context: 85% HIGH (full mode)
  Fit for: ALL purposes including live execution

No broker? Trust = LOW — fit for research only. Full trust framework docs

Forward Testing, Not Backtesting

income-desk has no backtesting engine. Deliberately.

Start with 1 contract. Validation gates protect your capital. System learns from YOUR real outcomes. Kelly scales up as edge is proven.

1 contract → validation gates protect → record outcome →
calibrate_weights() learns → Kelly scales up → repeat

Workflow APIs

15 high-level operations — one function call per trading action. All rate limiting, caching, and orchestration handled internally. Trades only propose strikes verified liquid in the broker's option chain.

from income_desk.workflow import generate_daily_plan, DailyPlanRequest

plan = generate_daily_plan(
    DailyPlanRequest(tickers=["NIFTY", "BANKNIFTY", "RELIANCE", "TCS"], capital=5_000_000, market="India"),
    ma,
)
# plan.proposed_trades[0].short_put = 2300 (verified OI=305,000)
CategoryWorkflows
Pre-marketgenerate_daily_plan, snapshot_market
Scanningscan_universe, rank_opportunities
Trade entryvalidate_trade, size_position, price_trade
Positionsmonitor_positions, adjust_position, assess_overnight_risk
Portfolio riskaggregate_portfolio_greeks, check_portfolio_health
Stress testingstress_test_portfolio (18 macro scenarios)
Expirycheck_expiry_day
Reportinggenerate_daily_report

Every workflow: Pydantic request in, Pydantic response out, WorkflowMeta with timestamp and warnings.


Simulated Market Data — Weekend & After-Hours Testing

Full pipeline works without broker, internet, or market hours. Swap one line to go from live to simulated.

from income_desk.adapters.simulated import create_india_trading, create_ideal_income, SimulatedMetrics

# India: 22 tickers (5 indices + 17 F&O stocks, correct strike intervals & lot sizes)
sim = create_india_trading()

# US: 16 tickers (SPY/QQQ/IWM + AAPL/MSFT/NVDA/TSLA + sector ETFs)
sim = create_ideal_income()

# Create analyzer — all 15 workflows work identically
ma = MarketAnalyzer(data_service=DataService(), market_data=sim, market_metrics=SimulatedMetrics(sim))

# Discovery: what tickers does this simulation support?
sim.supported_tickers()   # ["NIFTY", "BANKNIFTY", "RELIANCE", ...]
sim.has_ticker("NIFTY")   # True
sim.ticker_info()         # {"NIFTY": {"price": 23000, "iv": 0.18, ...}}

Available presets: create_calm_market, create_volatile_market, create_crash_scenario, create_post_crash_recovery, create_wheel_opportunity, create_india_market, create_india_trading, create_ideal_income.


Portfolio Stress Testing

Run all 18 macro scenarios against your portfolio in one call. Factor model with correlations, IV leverage effect, and Monte Carlo confidence intervals.

from income_desk.workflow import stress_test_portfolio, StressTestRequest

result = stress_test_portfolio(
    StressTestRequest(positions=my_positions, capital=5_000_000, market="India"),
    ma,
)
# result.risk_score = "safe"
# result.worst_scenario = "black_monday" (INR -8,814 loss)
# result.scenarios_breaching_limit = []

18 scenarios: S&P corrections (-5/-10/-20%), Black Monday, NIFTY crash, FII sell-off, RBI rate hike, commodity meltup, gold crash, rate shock, inflation/deflation, tech rotation, geopolitical shock, correlation spike.

Scenario engine (income_desk/scenarios/) also available standalone for stress-testing market data:

from income_desk.scenarios import apply_scenario
stressed_sim, result = apply_scenario(baseline, "nifty_down_10")
# stressed_sim is a new SimulatedMarketData — use with any workflow

Daily Profitability Test

Run every market day to verify the pipeline is production-ready:

.venv_312/Scripts/python.exe scripts/daily_profitability_test.py          # live Dhan
.venv_312/Scripts/python.exe scripts/daily_profitability_test.py --sim    # simulated

Produces a GO / CAUTION / NO-GO verdict based on: broker connectivity, option chain quality, regime detection, trade recommendation quality, validation gate pass rate, and position sizing sanity. Reports saved to ~/.income_desk/profitability_reports/.


Documentation

90+ CLI Commands

Workflows:  daily_plan, snapshot, portfolio_greeks, profitability, presets, expiry_check, scenario, stress_portfolio
Trading:    validate, rank, screen, opportunity, entry_analysis, kelly, audit, sentinel
Monitoring: health, monitor, exit_intelligence, adjust, assignment_risk
Portfolio:  desk, portfolio, trade, close_trade, rebalance
Sizing:     kelly, size, margin, margin_buffer, csp, covered_call
Research:   regime, technicals, candles, vol, levels, research, stress, rate_risk
Account:    balance, quotes, watchlist, wizard

Run help in the CLI for the full list.

Contributing

See CONTRIBUTING.md. Adding a broker = ~170 lines of field mapping, zero core changes.

License

MIT — see LICENSE.