ghosalquant 0.1.1__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. {ghosalquant-0.1.1/src/ghosalquant.egg-info → ghosalquant-0.2.0}/PKG-INFO +17 -5
  2. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/README.md +16 -4
  3. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/__init__.py +1 -1
  4. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/backtester/backtester_base.py +7 -0
  5. ghosalquant-0.2.0/src/ghosalquant/blocks/__init__.py +18 -0
  6. ghosalquant-0.2.0/src/ghosalquant/blocks/nodes.py +406 -0
  7. ghosalquant-0.2.0/src/ghosalquant/blocks/runner.py +144 -0
  8. ghosalquant-0.2.0/src/ghosalquant/blocks/schema.py +317 -0
  9. ghosalquant-0.2.0/src/ghosalquant/blocks/strategy.py +105 -0
  10. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/broker_base.py +4 -0
  11. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/commissions.py +1 -1
  12. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/fills.py +63 -28
  13. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/order_book_sim.py +3 -0
  14. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/simulation.py +24 -34
  15. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/core/__init__.py +6 -0
  16. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/core/contracts.py +10 -3
  17. ghosalquant-0.2.0/src/ghosalquant/core/depth.py +102 -0
  18. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/core/metadata_keys.py +5 -2
  19. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/core/types.py +23 -14
  20. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/recording_datasource.py +68 -28
  21. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/yfinance_datasource.py +3 -1
  22. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/yfinance_multi_datasource.py +3 -1
  23. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/execution/execution_system.py +240 -126
  24. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/metrics/__init__.py +3 -0
  25. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/metrics/gates.py +15 -9
  26. ghosalquant-0.2.0/src/ghosalquant/metrics/markouts.py +48 -0
  27. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/metrics/risk_adjusted.py +33 -2
  28. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/__init__.py +6 -1
  29. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/basic_portfolio.py +9 -19
  30. ghosalquant-0.2.0/src/ghosalquant/portfolio/fair_value.py +249 -0
  31. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/marks.py +42 -0
  32. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/portfolio_base.py +5 -0
  33. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/valuation.py +19 -41
  34. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/recording/events.py +29 -18
  35. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/recording/intervals.py +13 -14
  36. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/recording/recorder.py +48 -21
  37. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/recording/storage.py +12 -9
  38. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/__init__.py +6 -0
  39. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/builder.py +18 -0
  40. ghosalquant-0.2.0/src/ghosalquant/risk/buying_power.py +75 -0
  41. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/risk_manager.py +9 -20
  42. ghosalquant-0.2.0/src/ghosalquant/risk/rules/rule_buying_power.py +42 -0
  43. ghosalquant-0.2.0/src/ghosalquant/risk/rules/rule_long_only.py +27 -0
  44. ghosalquant-0.2.0/src/ghosalquant/risk/rules/rule_price_collar.py +30 -0
  45. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/types.py +3 -2
  46. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/state/event_store.py +4 -2
  47. {ghosalquant-0.1.1 → ghosalquant-0.2.0/src/ghosalquant.egg-info}/PKG-INFO +17 -5
  48. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant.egg-info/SOURCES.txt +18 -0
  49. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_backtester.py +64 -8
  50. ghosalquant-0.2.0/tests/test_blocks.py +364 -0
  51. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_contracts.py +4 -2
  52. ghosalquant-0.2.0/tests/test_depth.py +103 -0
  53. ghosalquant-0.2.0/tests/test_execution_loop.py +259 -0
  54. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_execution_order_book.py +30 -4
  55. ghosalquant-0.2.0/tests/test_fair_value.py +264 -0
  56. ghosalquant-0.2.0/tests/test_markouts.py +70 -0
  57. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_metrics.py +71 -0
  58. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_order_book_sim_broker.py +111 -0
  59. ghosalquant-0.2.0/tests/test_pre_trade_rules.py +257 -0
  60. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_recording.py +84 -2
  61. ghosalquant-0.2.0/tests/test_replace_orders.py +390 -0
  62. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_state.py +21 -0
  63. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_valuation.py +16 -0
  64. ghosalquant-0.1.1/tests/test_replace_orders.py +0 -188
  65. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/LICENSE +0 -0
  66. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/pyproject.toml +0 -0
  67. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/setup.cfg +0 -0
  68. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/backtest_ui/__init__.py +0 -0
  69. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/backtest_ui/__main__.py +0 -0
  70. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/backtest_ui/app.py +0 -0
  71. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/backtest_ui/runner.py +0 -0
  72. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/backtester/__init__.py +0 -0
  73. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/backtester/dataframe_backtester.py +0 -0
  74. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/bench/__init__.py +0 -0
  75. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/bench/benchmark_buy_and_hold.py +0 -0
  76. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/bench/benchmark_trend_vol_target.py +0 -0
  77. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/__init__.py +0 -0
  78. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/builder.py +0 -0
  79. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/ibkr.py +0 -0
  80. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/open_orders.py +0 -0
  81. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/simulated.py +0 -0
  82. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/compatibility/legacybacktester.py +0 -0
  83. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/compatibility/plotManager.py +0 -0
  84. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/compatibility/test_strategy.py +0 -0
  85. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/compatibility/trade.py +0 -0
  86. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/core/blackscholes.py +0 -0
  87. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/core/volatility.py +0 -0
  88. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/__init__.py +0 -0
  89. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/cboe_datasource.py +0 -0
  90. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/dataLayer.py +0 -0
  91. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/dataframe_datasource.py +0 -0
  92. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/datasource_base.py +0 -0
  93. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/datasource_factory.py +0 -0
  94. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/dolt_datasource.py +0 -0
  95. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/listEditor.py +0 -0
  96. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/list_datasource.py +0 -0
  97. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/live_alpaca_datasource.py +0 -0
  98. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/live_ibkr_datasource.py +0 -0
  99. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/live_polygon_datasource.py +0 -0
  100. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/merge.py +0 -0
  101. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/nse_datasource.py +0 -0
  102. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/parquet_polygon_datasource.py +0 -0
  103. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/shocks.py +0 -0
  104. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/staticUpdater.py +0 -0
  105. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/execution/__init__.py +0 -0
  106. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/execution/context.py +0 -0
  107. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/execution/sinks.py +0 -0
  108. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/execution/strategy_base.py +0 -0
  109. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/attribution.py +0 -0
  110. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/hedging.py +0 -0
  111. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/lots.py +0 -0
  112. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/recording/__init__.py +0 -0
  113. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/cash_allocation.py +0 -0
  114. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_confidence_sizer.py +0 -0
  115. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_correlation_filter.py +0 -0
  116. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_drawdown_killswitch.py +0 -0
  117. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_integer_quantity.py +0 -0
  118. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_kelly_sizer.py +0 -0
  119. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_max_open_positions.py +0 -0
  120. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_max_symbol_exposure.py +0 -0
  121. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_regime_filter.py +0 -0
  122. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_signal_quantity_cap.py +0 -0
  123. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_symbol_capital_sizer.py +0 -0
  124. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_tick_rounding.py +0 -0
  125. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/risk/sizing.py +0 -0
  126. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/state/__init__.py +0 -0
  127. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/state/atomic.py +0 -0
  128. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/state/json_store.py +0 -0
  129. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/util/backtester_utils.py +0 -0
  130. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/util/config.py +0 -0
  131. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/util/deprecation.py +0 -0
  132. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/util/rounding.py +0 -0
  133. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant/util/visualisation.py +0 -0
  134. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant.egg-info/dependency_links.txt +0 -0
  135. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant.egg-info/entry_points.txt +0 -0
  136. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant.egg-info/requires.txt +0 -0
  137. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/src/ghosalquant.egg-info/top_level.txt +0 -0
  138. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_cboe_datasource.py +0 -0
  139. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_config.py +0 -0
  140. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_dolt_datasource.py +0 -0
  141. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_example_options_momentum.py +0 -0
  142. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_example_order_book.py +0 -0
  143. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_execution.py +0 -0
  144. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_ibkr_broker.py +0 -0
  145. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_ibkr_real_client.py +0 -0
  146. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_legacy_backtester.py +0 -0
  147. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_limit_orders.py +0 -0
  148. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_live_sources.py +0 -0
  149. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_nse_datasource.py +0 -0
  150. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_order_book_types.py +0 -0
  151. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_public_api.py +0 -0
  152. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_risk_rules.py +0 -0
  153. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_shocks.py +0 -0
  154. {ghosalquant-0.1.1 → ghosalquant-0.2.0}/tests/test_volatility.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ghosalquant
