ghosalquant 0.1.0__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 (158) hide show
  1. ghosalquant-0.2.0/PKG-INFO +291 -0
  2. ghosalquant-0.2.0/README.md +245 -0
  3. ghosalquant-0.2.0/src/ghosalquant/__init__.py +38 -0
  4. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/backtester/backtester_base.py +33 -7
  5. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/backtester/dataframe_backtester.py +14 -6
  6. ghosalquant-0.2.0/src/ghosalquant/blocks/__init__.py +18 -0
  7. ghosalquant-0.2.0/src/ghosalquant/blocks/nodes.py +406 -0
  8. ghosalquant-0.2.0/src/ghosalquant/blocks/runner.py +144 -0
  9. ghosalquant-0.2.0/src/ghosalquant/blocks/schema.py +317 -0
  10. ghosalquant-0.2.0/src/ghosalquant/blocks/strategy.py +105 -0
  11. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/broker_base.py +4 -0
  12. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/commissions.py +1 -1
  13. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/fills.py +63 -28
  14. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/order_book_sim.py +3 -0
  15. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/simulation.py +24 -34
  16. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/core/__init__.py +6 -2
  17. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/core/contracts.py +10 -3
  18. ghosalquant-0.2.0/src/ghosalquant/core/depth.py +102 -0
  19. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/core/metadata_keys.py +5 -2
  20. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/core/types.py +30 -31
  21. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/datasource_factory.py +12 -0
  22. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/recording_datasource.py +68 -28
  23. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/yfinance_datasource.py +3 -1
  24. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/yfinance_multi_datasource.py +3 -1
  25. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/execution/execution_system.py +243 -126
  26. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/metrics/__init__.py +3 -0
  27. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/metrics/gates.py +15 -9
  28. ghosalquant-0.2.0/src/ghosalquant/metrics/markouts.py +48 -0
  29. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/metrics/risk_adjusted.py +33 -2
  30. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/__init__.py +6 -1
  31. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/basic_portfolio.py +15 -10
  32. ghosalquant-0.2.0/src/ghosalquant/portfolio/fair_value.py +249 -0
  33. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/marks.py +42 -0
  34. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/portfolio_base.py +10 -0
  35. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/valuation.py +19 -41
  36. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/recording/events.py +29 -18
  37. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/recording/intervals.py +13 -14
  38. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/recording/recorder.py +48 -21
  39. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/recording/storage.py +12 -9
  40. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/__init__.py +6 -0
  41. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/builder.py +19 -1
  42. ghosalquant-0.2.0/src/ghosalquant/risk/buying_power.py +75 -0
  43. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/risk_manager.py +54 -9
  44. ghosalquant-0.2.0/src/ghosalquant/risk/rules/rule_buying_power.py +42 -0
  45. ghosalquant-0.2.0/src/ghosalquant/risk/rules/rule_long_only.py +27 -0
  46. ghosalquant-0.2.0/src/ghosalquant/risk/rules/rule_price_collar.py +30 -0
  47. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/types.py +4 -2
  48. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/state/event_store.py +4 -2
  49. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/util/backtester_utils.py +3 -0
  50. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/util/config.py +140 -121
  51. ghosalquant-0.2.0/src/ghosalquant.egg-info/PKG-INFO +291 -0
  52. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant.egg-info/SOURCES.txt +20 -0
  53. ghosalquant-0.2.0/tests/test_backtester.py +229 -0
  54. ghosalquant-0.2.0/tests/test_blocks.py +364 -0
  55. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_config.py +62 -0
  56. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_contracts.py +4 -2
  57. ghosalquant-0.2.0/tests/test_depth.py +103 -0
  58. ghosalquant-0.2.0/tests/test_execution_loop.py +259 -0
  59. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_execution_order_book.py +30 -4
  60. ghosalquant-0.2.0/tests/test_fair_value.py +264 -0
  61. ghosalquant-0.2.0/tests/test_markouts.py +70 -0
  62. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_metrics.py +71 -0
  63. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_order_book_sim_broker.py +111 -0
  64. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_order_book_types.py +0 -10
  65. ghosalquant-0.2.0/tests/test_pre_trade_rules.py +257 -0
  66. ghosalquant-0.2.0/tests/test_public_api.py +18 -0
  67. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_recording.py +84 -2
  68. ghosalquant-0.2.0/tests/test_replace_orders.py +390 -0
  69. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_risk_rules.py +89 -0
  70. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_state.py +21 -0
  71. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_valuation.py +16 -0
  72. ghosalquant-0.1.0/PKG-INFO +0 -113
  73. ghosalquant-0.1.0/README.md +0 -67
  74. ghosalquant-0.1.0/src/ghosalquant/__init__.py +0 -10
  75. ghosalquant-0.1.0/src/ghosalquant.egg-info/PKG-INFO +0 -113
  76. ghosalquant-0.1.0/tests/test_replace_orders.py +0 -188
  77. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/LICENSE +0 -0
  78. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/pyproject.toml +0 -0
  79. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/setup.cfg +0 -0
  80. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/backtest_ui/__init__.py +0 -0
  81. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/backtest_ui/__main__.py +0 -0
  82. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/backtest_ui/app.py +0 -0
  83. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/backtest_ui/runner.py +0 -0
  84. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/backtester/__init__.py +0 -0
  85. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/bench/__init__.py +0 -0
  86. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/bench/benchmark_buy_and_hold.py +0 -0
  87. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/bench/benchmark_trend_vol_target.py +0 -0
  88. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/__init__.py +0 -0
  89. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/builder.py +0 -0
  90. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/ibkr.py +0 -0
  91. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/open_orders.py +0 -0
  92. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/brokerage/simulated.py +0 -0
  93. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/compatibility/legacybacktester.py +0 -0
  94. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/compatibility/plotManager.py +0 -0
  95. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/compatibility/test_strategy.py +0 -0
  96. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/compatibility/trade.py +0 -0
  97. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/core/blackscholes.py +0 -0
  98. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/core/volatility.py +0 -0
  99. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/__init__.py +0 -0
  100. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/cboe_datasource.py +0 -0
  101. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/dataLayer.py +0 -0
  102. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/dataframe_datasource.py +0 -0
  103. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/datasource_base.py +0 -0
  104. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/dolt_datasource.py +0 -0
  105. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/listEditor.py +0 -0
  106. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/list_datasource.py +0 -0
  107. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/live_alpaca_datasource.py +0 -0
  108. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/live_ibkr_datasource.py +0 -0
  109. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/live_polygon_datasource.py +0 -0
  110. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/merge.py +0 -0
  111. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/nse_datasource.py +0 -0
  112. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/parquet_polygon_datasource.py +0 -0
  113. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/shocks.py +0 -0
  114. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/data_layer/staticUpdater.py +0 -0
  115. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/execution/__init__.py +0 -0
  116. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/execution/context.py +0 -0
  117. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/execution/sinks.py +0 -0
  118. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/execution/strategy_base.py +0 -0
  119. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/attribution.py +0 -0
  120. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/hedging.py +0 -0
  121. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/portfolio/lots.py +0 -0
  122. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/recording/__init__.py +0 -0
  123. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/cash_allocation.py +0 -0
  124. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_confidence_sizer.py +0 -0
  125. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_correlation_filter.py +0 -0
  126. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_drawdown_killswitch.py +0 -0
  127. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_integer_quantity.py +0 -0
  128. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_kelly_sizer.py +0 -0
  129. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_max_open_positions.py +0 -0
  130. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_max_symbol_exposure.py +0 -0
  131. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_regime_filter.py +0 -0
  132. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_signal_quantity_cap.py +0 -0
  133. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_symbol_capital_sizer.py +0 -0
  134. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/rules/rule_tick_rounding.py +0 -0
  135. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/risk/sizing.py +0 -0
  136. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/state/__init__.py +0 -0
  137. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/state/atomic.py +0 -0
  138. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/state/json_store.py +0 -0
  139. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/util/deprecation.py +0 -0
  140. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/util/rounding.py +0 -0
  141. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant/util/visualisation.py +0 -0
  142. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant.egg-info/dependency_links.txt +0 -0
  143. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant.egg-info/entry_points.txt +0 -0
  144. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant.egg-info/requires.txt +0 -0
  145. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/src/ghosalquant.egg-info/top_level.txt +0 -0
  146. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_cboe_datasource.py +0 -0
  147. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_dolt_datasource.py +0 -0
  148. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_example_options_momentum.py +0 -0
  149. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_example_order_book.py +0 -0
  150. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_execution.py +0 -0
  151. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_ibkr_broker.py +0 -0
  152. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_ibkr_real_client.py +0 -0
  153. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_legacy_backtester.py +0 -0
  154. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_limit_orders.py +0 -0
  155. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_live_sources.py +0 -0
  156. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_nse_datasource.py +0 -0
  157. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_shocks.py +0 -0
  158. {ghosalquant-0.1.0 → ghosalquant-0.2.0}/tests/test_volatility.py +0 -0
