Chidi cont work#10
Open
Zino-ctrlZ wants to merge 81 commits into
Open
Conversation
…lter_contracts API
…patibility contract
…, and sizing safeguards
- Add AggregationLevel enum (BY_TRADE_SIGNAL, BY_SIGNAL, BY_TRADE) to types.py - Fix signal_id typo in trade.py constructor - Implement aggregate_trades() method with weighted/additive column specs - Support flexible trade grouping for reporting and analysis
…ttlement - Ensure effective_date respects next trading day after (last_updated + t_plus_n) - Prevents limits from taking effect intra-t+n period - Maintains correct settlement timeline for portfolio constraints
Add LiquidityConfig and LiquidityPolicy for shared liquidity control: - Level 0: Disabled (all trades execute normally) - Level 1: Quantity haircut in risk manager for wide spreads - Level 2: Silent drop + next-business-day reschedule at threshold Implementation: - LiquidityConfig with level (0..2) and max_spread_pct threshold - LiquidityPolicy service with enabled(level) and should_drop_for_spread() checks - Inject shared policy into RiskManager (level-1 quantity gate) - Inject shared policy into SimulatedExecutionHandler (level-2 silent drop + tracking) - Backtest orchestrator wires policy to both components - Add finalize-trades infrastructure for eq_strategy: close all open positions on final day
- Add _ffill_adj_strike_business_days() for continuous adjusted-strike cache - Reindex strike data on explicit business-day range to prevent data gaps - Update .gitignore with debug/ folder rules (excludes development utilities) - Clean trailing whitespace and improve formatting in utils.py
- Check get_preset_order() first in get_order() - Return preset order directly when available - Normalize preset payload date/quantity to Order shape - Use helper to_datetime for date conversions
- add get_trade_timeseries(trade_id, signal_id=None) - resolve signal_id from aggregated trades when unambiguous - slice position market data by entry/exit dates - use backtest end date for still-open trades
- extend convert_attribution_to_df with groupby='daily' - aggregate attribution rows by date index - drop signal_id and trade_id in daily mode - keep existing signal and trade aggregation behavior
…n and DataManager improvements - Add dynamic base_dir resolution via get_dm_gen_path() in CacheSpec.__post_init__ - Update dividend and date utilities - Add new vars and config entries for DataManager
Co-authored-by: Cursor <cursoragent@cursor.com>
… defaults Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
QuantTools: EventDriven backtest, risk manager, and datamanager overhaul
Branch:
CHIDI-CONT-WORKScope: 144 files changed · ~19.5k insertions · ~5k deletions
Summary
This PR is a large integration branch that modernizes the EventDriven backtesting stack, replaces legacy order-selection paths with a scoring-based picker, adds position lifecycle COGs (PnL monitor, Donchian, mean reversion, vectorized sizing), and brings substantial datamanager/cache improvements—including negative caching for option spot gaps. It also adds vectorized option PnL retrieval/runner tooling, refactors position attribution into a dedicated module, and expands developer workflow docs (Copilot skills, docstring standards, MCP/editor config).
EventDriven backtest & execution
OptionSignalBacktestnow mixes inBacktestRunMixin, wires a sharedLiquidityPolicy, and adds pre/post signal analysis hooks plus finalize-close signal injection on the last backtest day.eq_strategyproperty propagates strategy changes to risk manager and portfolio after initialization.SimulatedExecutionHandlerrefactor:randomized,fixed,pct_of_spread,none) viaExecutionHandlerConfig.get_fill_tracking_df().LiquidityPolicyshared across backtest, risk manager, and execution.EventDriven/logging.pyfor package-wide logger level control.Position attribution
attributor.pywith newattribution.py(~587 lines).xmultiply_attr_v2payload loading for option PnL decomposition.PositionAttributionAnalyzer, trade quantity time series normalization, and trade/signal/portfolio aggregation helpers.Risk manager & order picker
Legacy removal (breaking)
_order_validator.py,_orders.py, and monolithicmarket_data.py.Scoring-based order selection
chain_scoring.py— Gaussian-style moneyness/DTE scoring with tilt options.iv_helper.pyandpicker/utils.pysupporting chain filtering and scoring columns.OrderPickerrewritten around_score_chain, preset-order honor path, and flexiblefilter_contractsAPI.ScoringConfigsadded; config export/validation aligned to scoring-only flow.Position COGs (new / expanded)
pnl_monitor.pydonchian_cog.pymean_reversion.pyplain_sizing.pyvectorized.pyPnLMonitorConfigmoved toconfigs.corewith YAML export support.effective_date; limits metadata and special dividends loaded fromspecial_dividends.yaml.Market data & timeseries
market_timeseries.pyexpanded to absorb deleted market-data responsibilities; continuous dividend adjustment for chain Greeks.size_limit; temp-cache isolation improved in_vars.py.OPTION_TIMESERIES_START_DATEcentralized fromtrade.optionlib.config.defaults.Portfolio & strategy
new_portfolio.py— trade timeseries lookup, trade aggregation API (multiple granularities), preset-order support, improved PnL consistency and state tracking.strategy.py/eventScheduler.py— signal ID propagation, conflict handling, empty-queue semantics, type-hint cleanup.BacktestRunMixinon portfolio, risk manager, and backtest timeseries for shared pre-run lifecycle.trade / datamanager
Negative cache (option spot gaps)
classification.py(new) — classifies fetched vs missing vs checked-missing dates.cache.py/option_spot.py/date.py—_CachedData.checked_missing_datesprevents repeat API calls for confirmed empty ranges.test_negative_cache.py— manual verification script for the negative-cache flow.Other datamanager changes
CacheSpecpath resolution; global cache toggle and guarded write paths.get_div_scheduleoptionalfilter_specials; duplicateCACHE_NAMEregistry check disabled.trade / backtester & assets
option_vectorized_retrieval.py— contract retrieval for vectorized runs.option_vectorized_pnl_runner.py— retrieval → PnL → trade/signal/portfolio aggregation + equity curve.xmultiply_attr_v2.py— payload-driven option attribution loading.Calculate.pymajor refactor (~1.4k line delta); rates migrated toget_risk_free_rate_helper_v2.trade/backtester_/utils/aggregators.pyexpanded aggregation utilities.trade/helpers/helper.py— cache helpers, date utilities, type cleanup inhelper_types.py.trade/__init__.py— Plotly plotting backend default; minor import hygiene.Config & tooling
EventDriven/configs/core.py— new config types:LiquidityConfig,ExecutionHandlerConfig,ScoringConfigs,PnlMonitorConfig,VectorizedCogConfig,PlainSizingCogConfig,MeanReversionSizerConfigs, validation mixin updates..github/copilot-instructions.md— commit strategy and strict docstring policy.commit-strategy,docstring-standards,tfp-db..vscode/mcp.json, settings updates;ruff.tomlignoresF541,B905.EventDriven/Testing/→EventDriven/tests/rename with golden regression data (async/process/thread run outputs).Test plan
EventDriven/tests/(process, thread, async runners) and compare CSV/txt outputs.trade/tests/test_option_vectorized_retrieval.pyandtest_option_vectorized_pnl_runner.py.module_test/test_trade_pnl_consistency.py,test_position_cache.py,test_xmultiply_dual_mode.py.OrderPickerwith a known strategy config; confirm legacy schema paths raise as expected.test_negative_cache.pyagainst ThetaData (or mock) to confirm second call avoids API for checked-missing dates.PositionAttributionAnalyzeragainst priorattributorbaselines on a fixed trade set.Notes / follow-ups
.live_forward_compatibility.txttracks live-forward migration items (trade map load, limits DB metadata)..DS_Storechanges should not be merged; consider stripping before merge.chidi_agent.mdis an empty placeholder agent file.