3
- Version: 0.1.1
3
+ Version: 0.2.0
4
4
  Summary: Event-driven quantitative trading research framework
5
5
  Author: Ghosal Quants
6
6
  License-Expression: MIT
@@ -218,12 +218,13 @@ is required. To have the library load the bars too, set `DATA` (`yfinance`, `pol
218
218
  |---|---|
219
219
  | Sizing | `ConfidenceSizer`, `SymbolCapitalFractionSizer`, `FractionalKellySizer`, `SignalQuantityCap` |
220
220
  | Limits | `MaxOpenPositions`, `MaxSymbolExposure`, `CashAllocationRule`, `DrawdownKillSwitch`, `CorrelationFilter`, `RegimeFilter` |
221
- | Venue | `IntegerQuantity`, `TickRounding` |
221
+ | Account | `BuyingPower`, `LongOnly` |
222
+ | Venue | `IntegerQuantity`, `TickRounding`, `PriceCollar` |
222
223
 
223
224
  ### Portfolio and valuation (`ghosalquant.portfolio`)
224
225
  - `BasicPortfolio`: signed positions, LIFO lots, commissions, de-duplication of fills by `execution_id`, and
225
- `adopt()` to start from a live account's cash and positions. It refuses a buy fill it can't afford, with a
226
- warning.
226
+ `adopt()` to start from a live account's cash and positions.
227
+ - `FairValueMarks`: a `mark_policy` for markets that trade rarely.
227
228
  - `PortfolioValuationEngine`: marked NAV, liquidation equity into displayed bids, and a risk equity capped at cost.
228
229
  - `hedging` gives net delta and gamma per underlier and the hedge quantity; `attribution` splits a position's change
229
230
  in value into its causes.
@@ -231,12 +232,22 @@ is required. To have the library load the bars too, set `DATA` (`yfinance`, `pol
231
232
  ### Contracts and options (`ghosalquant.core`)
232
233
  - `ContractRegistry` and `Contract`: multiplier, option right, strike, expiry, and cash or physical settlement.
233
234
  `settlement_fills` settles positions at expiry.
235
+ - `depth`: a book without our own orders, what an order would take from it, and where it reaches a given depth.
234
236
  - `blackscholes` (price, greeks, implied volatility), and `VolSurface` / `Smile` built from a chain.
235
237
 
236
238
  ### Metrics (`ghosalquant.metrics`)
237
- - `risk_adjusted_metrics(equity_curve, init_capital=...)` for any equity curve.
239
+ - `risk_adjusted_metrics(equity_curve, init_capital=...)` for any equity curve, net of `deposits`.
240
+ - `markouts(fills, marks, horizons)` for what fills were worth later.
238
241
  - `evaluate_gates(metrics, spec)` for go/no-go checks on a set of metrics.
239
242
 
243
+ ### Block strategies (`ghosalquant.blocks`)
244
+ - A strategy described as JSON instead of code, for visual editors: rules of the form "when this condition holds,
245
+ hold this share of equity", built from prices, indicators, comparisons and crossovers.
246
+ - `validate_spec` checks a spec and names where it is wrong; `BlockStrategy` runs one as an ordinary `Strategy`;
247
+ `run_spec` / `run_spec_async` backtest one on a DataFrame and return a JSON-ready result.
248
+ - The package imports without yfinance, so this runs in a browser under Pyodide. The spec is documented in
249
+ `ghosalquant/blocks/schema.py`.
250
+
240
251
  ### Recording and state
241
252
  - `ghosalquant.recording`: one durable stream per event kind. Each stream is a write-ahead log sealed into verified
242
253
  Parquet segments, with books stored only when they change and prints de-duplicated.
@@ -271,6 +282,7 @@ src/ghosalquant/
271
282
  recording/ # Recorders and segmented Parquet storage
272
283
  state/ # Atomic JSON, versioned state store, SQLite event journal
273
284
  util/ # Config, visualisation, KPM calculation, tick rounding
285
+ blocks/ # JSON strategy spec, validator and BlockStrategy for visual editors
274
286
  backtest_ui/ # Prototype GUI (the ui extra)
275
287
  compatibility/ # Deprecated LegacyBacktester
276
288
  examples/ # Example scripts and a commented config.yaml
@@ -172,12 +172,13 @@ is required. To have the library load the bars too, set `DATA` (`yfinance`, `pol
172
172
  |---|---|
173
173
  | Sizing | `ConfidenceSizer`, `SymbolCapitalFractionSizer`, `FractionalKellySizer`, `SignalQuantityCap` |
174
174
  | Limits | `MaxOpenPositions`, `MaxSymbolExposure`, `CashAllocationRule`, `DrawdownKillSwitch`, `CorrelationFilter`, `RegimeFilter` |
175
- | Venue | `IntegerQuantity`, `TickRounding` |
175
+ | Account | `BuyingPower`, `LongOnly` |
176
+ | Venue | `IntegerQuantity`, `TickRounding`, `PriceCollar` |
176
177
 
177
178
  ### Portfolio and valuation (`ghosalquant.portfolio`)
178
179
  - `BasicPortfolio`: signed positions, LIFO lots, commissions, de-duplication of fills by `execution_id`, and
179
- `adopt()` to start from a live account's cash and positions. It refuses a buy fill it can't afford, with a
180
- warning.
180
+ `adopt()` to start from a live account's cash and positions.
181
+ - `FairValueMarks`: a `mark_policy` for markets that trade rarely.
181
182
  - `PortfolioValuationEngine`: marked NAV, liquidation equity into displayed bids, and a risk equity capped at cost.
182
183
  - `hedging` gives net delta and gamma per underlier and the hedge quantity; `attribution` splits a position's change
183
184
  in value into its causes.
@@ -185,12 +186,22 @@ is required. To have the library load the bars too, set `DATA` (`yfinance`, `pol
185
186
  ### Contracts and options (`ghosalquant.core`)
186
187
  - `ContractRegistry` and `Contract`: multiplier, option right, strike, expiry, and cash or physical settlement.
187
188
  `settlement_fills` settles positions at expiry.
189
+ - `depth`: a book without our own orders, what an order would take from it, and where it reaches a given depth.
188
190
  - `blackscholes` (price, greeks, implied volatility), and `VolSurface` / `Smile` built from a chain.
189
191
 
190
192
  ### Metrics (`ghosalquant.metrics`)
191
- - `risk_adjusted_metrics(equity_curve, init_capital=...)` for any equity curve.
193
+ - `risk_adjusted_metrics(equity_curve, init_capital=...)` for any equity curve, net of `deposits`.
194
+ - `markouts(fills, marks, horizons)` for what fills were worth later.
192
195
  - `evaluate_gates(metrics, spec)` for go/no-go checks on a set of metrics.
193
196
 
197
+ ### Block strategies (`ghosalquant.blocks`)
198
+ - A strategy described as JSON instead of code, for visual editors: rules of the form "when this condition holds,
199
+ hold this share of equity", built from prices, indicators, comparisons and crossovers.
200
+ - `validate_spec` checks a spec and names where it is wrong; `BlockStrategy` runs one as an ordinary `Strategy`;
201
+ `run_spec` / `run_spec_async` backtest one on a DataFrame and return a JSON-ready result.
202
+ - The package imports without yfinance, so this runs in a browser under Pyodide. The spec is documented in
203
+ `ghosalquant/blocks/schema.py`.
204
+
194
205
  ### Recording and state
195
206
  - `ghosalquant.recording`: one durable stream per event kind. Each stream is a write-ahead log sealed into verified
196
207
  Parquet segments, with books stored only when they change and prints de-duplicated.
@@ -225,6 +236,7 @@ src/ghosalquant/
225
236
  recording/ # Recorders and segmented Parquet storage
226
237
  state/ # Atomic JSON, versioned state store, SQLite event journal
227
238
  util/ # Config, visualisation, KPM calculation, tick rounding
239
+ blocks/ # JSON strategy spec, validator and BlockStrategy for visual editors
228
240
  backtest_ui/ # Prototype GUI (the ui extra)
229
241
  compatibility/ # Deprecated LegacyBacktester
230
242
  examples/ # Example scripts and a commented config.yaml
@@ -16,7 +16,7 @@ from ghosalquant.core.types import (
16
16
  Trade,
17
17
  )
18
18
 
19
- __version__ = "0.1.1"
19
+ __version__ = "0.2.0"
20
20
 
21
21
  __all__ = [
22
22
  "OrderBookStrategy",
@@ -1,4 +1,5 @@
1
1
  import asyncio
2
+ from datetime import timedelta
2
3
  from pathlib import Path
3
4
  from typing import final, Iterable
4
5
 
@@ -11,6 +12,7 @@ from ..execution.sinks import SignalSink
11
12
  from ..core.contracts import ContractRegistry
12
13
  from ..core.types import Order, BacktestKPMs, EquityPoint
13
14
  from ..portfolio.basic_portfolio import BasicPortfolio
15
+ from ..portfolio.marks import Marker, MarkPolicy
14
16
  from ..portfolio.portfolio_base import Portfolio
15
17
  from ..brokerage.broker_base import Broker
16
18
  from ..risk.builder import build_risk_manager
@@ -31,6 +33,8 @@ class Backtester:
31
33
  broker: Broker | None = None,
32
34
  config: Config | None = None,
33
35
  contracts: ContractRegistry | None = None,
36
+ mark_policy: Marker = MarkPolicy.MID,
37
+ snapshot_interval: timedelta = timedelta(seconds=1),
34
38
  ) -> None:
35
39
  self.config = config
36
40
 
@@ -48,6 +52,9 @@ class Backtester:
48
52
  portfolio = portfolio,
49
53
  broker = broker,
50
54
  contracts = contracts,
55
+ mark_policy = mark_policy,
56
+ snapshot_interval = snapshot_interval,
57
+ replay_observed_at = True,
51
58
  )
52
59
 
53
60
  self._portfolio = self.execution_system.portfolio
@@ -0,0 +1,18 @@
1
+ """
2
+ Strategies described as data, for visual editors: a JSON spec, its validator, and the
3
+ ``Strategy`` that runs it. See ``ghosalquant.blocks.schema`` for the spec.
4
+ """
5
+
6
+ from .runner import bars_from_payload, run_spec, run_spec_async
7
+ from .schema import SPEC_VERSION, SpecError, validate_spec
8
+ from .strategy import BlockStrategy
9
+
10
+ __all__ = [
11
+ "SPEC_VERSION",
12
+ "BlockStrategy",
13
+ "SpecError",
14
+ "bars_from_payload",
15
+ "run_spec",
16
+ "run_spec_async",
17
+ "validate_spec",
18
+ ]
@@ -0,0 +1,406 @@
1
+ """
2
+ The evaluation tree a validated spec compiles to.
3
+
4
+ Every node has ``step(ctx)``, called exactly once per bar, in bar order. A node only ever sees the
5
+ current bar and what it has kept from earlier ones, so no node can read the future. ``None``
6
+ means "no value yet" (an indicator still warming up, a division by zero, no open position); it
7
+ propagates through arithmetic, and any comparison involving it is false.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from collections import deque
14
+ from dataclasses import dataclass
15
+ from typing import Any, Callable
16
+
17
+ from ..core.types import Bar
18
+
19
+
20
+ @dataclass(slots=True)
21
+ class BarContext:
22
+ """What a node may look at for the current bar."""
23
+ bar: Bar
24
+ in_position: bool
25
+ position_return_pct: float | None
26
+ bars_held: int | None
27
+
28
+
29
+ class Node:
30
+ def step(self, ctx: BarContext) -> Any:
31
+ raise NotImplementedError
32
+
33
+
34
+ # ----- Numbers ----- #
35
+
36
+ class Const(Node):
37
+ def __init__(self, value: float) -> None:
38
+ self.value = value
39
+
40
+ def step(self, ctx: BarContext) -> float:
41
+ return self.value
42
+
43
+
44
+ class Price(Node):
45
+ def __init__(self, field: str) -> None:
46
+ self.field = field
47
+
48
+ def step(self, ctx: BarContext) -> float | None:
49
+ value = float(getattr(ctx.bar, self.field))
50
+ return value if math.isfinite(value) else None
51
+
52
+
53
+ class PositionReturn(Node):
54
+ def step(self, ctx: BarContext) -> float | None:
55
+ return ctx.position_return_pct
56
+
57
+
58
+ class BarsHeld(Node):
59
+ def step(self, ctx: BarContext) -> float | None:
60
+ return None if ctx.bars_held is None else float(ctx.bars_held)
61
+
62
+
63
+ _MATH: dict[str, Callable[[float, float], float | None]] = {
64
+ "+": lambda a, b: a + b,
65
+ "-": lambda a, b: a - b,
66
+ "*": lambda a, b: a * b,
67
+ "/": lambda a, b: None if b == 0.0 else a / b,
68
+ }
69
+
70
+
71
+ class Math(Node):
72
+ def __init__(self, op: str, left: Node, right: Node) -> None:
73
+ self.fn = _MATH[op]
74
+ self.left = left
75
+ self.right = right
76
+
77
+ def step(self, ctx: BarContext) -> float | None:
78
+ a = self.left.step(ctx)
79
+ b = self.right.step(ctx)
80
+ if a is None or b is None:
81
+ return None
82
+ out = self.fn(a, b)
83
+ return out if out is not None and math.isfinite(out) else None
84
+
85
+
86
+ class Previous(Node):
87
+ """The value its child had ``bars`` bars ago."""
88
+
89
+ def __init__(self, of: Node, bars: int) -> None:
90
+ self.of = of
91
+ self.history: deque[float | None] = deque(maxlen=bars + 1)
92
+
93
+ def step(self, ctx: BarContext) -> float | None:
94
+ self.history.append(self.of.step(ctx))
95
+ if len(self.history) < self.history.maxlen:
96
+ return None
97
+ return self.history[0]
98
+
99
+
100
+ # ----- Indicators ----- #
101
+
102
+ class _Windowed(Node):
103
+ """An indicator over the last ``period`` values of its source; a missing value restarts it."""
104
+
105
+ def __init__(self, source: Node, period: int) -> None:
106
+ self.source = source
107
+ self.period = period
108
+ self.window: deque[float] = deque(maxlen=period)
109
+
110
+ def step(self, ctx: BarContext) -> float | None:
111
+ value = self.source.step(ctx)
112
+ if value is None:
113
+ self.window.clear()
114
+ return None
115
+ self.window.append(value)
116
+ if len(self.window) < self.period:
117
+ return None
118
+ return self.compute()
119
+
120
+ def compute(self) -> float | None:
121
+ raise NotImplementedError
122
+
123
+
124
+ class Sma(_Windowed):
125
+ def compute(self) -> float:
126
+ return math.fsum(self.window) / self.period
127
+
128
+
129
+ class Highest(_Windowed):
130
+ def compute(self) -> float:
131
+ return max(self.window)
132
+
133
+
134
+ class Lowest(_Windowed):
135
+ def compute(self) -> float:
136
+ return min(self.window)
137
+
138
+
139
+ class StdDev(_Windowed):
140
+ """Population standard deviation, the convention Bollinger bands use."""
141
+
142
+ def compute(self) -> float:
143
+ mean = math.fsum(self.window) / self.period
144
+ return math.sqrt(math.fsum((x - mean) ** 2 for x in self.window) / self.period)
145
+
146
+
147
+ class Bollinger(_Windowed):
148
+ def __init__(self, source: Node, period: int, mult: float, sign: float) -> None:
149
+ super().__init__(source, period)
150
+ self.offset = mult * sign
151
+
152
+ def compute(self) -> float:
153
+ mean = math.fsum(self.window) / self.period
154
+ std = math.sqrt(math.fsum((x - mean) ** 2 for x in self.window) / self.period)
155
+ return mean + self.offset * std
156
+
157
+
158
+ class Roc(Node):
159
+ """Percent change against the value ``period`` bars ago."""
160
+
161
+ def __init__(self, source: Node, period: int) -> None:
162
+ self.source = source
163
+ self.window: deque[float] = deque(maxlen=period + 1)
164
+
165
+ def step(self, ctx: BarContext) -> float | None:
166
+ value = self.source.step(ctx)
167
+ if value is None:
168
+ self.window.clear()
169
+ return None
170
+ self.window.append(value)
171
+ if len(self.window) < self.window.maxlen or self.window[0] == 0.0:
172
+ return None
173
+ return (value / self.window[0] - 1.0) * 100.0
174
+
175
+
176
+ class Ema(Node):
177
+ """Exponential average with alpha 2 / (period + 1), seeded with the SMA of the first ``period`` values."""
178
+
179
+ def __init__(self, source: Node, period: int) -> None:
180
+ self.source = source
181
+ self.period = period
182
+ self.alpha = 2.0 / (period + 1.0)
183
+ self.seed: list[float] = []
184
+ self.value: float | None = None
185
+
186
+ def step(self, ctx: BarContext) -> float | None:
187
+ x = self.source.step(ctx)
188
+ if x is None:
189
+ self.seed.clear()
190
+ self.value = None
191
+ return None
192
+ if self.value is None:
193
+ self.seed.append(x)
194
+ if len(self.seed) < self.period:
195
+ return None
196
+ self.value = math.fsum(self.seed) / self.period
197
+ return self.value
198
+ self.value += self.alpha * (x - self.value)
199
+ return self.value
200
+
201
+
202
+ class _Wilder:
203
+ """Wilder's smoothing: the mean of the first ``period`` values, then a 1/period exponential."""
204
+
205
+ def __init__(self, period: int) -> None:
206
+ self.period = period
207
+ self.count = 0
208
+ self.total = 0.0
209
+ self.value: float | None = None
210
+
211
+ def push(self, x: float) -> float | None:
212
+ if self.value is None:
213
+ self.count += 1
214
+ self.total += x
215
+ if self.count == self.period:
216
+ self.value = self.total / self.period
217
+ return self.value
218
+ self.value += (x - self.value) / self.period
219
+ return self.value
220
+
221
+ def reset(self) -> None:
222
+ self.count = 0
223
+ self.total = 0.0
224
+ self.value = None
225
+
226
+
227
+ class Rsi(Node):
228
+ def __init__(self, source: Node, period: int) -> None:
229
+ self.source = source
230
+ self.gain = _Wilder(period)
231
+ self.loss = _Wilder(period)
232
+ self.last: float | None = None
233
+
234
+ def step(self, ctx: BarContext) -> float | None:
235
+ x = self.source.step(ctx)
236
+ if x is None:
237
+ self.last = None
238
+ self.gain.reset()
239
+ self.loss.reset()
240
+ return None
241
+ if self.last is None:
242
+ self.last = x
243
+ return None
244
+ change = x - self.last
245
+ self.last = x
246
+ gain = self.gain.push(max(change, 0.0))
247
+ loss = self.loss.push(max(-change, 0.0))
248
+ if gain is None or loss is None:
249
+ return None
250
+ if loss == 0.0:
251
+ return 100.0 if gain > 0.0 else 50.0
252
+ return 100.0 - 100.0 / (1.0 + gain / loss)
253
+
254
+
255
+ class Atr(Node):
256
+ def __init__(self, period: int) -> None:
257
+ self.smooth = _Wilder(period)
258
+ self.last_close: float | None = None
259
+
260
+ def step(self, ctx: BarContext) -> float | None:
261
+ bar = ctx.bar
262
+ if self.last_close is None:
263
+ true_range = bar.high - bar.low
264
+ else:
265
+ true_range = max(bar.high - bar.low, abs(bar.high - self.last_close), abs(bar.low - self.last_close))
266
+ self.last_close = bar.close
267
+ return self.smooth.push(true_range)
268
+
269
+
270
+ # ----- Conditions ----- #
271
+
272
+ _COMPARE: dict[str, Callable[[float, float], bool]] = {
273
+ ">": lambda a, b: a > b,
274
+ "<": lambda a, b: a < b,
275
+ ">=": lambda a, b: a >= b,
276
+ "<=": lambda a, b: a <= b,
277
+ }
278
+
279
+
280
+ class Compare(Node):
281
+ def __init__(self, op: str, left: Node, right: Node) -> None:
282
+ self.fn = _COMPARE[op]
283
+ self.left = left
284
+ self.right = right
285
+
286
+ def step(self, ctx: BarContext) -> bool:
287
+ a = self.left.step(ctx)
288
+ b = self.right.step(ctx)
289
+ return a is not None and b is not None and self.fn(a, b)
290
+
291
+
292
+ class Cross(Node):
293
+ """True on the bar where ``left`` moves from at-or-below ``right`` to above it (or the reverse)."""
294
+
295
+ def __init__(self, direction: str, left: Node, right: Node) -> None:
296
+ self.sign = 1.0 if direction == "above" else -1.0
297
+ self.left = left
298
+ self.right = right
299
+ self.last_diff: float | None = None
300
+
301
+ def step(self, ctx: BarContext) -> bool:
302
+ a = self.left.step(ctx)
303
+ b = self.right.step(ctx)
304
+ if a is None or b is None:
305
+ self.last_diff = None
306
+ return False
307
+ diff = (a - b) * self.sign
308
+ crossed = self.last_diff is not None and self.last_diff <= 0.0 < diff
309
+ self.last_diff = diff
310
+ return crossed
311
+
312
+
313
+ class And(Node):
314
+ def __init__(self, args: list[Node]) -> None:
315
+ self.args = args
316
+
317
+ def step(self, ctx: BarContext) -> bool:
318
+ # No short-circuit: every child must see every bar to keep its history.
319
+ return all([arg.step(ctx) for arg in self.args])
320
+
321
+
322
+ class Or(Node):
323
+ def __init__(self, args: list[Node]) -> None:
324
+ self.args = args
325
+
326
+ def step(self, ctx: BarContext) -> bool:
327
+ return any([arg.step(ctx) for arg in self.args])
328
+
329
+
330
+ class Not(Node):
331
+ def __init__(self, arg: Node) -> None:
332
+ self.arg = arg
333
+
334
+ def step(self, ctx: BarContext) -> bool:
335
+ return not self.arg.step(ctx)
336
+
337
+
338
+ class InPosition(Node):
339
+ def step(self, ctx: BarContext) -> bool:
340
+ return ctx.in_position
341
+
342
+
343
+ # ----- Compilation ----- #
344
+
345
+ def compile_node(node: dict[str, Any]) -> Node:
346
+ """Build the evaluation tree for one node of a spec ``validate_spec`` has already accepted."""
347
+ kind = node["type"]
348
+
349
+ if kind == "number":
350
+ return Const(node["value"])
351
+ if kind == "price":
352
+ return Price(node["field"])
353
+ if kind == "position_return":
354
+ return PositionReturn()
355
+ if kind == "bars_held":
356
+ return BarsHeld()
357
+ if kind == "math":
358
+ return Math(node["op"], compile_node(node["left"]), compile_node(node["right"]))
359
+ if kind == "previous":
360
+ return Previous(compile_node(node["of"]), node["bars"])
361
+ if kind == "indicator":
362
+ return _compile_indicator(node)
363
+
364
+ if kind == "compare":
365
+ return Compare(node["op"], compile_node(node["left"]), compile_node(node["right"]))
366
+ if kind == "cross":
367
+ return Cross(node["direction"], compile_node(node["left"]), compile_node(node["right"]))
368
+ if kind == "and":
369
+ return And([compile_node(arg) for arg in node["args"]])
370
+ if kind == "or":
371
+ return Or([compile_node(arg) for arg in node["args"]])
372
+ if kind == "not":
373
+ return Not(compile_node(node["arg"]))
374
+ if kind == "in_position":
375
+ return InPosition()
376
+
377
+ raise ValueError(f"Unknown node type {kind!r}; validate the spec first")
378
+
379
+
380
+ def _compile_indicator(node: dict[str, Any]) -> Node:
381
+ name = node["name"]
382
+ period = node["period"]
383
+ if name == "atr":
384
+ return Atr(period)
385
+
386
+ source = compile_node(node["source"])
387
+ if name == "sma":
388
+ return Sma(source, period)
389
+ if name == "ema":
390
+ return Ema(source, period)
391
+ if name == "rsi":
392
+ return Rsi(source, period)
393
+ if name == "highest":
394
+ return Highest(source, period)
395
+ if name == "lowest":
396
+ return Lowest(source, period)
397
+ if name == "stddev":
398
+ return StdDev(source, period)
399
+ if name == "roc":
400
+ return Roc(source, period)
401
+ if name == "bollinger_upper":
402
+ return Bollinger(source, period, node["mult"], 1.0)
403
+ if name == "bollinger_lower":
404
+ return Bollinger(source, period, node["mult"], -1.0)
405
+
406
+ raise ValueError(f"Unknown indicator {name!r}; validate the spec first")