@@ -0,0 +1,291 @@
1
+ Metadata-Version: 2.4
2
+ Name: ghosalquant
3
+ Version: 0.2.0
4
+ Summary: Event-driven quantitative trading research framework
5
+ Author: Ghosal Quants
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Ghosal-Quants/GhosalQuant
8
+ Project-URL: Documentation, https://github.com/Ghosal-Quants/GhosalQuant/blob/main/design/user_guide.md
9
+ Project-URL: Repository, https://github.com/Ghosal-Quants/GhosalQuant
10
+ Project-URL: Issues, https://github.com/Ghosal-Quants/GhosalQuant/issues
11
+ Keywords: quant,trading,backtesting,algorithmic-trading,finance
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Financial and Insurance Industry
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Office/Business :: Financial :: Investment
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: numpy
27
+ Requires-Dist: pandas
28
+ Requires-Dist: pytz
29
+ Requires-Dist: requests
30
+ Requires-Dist: yfinance
31
+ Requires-Dist: PyYAML
32
+ Requires-Dist: python-dotenv
33
+ Requires-Dist: pyarrow
34
+ Requires-Dist: fastparquet
35
+ Requires-Dist: ib_insync
36
+ Requires-Dist: websockets
37
+ Provides-Extra: alpaca
38
+ Requires-Dist: alpaca-py; extra == "alpaca"
39
+ Provides-Extra: plotting
40
+ Requires-Dist: matplotlib; extra == "plotting"
41
+ Requires-Dist: plotly; extra == "plotting"
42
+ Provides-Extra: ui
43
+ Requires-Dist: customtkinter; extra == "ui"
44
+ Requires-Dist: matplotlib; extra == "ui"
45
+ Dynamic: license-file
46
+
47
+ # GhosalQuant
48
+ Ghosal Fund | Quantitative Trading Team Repository
49
+
50
+ An event-driven Python framework for backtesting and trading quantitative strategies. A strategy turns market events
51
+ (bars, order books, public trades) into signals. The same strategy class runs on historical data, recorded sessions,
52
+ a simulated broker or Interactive Brokers.
53
+
54
+ ## Documentation
55
+ - [User Guide](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/design/user_guide.md) - writing strategies,
56
+ configuring and running backtests, live trading, recording
57
+ - [System Overview](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/design/system-overview.md) - component
58
+ reference: core types, data sources, risk rules, brokers, configuration
59
+
60
+ ## Installation
61
+ Requires Python 3.10 or later.
62
+
63
+ ### Using a release
64
+ To write and backtest strategies, install the published package from [PyPI](https://pypi.org/project/ghosalquant/):
65
+ ```bash
66
+ pip install ghosalquant
67
+ ```
68
+ Pin a version (`pip install ghosalquant==0.1.0`) to keep results reproducible, and `pip install -U ghosalquant` to
69
+ upgrade. Optional extras add integrations:
70
+
71
+ | Extra | Adds |
72
+ |---|---|
73
+ | `alpaca` | Alpaca market data (`alpaca-py`) |
74
+ | `plotting` | Equity curve and results charts (`matplotlib`, `plotly`) |
75
+ | `ui` | The prototype backtest GUI, launched with `ghosalquant-ui` |
76
+
77
+ ```bash
78
+ pip install "ghosalquant[plotting,ui]"
79
+ ```
80
+
81
+ API keys for Alpaca and Polygon are read from environment variables or a `.env` file beside your config (see
82
+ [`.env.example`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/.env.example)). They are refused if written
83
+ into the config file.
84
+
85
+ ### For developers
86
+ To work on the framework itself, clone the repository and install it in editable mode, so your changes take effect
87
+ without reinstalling:
88
+ ```bash
89
+ git clone https://github.com/Ghosal-Quants/GhosalQuant.git
90
+ cd GhosalQuant
91
+ pip install -e ".[plotting,ui]" pytest
92
+ python -m pytest tests --ignore=tests/legacy
93
+ ```
94
+ Copy `.env.example` to `.env` and fill in any API keys you need.
95
+
96
+ Releases are published by CI: bump `__version__` in `src/ghosalquant/__init__.py`, push to `main`, then publish a
97
+ GitHub release tagged with that version (e.g. `v0.1.1`). The workflow runs the tests, builds the package and uploads
98
+ it to PyPI, and fails if the tag and version don't match.
99
+
100
+ ## Quick Start
101
+ Subclass `Strategy`, return a `Signal` from `on_market_data`, and backtest it on any OHLCV DataFrame. This runs as is,
102
+ with no config file, network or API keys:
103
+ ```python
104
+ import numpy as np
105
+ import pandas as pd
106
+
107
+ from ghosalquant import Signal, SignalType, Strategy, metadata_keys
108
+ from ghosalquant.backtester import DataFrameBacktester
109
+
110
+
111
+ class Trend(Strategy):
112
+ """Fully invested above the 50-day average, flat below it."""
113
+
114
+ def on_start(self):
115
+ self.closes = []
116
+
117
+ def on_end(self):
118
+ pass
119
+
120
+ def on_market_data(self, bar):
121
+ self.closes.append(bar.close)
122
+ if len(self.closes) < 50:
123
+ return None
124
+ weight = 1.0 if bar.close > np.mean(self.closes[-50:]) else 0.0
125
+ return Signal(
126
+ time_stamp=bar.time_stamp, symbol=bar.symbol, ref_price=bar.close,
127
+ signal_type=SignalType.BUY if weight else SignalType.SELL,
128
+ metadata={metadata_keys.TARGET_WEIGHT: weight},
129
+ )
130
+
131
+
132
+ # Two years of synthetic daily bars; any DataFrame with OHLCV columns works.
133
+ rng = np.random.default_rng(0)
134
+ close = 100 * np.exp(np.cumsum(rng.normal(0.0004, 0.012, 500)))
135
+ open_ = np.r_[100.0, close[:-1]] * np.exp(rng.normal(0.0, 0.003, 500))
136
+ df = pd.DataFrame(
137
+ {"Open": open_, "High": np.maximum(open_, close), "Low": np.minimum(open_, close),
138
+ "Close": close, "Volume": 1e6},
139
+ index=pd.bdate_range("2023-01-02", periods=500),
140
+ )
141
+
142
+ kpms = DataFrameBacktester(strategy=Trend(), dataframe=df, symbol="DEMO").run()
143
+ print(kpms)
144
+ ```
145
+ `run()` returns a `BacktestKPMs`: trade counts and win rate, realised and unrealised P&L, open positions, fills, max
146
+ drawdown, annualised return and volatility, and the Sharpe, Sortino and Calmar ratios. `total_trades` counts closed
147
+ lots: one per lot, or part of a lot, that an opposite fill closed. The backtester also exposes `equity_curve`, and
148
+ `plot_equity_curve` (`ghosalquant.util.visualisation`, `plotting` extra) draws it.
149
+
150
+ Every signal needs a size: a `quantity`, a `TARGET_WEIGHT` (a share of equity) in its metadata, or a sizing rule
151
+ such as `ConfidenceSizer` in the risk rules. A signal with none of these is dropped, with a warning. A
152
+ `TARGET_WEIGHT` buy is capped at the cash not committed to resting buys, less `RISK.cash_buffer` (default 1%) of
153
+ equity.
154
+
155
+ A simulated market order fills at the next bar's open, with the broker's spread, slippage and impact applied.
156
+
157
+ ### Configuring a run
158
+ With no config you get a simulated broker and no risk rules. To change that, pass a `Config`:
159
+ ```python
160
+ from ghosalquant.util.config import BrokerConfig, Config, RiskConfig, RiskRuleConfig, SimBrokerConfig
161
+
162
+ config = Config(
163
+ broker=BrokerConfig(sim=SimBrokerConfig(spread_bps=5.0, commission_per_share=0.005)),
164
+ risk=RiskConfig(rules=[RiskRuleConfig("MaxOpenPositions", {"max_open_positions": 3})]),
165
+ )
166
+ kpms = DataFrameBacktester(strategy=Trend(), dataframe=df, config=config).run()
167
+ ```
168
+ Or keep the same settings in YAML and pass `config_path="config.yaml"`, or load it with `Config.from_yaml`; see
169
+ [`examples/config.yaml`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/config.yaml). Only `SYSTEM`
170
+ is required. To have the library load the bars too, set `DATA` (`yfinance`, `polygon`, `live_ibkr` or
171
+ `live_alpaca`), plus `TIME_RANGE` for the historical sources, and use
172
+ `Backtester.from_config(strategy=Trend(), config_path="config.yaml")`.
173
+
174
+ ## Components
175
+
176
+ ### Strategies and execution
177
+ - `Strategy` handles bars (`on_market_data`). `OrderBookStrategy` handles order books and prints (`on_order_book`,
178
+ `on_public_trade`), with a `StrategyContext` holding the symbol's position, cash and resting orders. Optional
179
+ hooks: `on_fill`, `on_order_accepted`, `on_order_expired`. A hook returns `None`, one `Signal` or several.
180
+ - A `Signal` becomes a market order, or a limit order when it sets `limit_price`, with `liquidity` declaring maker or
181
+ taker. Metadata keys (`ghosalquant.core.metadata_keys`) carry the target weight, stop loss and take profit, order
182
+ time to live, and replacement of resting orders.
183
+ - `ExecutionSystem` runs one event loop for backtests, paper and live trading. For each event it expires resting
184
+ orders past their time to live, updates the broker, marks the portfolio, books fills, then sends the strategy's
185
+ signals through the risk manager to the broker.
186
+ - Signal sinks (`PrintSink`, `ListSink`, `DataFrameSink`) receive every signal before the risk manager. An
187
+ `ExecutionSystem` with no risk manager, portfolio or broker only emits signals to them.
188
+ - Benchmarks (`ghosalquant.bench`): `BenchmarkBuyAndHold` and `BenchmarkTrendVolTarget` (EMA trend with volatility
189
+ targeting).
190
+
191
+ ### Data sources (`ghosalquant.data_layer`)
192
+ | Source | Provides |
193
+ |---|---|
194
+ | `DataFrameDataSource`, `ListDataSource` | Bars from a DataFrame; any events from a list |
195
+ | `YFinanceDataSource`, `YFinanceMultiDataSource` | Historical bars from yfinance, one or several symbols |
196
+ | `ParquetPolygonDataSource` | Polygon aggregates from a local parquet store, filtered to a session and resampled |
197
+ | `LivePolygonDataSource` | Polygon WebSocket: bars, quotes, trades |
198
+ | `LiveIBKRDataSource` | IBKR: bars, market depth, tick-by-tick trades, for equities and options |
199
+ | `LiveAlpacaDataSource` | Alpaca: bars, top-of-book quotes, trades, for equities and options (`alpaca` extra) |
200
+ | `DoltOptionsDataSource`, `CboeEODDataSource`, `NSEDataSource` | End-of-day option chains from DoltHub, Cboe DataShop and NSE bhavcopies |
201
+ | `RecordingDataSource`, `RecordedDataSource` | Record a stream to disk as it is consumed; replay a recording |
202
+ | `MergedDataSource` (`merge_datasources`), `ShockedDataSource` | Merge streams in time order; replay with shifted prices or thinned depth |
203
+
204
+ ### Brokers (`ghosalquant.brokerage`)
205
+ - `SimBroker`: fills against bars, with spread, slippage, market impact, a cap on the share of bar volume, partial
206
+ fills, rejections, latency and per-share commission, with an optional seed.
207
+ - `OrderBookSimBroker`: fills against L2 books. A taker sweeps displayed depth; a maker queues behind the displayed
208
+ size at its price and fills when prints trade through it. Maker rebate, taker fee, lot size and order time to
209
+ live are all configurable.
210
+ - `IBKRBroker`: paper and live trading through `ib_insync`. Sends market and limit orders for equities and options,
211
+ persists submitted orders across restarts with `state_path`, and returns cash and positions with
212
+ `account_snapshot()`.
213
+
214
+ ### Risk (`ghosalquant.risk`)
215
+ `RiskManager` turns a signal into an order through a chain of rules, each of which can resize or block it.
216
+
217
+ | Purpose | Rules |
218
+ |---|---|
219
+ | Sizing | `ConfidenceSizer`, `SymbolCapitalFractionSizer`, `FractionalKellySizer`, `SignalQuantityCap` |
220
+ | Limits | `MaxOpenPositions`, `MaxSymbolExposure`, `CashAllocationRule`, `DrawdownKillSwitch`, `CorrelationFilter`, `RegimeFilter` |
221
+ | Account | `BuyingPower`, `LongOnly` |
222
+ | Venue | `IntegerQuantity`, `TickRounding`, `PriceCollar` |
223
+
224
+ ### Portfolio and valuation (`ghosalquant.portfolio`)
225
+ - `BasicPortfolio`: signed positions, LIFO lots, commissions, de-duplication of fills by `execution_id`, and
226
+ `adopt()` to start from a live account's cash and positions.
227
+ - `FairValueMarks`: a `mark_policy` for markets that trade rarely.
228
+ - `PortfolioValuationEngine`: marked NAV, liquidation equity into displayed bids, and a risk equity capped at cost.
229
+ - `hedging` gives net delta and gamma per underlier and the hedge quantity; `attribution` splits a position's change
230
+ in value into its causes.
231
+
232
+ ### Contracts and options (`ghosalquant.core`)
233
+ - `ContractRegistry` and `Contract`: multiplier, option right, strike, expiry, and cash or physical settlement.
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.
236
+ - `blackscholes` (price, greeks, implied volatility), and `VolSurface` / `Smile` built from a chain.
237
+
238
+ ### Metrics (`ghosalquant.metrics`)
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.
241
+ - `evaluate_gates(metrics, spec)` for go/no-go checks on a set of metrics.
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
+
251
+ ### Recording and state
252
+ - `ghosalquant.recording`: one durable stream per event kind. Each stream is a write-ahead log sealed into verified
253
+ Parquet segments, with books stored only when they change and prints de-duplicated.
254
+ - `ghosalquant.state`: atomic JSON writes, `VersionedJsonStateStore`, and the SQLite `EventLog` / `EventStore`
255
+ journal taken by `ExecutionSystem(journal=...)`.
256
+
257
+ ## Examples
258
+ Run as `python examples/<file>`. The yfinance examples plot with `matplotlib` (the `plotting` extra).
259
+
260
+ | File | Shows |
261
+ |---|---|
262
+ | [`example_main.py`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/example_main.py) | `DataFrameBacktester` on yfinance AAPL bars with `config.yaml` |
263
+ | [`example_comparison.py`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/example_comparison.py) | The example strategy against both benchmarks, equity curves overlaid |
264
+ | [`example_order_book_strategy.py`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/example_order_book_strategy.py) | `OrderBookStrategy` on synthetic L2 books and prints with `OrderBookSimBroker` |
265
+ | [`example_options_momentum.py`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/example_options_momentum.py) | Options from underlier bars and a quoted chain, with `ContractRegistry`, Kelly sizing and exposure caps |
266
+ | [`example_non_backtesting.py`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/example_non_backtesting.py) | `ExecutionSystem` on a live Polygon stream with simulated fills (needs `POLYGON_API_KEY`) |
267
+ | [`example_ibkr.py`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/example_ibkr.py) | IBKR live data and paper trading (needs TWS or IB Gateway running) |
268
+ | [`config.yaml`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/config.yaml) | Every config section, commented |
269
+
270
+ ## Project Structure
271
+ ```
272
+ src/ghosalquant/
273
+ core/ # Bar, OrderBook, PublicTrade, Signal, Order, Fill, Trade; contracts, Black-Scholes, vol surfaces
274
+ execution/ # Strategy, OrderBookStrategy, StrategyContext, ExecutionSystem, signal sinks
275
+ data_layer/ # Data sources, merging, shocks, recording; Polygon parquet store tools
276
+ backtester/ # Backtester, DataFrameBacktester
277
+ bench/ # Benchmark strategies
278
+ risk/ # RiskManager, risk rules, cash allocation, sizing helpers
279
+ portfolio/ # Portfolio protocol, BasicPortfolio, lots, marks, valuation, hedging, attribution
280
+ brokerage/ # Broker base, SimBroker, OrderBookSimBroker, IBKRBroker, fill and commission models
281
+ metrics/ # Risk-adjusted metrics, performance gates
282
+ recording/ # Recorders and segmented Parquet storage
283
+ state/ # Atomic JSON, versioned state store, SQLite event journal
284
+ util/ # Config, visualisation, KPM calculation, tick rounding
285
+ blocks/ # JSON strategy spec, validator and BlockStrategy for visual editors
286
+ backtest_ui/ # Prototype GUI (the ui extra)
287
+ compatibility/ # Deprecated LegacyBacktester
288
+ examples/ # Example scripts and a commented config.yaml
289
+ design/ # User guide, system overview, diagrams
290
+ tests/ # pytest suite
291
+ ```
@@ -0,0 +1,245 @@
1
+ # GhosalQuant
2
+ Ghosal Fund | Quantitative Trading Team Repository
3
+
4
+ An event-driven Python framework for backtesting and trading quantitative strategies. A strategy turns market events
5
+ (bars, order books, public trades) into signals. The same strategy class runs on historical data, recorded sessions,
6
+ a simulated broker or Interactive Brokers.
7
+
8
+ ## Documentation
9
+ - [User Guide](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/design/user_guide.md) - writing strategies,
10
+ configuring and running backtests, live trading, recording
11
+ - [System Overview](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/design/system-overview.md) - component
12
+ reference: core types, data sources, risk rules, brokers, configuration
13
+
14
+ ## Installation
15
+ Requires Python 3.10 or later.
16
+
17
+ ### Using a release
18
+ To write and backtest strategies, install the published package from [PyPI](https://pypi.org/project/ghosalquant/):
19
+ ```bash
20
+ pip install ghosalquant
21
+ ```
22
+ Pin a version (`pip install ghosalquant==0.1.0`) to keep results reproducible, and `pip install -U ghosalquant` to
23
+ upgrade. Optional extras add integrations:
24
+
25
+ | Extra | Adds |
26
+ |---|---|
27
+ | `alpaca` | Alpaca market data (`alpaca-py`) |
28
+ | `plotting` | Equity curve and results charts (`matplotlib`, `plotly`) |
29
+ | `ui` | The prototype backtest GUI, launched with `ghosalquant-ui` |
30
+
31
+ ```bash
32
+ pip install "ghosalquant[plotting,ui]"
33
+ ```
34
+
35
+ API keys for Alpaca and Polygon are read from environment variables or a `.env` file beside your config (see
36
+ [`.env.example`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/.env.example)). They are refused if written
37
+ into the config file.
38
+
39
+ ### For developers
40
+ To work on the framework itself, clone the repository and install it in editable mode, so your changes take effect
41
+ without reinstalling:
42
+ ```bash
43
+ git clone https://github.com/Ghosal-Quants/GhosalQuant.git
44
+ cd GhosalQuant
45
+ pip install -e ".[plotting,ui]" pytest
46
+ python -m pytest tests --ignore=tests/legacy
47
+ ```
48
+ Copy `.env.example` to `.env` and fill in any API keys you need.
49
+
50
+ Releases are published by CI: bump `__version__` in `src/ghosalquant/__init__.py`, push to `main`, then publish a
51
+ GitHub release tagged with that version (e.g. `v0.1.1`). The workflow runs the tests, builds the package and uploads
52
+ it to PyPI, and fails if the tag and version don't match.
53
+
54
+ ## Quick Start
55
+ Subclass `Strategy`, return a `Signal` from `on_market_data`, and backtest it on any OHLCV DataFrame. This runs as is,
56
+ with no config file, network or API keys:
57
+ ```python
58
+ import numpy as np
59
+ import pandas as pd
60
+
61
+ from ghosalquant import Signal, SignalType, Strategy, metadata_keys
62
+ from ghosalquant.backtester import DataFrameBacktester
63
+
64
+
65
+ class Trend(Strategy):
66
+ """Fully invested above the 50-day average, flat below it."""
67
+
68
+ def on_start(self):
69
+ self.closes = []
70
+
71
+ def on_end(self):
72
+ pass
73
+
74
+ def on_market_data(self, bar):
75
+ self.closes.append(bar.close)
76
+ if len(self.closes) < 50:
77
+ return None
78
+ weight = 1.0 if bar.close > np.mean(self.closes[-50:]) else 0.0
79
+ return Signal(
80
+ time_stamp=bar.time_stamp, symbol=bar.symbol, ref_price=bar.close,
81
+ signal_type=SignalType.BUY if weight else SignalType.SELL,
82
+ metadata={metadata_keys.TARGET_WEIGHT: weight},
83
+ )
84
+
85
+
86
+ # Two years of synthetic daily bars; any DataFrame with OHLCV columns works.
87
+ rng = np.random.default_rng(0)
88
+ close = 100 * np.exp(np.cumsum(rng.normal(0.0004, 0.012, 500)))
89
+ open_ = np.r_[100.0, close[:-1]] * np.exp(rng.normal(0.0, 0.003, 500))
90
+ df = pd.DataFrame(
91
+ {"Open": open_, "High": np.maximum(open_, close), "Low": np.minimum(open_, close),
92
+ "Close": close, "Volume": 1e6},
93
+ index=pd.bdate_range("2023-01-02", periods=500),
94
+ )
95
+
96
+ kpms = DataFrameBacktester(strategy=Trend(), dataframe=df, symbol="DEMO").run()
97
+ print(kpms)
98
+ ```
99
+ `run()` returns a `BacktestKPMs`: trade counts and win rate, realised and unrealised P&L, open positions, fills, max
100
+ drawdown, annualised return and volatility, and the Sharpe, Sortino and Calmar ratios. `total_trades` counts closed
101
+ lots: one per lot, or part of a lot, that an opposite fill closed. The backtester also exposes `equity_curve`, and
102
+ `plot_equity_curve` (`ghosalquant.util.visualisation`, `plotting` extra) draws it.
103
+
104
+ Every signal needs a size: a `quantity`, a `TARGET_WEIGHT` (a share of equity) in its metadata, or a sizing rule
105
+ such as `ConfidenceSizer` in the risk rules. A signal with none of these is dropped, with a warning. A
106
+ `TARGET_WEIGHT` buy is capped at the cash not committed to resting buys, less `RISK.cash_buffer` (default 1%) of
107
+ equity.
108
+
109
+ A simulated market order fills at the next bar's open, with the broker's spread, slippage and impact applied.
110
+
111
+ ### Configuring a run
112
+ With no config you get a simulated broker and no risk rules. To change that, pass a `Config`:
113
+ ```python
114
+ from ghosalquant.util.config import BrokerConfig, Config, RiskConfig, RiskRuleConfig, SimBrokerConfig
115
+
116
+ config = Config(
117
+ broker=BrokerConfig(sim=SimBrokerConfig(spread_bps=5.0, commission_per_share=0.005)),
118
+ risk=RiskConfig(rules=[RiskRuleConfig("MaxOpenPositions", {"max_open_positions": 3})]),
119
+ )
120
+ kpms = DataFrameBacktester(strategy=Trend(), dataframe=df, config=config).run()
121
+ ```
122
+ Or keep the same settings in YAML and pass `config_path="config.yaml"`, or load it with `Config.from_yaml`; see
123
+ [`examples/config.yaml`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/config.yaml). Only `SYSTEM`
124
+ is required. To have the library load the bars too, set `DATA` (`yfinance`, `polygon`, `live_ibkr` or
125
+ `live_alpaca`), plus `TIME_RANGE` for the historical sources, and use
126
+ `Backtester.from_config(strategy=Trend(), config_path="config.yaml")`.
127
+
128
+ ## Components
129
+
130
+ ### Strategies and execution
131
+ - `Strategy` handles bars (`on_market_data`). `OrderBookStrategy` handles order books and prints (`on_order_book`,
132
+ `on_public_trade`), with a `StrategyContext` holding the symbol's position, cash and resting orders. Optional
133
+ hooks: `on_fill`, `on_order_accepted`, `on_order_expired`. A hook returns `None`, one `Signal` or several.
134
+ - A `Signal` becomes a market order, or a limit order when it sets `limit_price`, with `liquidity` declaring maker or
135
+ taker. Metadata keys (`ghosalquant.core.metadata_keys`) carry the target weight, stop loss and take profit, order
136
+ time to live, and replacement of resting orders.
137
+ - `ExecutionSystem` runs one event loop for backtests, paper and live trading. For each event it expires resting
138
+ orders past their time to live, updates the broker, marks the portfolio, books fills, then sends the strategy's
139
+ signals through the risk manager to the broker.
140
+ - Signal sinks (`PrintSink`, `ListSink`, `DataFrameSink`) receive every signal before the risk manager. An
141
+ `ExecutionSystem` with no risk manager, portfolio or broker only emits signals to them.
142
+ - Benchmarks (`ghosalquant.bench`): `BenchmarkBuyAndHold` and `BenchmarkTrendVolTarget` (EMA trend with volatility
143
+ targeting).
144
+
145
+ ### Data sources (`ghosalquant.data_layer`)
146
+ | Source | Provides |
147
+ |---|---|
148
+ | `DataFrameDataSource`, `ListDataSource` | Bars from a DataFrame; any events from a list |
149
+ | `YFinanceDataSource`, `YFinanceMultiDataSource` | Historical bars from yfinance, one or several symbols |
150
+ | `ParquetPolygonDataSource` | Polygon aggregates from a local parquet store, filtered to a session and resampled |
151
+ | `LivePolygonDataSource` | Polygon WebSocket: bars, quotes, trades |
152
+ | `LiveIBKRDataSource` | IBKR: bars, market depth, tick-by-tick trades, for equities and options |
153
+ | `LiveAlpacaDataSource` | Alpaca: bars, top-of-book quotes, trades, for equities and options (`alpaca` extra) |
154
+ | `DoltOptionsDataSource`, `CboeEODDataSource`, `NSEDataSource` | End-of-day option chains from DoltHub, Cboe DataShop and NSE bhavcopies |
155
+ | `RecordingDataSource`, `RecordedDataSource` | Record a stream to disk as it is consumed; replay a recording |
156
+ | `MergedDataSource` (`merge_datasources`), `ShockedDataSource` | Merge streams in time order; replay with shifted prices or thinned depth |
157
+
158
+ ### Brokers (`ghosalquant.brokerage`)
159
+ - `SimBroker`: fills against bars, with spread, slippage, market impact, a cap on the share of bar volume, partial
160
+ fills, rejections, latency and per-share commission, with an optional seed.
161
+ - `OrderBookSimBroker`: fills against L2 books. A taker sweeps displayed depth; a maker queues behind the displayed
162
+ size at its price and fills when prints trade through it. Maker rebate, taker fee, lot size and order time to
163
+ live are all configurable.
164
+ - `IBKRBroker`: paper and live trading through `ib_insync`. Sends market and limit orders for equities and options,
165
+ persists submitted orders across restarts with `state_path`, and returns cash and positions with
166
+ `account_snapshot()`.
167
+
168
+ ### Risk (`ghosalquant.risk`)
169
+ `RiskManager` turns a signal into an order through a chain of rules, each of which can resize or block it.
170
+
171
+ | Purpose | Rules |
172
+ |---|---|
173
+ | Sizing | `ConfidenceSizer`, `SymbolCapitalFractionSizer`, `FractionalKellySizer`, `SignalQuantityCap` |
174
+ | Limits | `MaxOpenPositions`, `MaxSymbolExposure`, `CashAllocationRule`, `DrawdownKillSwitch`, `CorrelationFilter`, `RegimeFilter` |
175
+ | Account | `BuyingPower`, `LongOnly` |
176
+ | Venue | `IntegerQuantity`, `TickRounding`, `PriceCollar` |
177
+
178
+ ### Portfolio and valuation (`ghosalquant.portfolio`)
179
+ - `BasicPortfolio`: signed positions, LIFO lots, commissions, de-duplication of fills by `execution_id`, and
180
+ `adopt()` to start from a live account's cash and positions.
181
+ - `FairValueMarks`: a `mark_policy` for markets that trade rarely.
182
+ - `PortfolioValuationEngine`: marked NAV, liquidation equity into displayed bids, and a risk equity capped at cost.
183
+ - `hedging` gives net delta and gamma per underlier and the hedge quantity; `attribution` splits a position's change
184
+ in value into its causes.
185
+
186
+ ### Contracts and options (`ghosalquant.core`)
187
+ - `ContractRegistry` and `Contract`: multiplier, option right, strike, expiry, and cash or physical settlement.
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.
190
+ - `blackscholes` (price, greeks, implied volatility), and `VolSurface` / `Smile` built from a chain.
191
+
192
+ ### Metrics (`ghosalquant.metrics`)
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.
195
+ - `evaluate_gates(metrics, spec)` for go/no-go checks on a set of metrics.
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
+
205
+ ### Recording and state
206
+ - `ghosalquant.recording`: one durable stream per event kind. Each stream is a write-ahead log sealed into verified
207
+ Parquet segments, with books stored only when they change and prints de-duplicated.
208
+ - `ghosalquant.state`: atomic JSON writes, `VersionedJsonStateStore`, and the SQLite `EventLog` / `EventStore`
209
+ journal taken by `ExecutionSystem(journal=...)`.
210
+
211
+ ## Examples
212
+ Run as `python examples/<file>`. The yfinance examples plot with `matplotlib` (the `plotting` extra).
213
+
214
+ | File | Shows |
215
+ |---|---|
216
+ | [`example_main.py`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/example_main.py) | `DataFrameBacktester` on yfinance AAPL bars with `config.yaml` |
217
+ | [`example_comparison.py`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/example_comparison.py) | The example strategy against both benchmarks, equity curves overlaid |
218
+ | [`example_order_book_strategy.py`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/example_order_book_strategy.py) | `OrderBookStrategy` on synthetic L2 books and prints with `OrderBookSimBroker` |
219
+ | [`example_options_momentum.py`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/example_options_momentum.py) | Options from underlier bars and a quoted chain, with `ContractRegistry`, Kelly sizing and exposure caps |
220
+ | [`example_non_backtesting.py`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/example_non_backtesting.py) | `ExecutionSystem` on a live Polygon stream with simulated fills (needs `POLYGON_API_KEY`) |
221
+ | [`example_ibkr.py`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/example_ibkr.py) | IBKR live data and paper trading (needs TWS or IB Gateway running) |
222
+ | [`config.yaml`](https://github.com/Ghosal-Quants/GhosalQuant/blob/main/examples/config.yaml) | Every config section, commented |
223
+
224
+ ## Project Structure
225
+ ```
226
+ src/ghosalquant/
227
+ core/ # Bar, OrderBook, PublicTrade, Signal, Order, Fill, Trade; contracts, Black-Scholes, vol surfaces
228
+ execution/ # Strategy, OrderBookStrategy, StrategyContext, ExecutionSystem, signal sinks
229
+ data_layer/ # Data sources, merging, shocks, recording; Polygon parquet store tools
230
+ backtester/ # Backtester, DataFrameBacktester
231
+ bench/ # Benchmark strategies
232
+ risk/ # RiskManager, risk rules, cash allocation, sizing helpers
233
+ portfolio/ # Portfolio protocol, BasicPortfolio, lots, marks, valuation, hedging, attribution
234
+ brokerage/ # Broker base, SimBroker, OrderBookSimBroker, IBKRBroker, fill and commission models
235
+ metrics/ # Risk-adjusted metrics, performance gates
236
+ recording/ # Recorders and segmented Parquet storage
237
+ state/ # Atomic JSON, versioned state store, SQLite event journal
238
+ util/ # Config, visualisation, KPM calculation, tick rounding
239
+ blocks/ # JSON strategy spec, validator and BlockStrategy for visual editors
240
+ backtest_ui/ # Prototype GUI (the ui extra)
241
+ compatibility/ # Deprecated LegacyBacktester
242
+ examples/ # Example scripts and a commented config.yaml
243
+ design/ # User guide, system overview, diagrams
244
+ tests/ # pytest suite
245
+ ```
@@ -0,0 +1,38 @@
1
+ from ghosalquant.execution.strategy_base import OrderBookStrategy, Strategy
2
+ import ghosalquant.core.types as types
3
+ from ghosalquant.core import metadata_keys
4
+ from ghosalquant.core.types import (
5
+ BacktestKPMs,
6
+ Bar,
7
+ BookLevel,
8
+ EquityPoint,
9
+ Fill,
10
+ Liquidity,
11
+ Order,
12
+ OrderBook,
13
+ PublicTrade,
14
+ Signal,
15
+ SignalType,
16
+ Trade,
17
+ )
18
+
19
+ __version__ = "0.2.0"
20
+
21
+ __all__ = [
22
+ "OrderBookStrategy",
23
+ "Strategy",
24
+ "types",
25
+ "metadata_keys",
26
+ "BacktestKPMs",
27
+ "Bar",
28
+ "BookLevel",
29
+ "EquityPoint",
30
+ "Fill",
31
+ "Liquidity",
32
+ "Order",
33
+ "OrderBook",
34
+ "PublicTrade",
35
+ "Signal",
36
+ "SignalType",
37
+ "Trade",
38
+ ]
@@ -1,4 +1,6 @@
1
1
  import asyncio
2
+ from datetime import timedelta
3
+ from pathlib import Path
2
4
  from typing import final, Iterable
3
5
 
4
6
  from ..data_layer.datasource_factory import datasource_from_config
@@ -10,6 +12,7 @@ from ..execution.sinks import SignalSink
10
12
  from ..core.contracts import ContractRegistry
11
13
  from ..core.types import Order, BacktestKPMs, EquityPoint
12
14
  from ..portfolio.basic_portfolio import BasicPortfolio
15
+ from ..portfolio.marks import Marker, MarkPolicy
13
16
  from ..portfolio.portfolio_base import Portfolio
14
17
  from ..brokerage.broker_base import Broker
15
18
  from ..risk.builder import build_risk_manager
@@ -30,14 +33,16 @@ class Backtester:
30
33
  broker: Broker | None = None,
31
34
  config: Config | None = None,
32
35
  contracts: ContractRegistry | None = None,
36
+ mark_policy: Marker = MarkPolicy.MID,
37
+ snapshot_interval: timedelta = timedelta(seconds=1),
33
38
  ) -> None:
34
39
  self.config = config
35
40
 
36
41
  if portfolio is None:
37
42
  portfolio = BasicPortfolio(init_capital=10_000.0, contracts=contracts)
38
43
 
39
- if risk_manager is None and config is not None and config.system.use_risk_manager:
40
- risk_manager = build_risk_manager(config.risk)
44
+ if risk_manager is None:
45
+ risk_manager = _risk_manager_for(config)
41
46
 
42
47
  self.execution_system = ExecutionSystem(
43
48
  data_src = data_src,
@@ -47,6 +52,9 @@ class Backtester:
47
52
  portfolio = portfolio,
48
53
  broker = broker,
49
54
  contracts = contracts,
55
+ mark_policy = mark_policy,
56
+ snapshot_interval = snapshot_interval,
57
+ replay_observed_at = True,
50
58
  )
51
59
 
52
60
  self._portfolio = self.execution_system.portfolio
@@ -55,7 +63,8 @@ class Backtester:
55
63
  def from_config(cls,
56
64
  *,
57
65
  strategy: Strategy,
58
- config_path: str,
66
+ config_path: str | None = None,
67
+ config: Config | None = None,
59
68
 
60
69
  # Optional overrides
61
70
  signal_destination: SignalSink | None = None,
@@ -65,15 +74,14 @@ class Backtester:
65
74
  contracts: ContractRegistry | None = None,
66
75
  ) -> "Backtester":
67
76
 
68
- cfg = load_config(config_path)
77
+ if config is None and config_path is None:
78
+ raise TypeError("from_config() needs config= or config_path=")
79
+ cfg = _resolve_config(config, config_path)
69
80
  data_src = datasource_from_config(cfg, contracts=contracts)
70
81
 
71
82
  if portfolio is None:
72
83
  portfolio = BasicPortfolio(init_capital=float(init_capital), contracts=contracts)
73
84
 
74
- if risk_manager is None and cfg.system.use_risk_manager:
75
- risk_manager = build_risk_manager(cfg.risk)
76
-
77
85
  return cls(
78
86
  strategy=strategy,
79
87
  data_src=data_src,
@@ -127,3 +135,21 @@ class Backtester:
127
135
  return asyncio.run(self.run_async())
128
136
 
129
137
  raise RuntimeError("Cannot run backtest synchronously within an existing event loop. Please use run_async() instead.")
138
+
139
+
140
+ def _resolve_config(config: Config | None, config_path: str | Path | None) -> Config:
141
+ """The ``Config`` object if given, else the YAML file, else the defaults."""
142
+ if config is not None and config_path is not None:
143
+ raise ValueError("Pass config or config_path, not both.")
144
+ if config is not None:
145
+ return config
146
+ if config_path is not None:
147
+ return load_config(config_path)
148
+ return Config()
149
+
150
+
151
+ def _risk_manager_for(config: Config | None) -> RiskManager:
152
+ # A Portfolio needs a RiskManager, so with the flag off this one applies no rules.
153
+ if config is not None and config.system.use_risk_manager:
154
+ return build_risk_manager(config.risk)
155
+ return RiskManager(rules=[])