ghosalquant 0.1.0__py3-none-any.whl

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 (104) hide show
  1. ghosalquant/__init__.py +10 -0
  2. ghosalquant/backtest_ui/__init__.py +7 -0
  3. ghosalquant/backtest_ui/__main__.py +10 -0
  4. ghosalquant/backtest_ui/app.py +148 -0
  5. ghosalquant/backtest_ui/runner.py +109 -0
  6. ghosalquant/backtester/__init__.py +7 -0
  7. ghosalquant/backtester/backtester_base.py +129 -0
  8. ghosalquant/backtester/dataframe_backtester.py +95 -0
  9. ghosalquant/bench/__init__.py +7 -0
  10. ghosalquant/bench/benchmark_buy_and_hold.py +51 -0
  11. ghosalquant/bench/benchmark_trend_vol_target.py +179 -0
  12. ghosalquant/brokerage/__init__.py +26 -0
  13. ghosalquant/brokerage/broker_base.py +123 -0
  14. ghosalquant/brokerage/builder.py +42 -0
  15. ghosalquant/brokerage/commissions.py +38 -0
  16. ghosalquant/brokerage/fills.py +470 -0
  17. ghosalquant/brokerage/ibkr.py +496 -0
  18. ghosalquant/brokerage/open_orders.py +27 -0
  19. ghosalquant/brokerage/order_book_sim.py +77 -0
  20. ghosalquant/brokerage/simulated.py +80 -0
  21. ghosalquant/brokerage/simulation.py +303 -0
  22. ghosalquant/compatibility/legacybacktester.py +253 -0
  23. ghosalquant/compatibility/plotManager.py +71 -0
  24. ghosalquant/compatibility/test_strategy.py +63 -0
  25. ghosalquant/compatibility/trade.py +70 -0
  26. ghosalquant/core/__init__.py +59 -0
  27. ghosalquant/core/blackscholes.py +169 -0
  28. ghosalquant/core/contracts.py +155 -0
  29. ghosalquant/core/metadata_keys.py +59 -0
  30. ghosalquant/core/types.py +454 -0
  31. ghosalquant/core/volatility.py +163 -0
  32. ghosalquant/data_layer/__init__.py +29 -0
  33. ghosalquant/data_layer/cboe_datasource.py +150 -0
  34. ghosalquant/data_layer/dataLayer.py +127 -0
  35. ghosalquant/data_layer/dataframe_datasource.py +76 -0
  36. ghosalquant/data_layer/datasource_base.py +18 -0
  37. ghosalquant/data_layer/datasource_factory.py +55 -0
  38. ghosalquant/data_layer/dolt_datasource.py +159 -0
  39. ghosalquant/data_layer/listEditor.py +372 -0
  40. ghosalquant/data_layer/list_datasource.py +27 -0
  41. ghosalquant/data_layer/live_alpaca_datasource.py +190 -0
  42. ghosalquant/data_layer/live_ibkr_datasource.py +246 -0
  43. ghosalquant/data_layer/live_polygon_datasource.py +264 -0
  44. ghosalquant/data_layer/merge.py +52 -0
  45. ghosalquant/data_layer/nse_datasource.py +126 -0
  46. ghosalquant/data_layer/parquet_polygon_datasource.py +108 -0
  47. ghosalquant/data_layer/recording_datasource.py +251 -0
  48. ghosalquant/data_layer/shocks.py +99 -0
  49. ghosalquant/data_layer/staticUpdater.py +408 -0
  50. ghosalquant/data_layer/yfinance_datasource.py +60 -0
  51. ghosalquant/data_layer/yfinance_multi_datasource.py +120 -0
  52. ghosalquant/execution/__init__.py +16 -0
  53. ghosalquant/execution/context.py +54 -0
  54. ghosalquant/execution/execution_system.py +533 -0
  55. ghosalquant/execution/sinks.py +122 -0
  56. ghosalquant/execution/strategy_base.py +109 -0
  57. ghosalquant/metrics/__init__.py +25 -0
  58. ghosalquant/metrics/gates.py +150 -0
  59. ghosalquant/metrics/risk_adjusted.py +196 -0
  60. ghosalquant/portfolio/__init__.py +30 -0
  61. ghosalquant/portfolio/attribution.py +81 -0
  62. ghosalquant/portfolio/basic_portfolio.py +373 -0
  63. ghosalquant/portfolio/hedging.py +87 -0
  64. ghosalquant/portfolio/lots.py +63 -0
  65. ghosalquant/portfolio/marks.py +58 -0
  66. ghosalquant/portfolio/portfolio_base.py +104 -0
  67. ghosalquant/portfolio/valuation.py +694 -0
  68. ghosalquant/recording/__init__.py +111 -0
  69. ghosalquant/recording/events.py +204 -0
  70. ghosalquant/recording/intervals.py +236 -0
  71. ghosalquant/recording/recorder.py +531 -0
  72. ghosalquant/recording/storage.py +607 -0
  73. ghosalquant/risk/__init__.py +56 -0
  74. ghosalquant/risk/builder.py +151 -0
  75. ghosalquant/risk/cash_allocation.py +285 -0
  76. ghosalquant/risk/risk_manager.py +109 -0
  77. ghosalquant/risk/rules/rule_confidence_sizer.py +32 -0
  78. ghosalquant/risk/rules/rule_correlation_filter.py +105 -0
  79. ghosalquant/risk/rules/rule_drawdown_killswitch.py +75 -0
  80. ghosalquant/risk/rules/rule_integer_quantity.py +27 -0
  81. ghosalquant/risk/rules/rule_kelly_sizer.py +74 -0
  82. ghosalquant/risk/rules/rule_max_open_positions.py +27 -0
  83. ghosalquant/risk/rules/rule_max_symbol_exposure.py +118 -0
  84. ghosalquant/risk/rules/rule_regime_filter.py +50 -0
  85. ghosalquant/risk/rules/rule_signal_quantity_cap.py +28 -0
  86. ghosalquant/risk/rules/rule_symbol_capital_sizer.py +78 -0
  87. ghosalquant/risk/rules/rule_tick_rounding.py +40 -0
  88. ghosalquant/risk/sizing.py +46 -0
  89. ghosalquant/risk/types.py +69 -0
  90. ghosalquant/state/__init__.py +23 -0
  91. ghosalquant/state/atomic.py +74 -0
  92. ghosalquant/state/event_store.py +249 -0
  93. ghosalquant/state/json_store.py +85 -0
  94. ghosalquant/util/backtester_utils.py +118 -0
  95. ghosalquant/util/config.py +522 -0
  96. ghosalquant/util/deprecation.py +19 -0
  97. ghosalquant/util/rounding.py +25 -0
  98. ghosalquant/util/visualisation.py +162 -0
  99. ghosalquant-0.1.0.dist-info/METADATA +113 -0
  100. ghosalquant-0.1.0.dist-info/RECORD +104 -0
  101. ghosalquant-0.1.0.dist-info/WHEEL +5 -0
  102. ghosalquant-0.1.0.dist-info/entry_points.txt +2 -0
  103. ghosalquant-0.1.0.dist-info/licenses/LICENSE +21 -0
  104. ghosalquant-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,179 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from collections import deque
5
+ from dataclasses import dataclass
6
+ from typing import Deque, Optional
7
+
8
+ from ..core.types import Bar, Signal, SignalType
9
+ from ..execution.strategy_base import Strategy
10
+
11
+ EPS = 1e-4
12
+
13
+
14
+ @dataclass
15
+ class EMA:
16
+ span: int
17
+ value: Optional[float] = None
18
+
19
+ def update(self, x: float) -> float:
20
+ a = 2.0 / (self.span + 1.0)
21
+ self.value = x if self.value is None else (1.0 - a) * self.value + a * x
22
+ return self.value
23
+
24
+
25
+ @dataclass
26
+ class EWStd:
27
+ span: int
28
+ mean: float = 0.0
29
+ var: float = 0.0
30
+ init: bool = False
31
+
32
+ def update(self, x: float) -> float:
33
+ a = 2.0 / (self.span + 1.0)
34
+ if not self.init:
35
+ self.mean = x
36
+ self.var = 0.0
37
+ self.init = True
38
+ return 0.0
39
+
40
+ prev_mean = self.mean
41
+ self.mean = (1.0 - a) * self.mean + a * x
42
+ self.var = (1.0 - a) * self.var + a * (x - prev_mean) * (x - prev_mean)
43
+ return math.sqrt(max(self.var, 0.0))
44
+
45
+
46
+ class BenchmarkTrendVolTarget(Strategy):
47
+ """
48
+ Long-only single-symbol trend benchmark with volatility targeting.
49
+
50
+ Emits a ``target_weight`` instead of a quantity; RiskManager sizes the order from equity.
51
+ """
52
+
53
+ def __init__(self) -> None:
54
+ super().__init__()
55
+
56
+ self.ema20 = EMA(20)
57
+ self.ema80 = EMA(80)
58
+ self.ema200 = EMA(200)
59
+ self.vol = EWStd(30)
60
+ self.vol_hist: Deque[float] = deque(maxlen=252)
61
+
62
+ self._symbol: str | None = None
63
+ self.prev_close: Optional[float] = None
64
+ self.vol_blocked: bool = False
65
+ self.target_weight: float = 0.0
66
+
67
+ self.TARGET_VOL = 0.010
68
+ self.MAX_POS = 1.0
69
+ self.VOL_FLOOR = 0.006
70
+
71
+ self.ENTER_TREND = 0.0025
72
+ self.EXIT_TREND = 0.0006
73
+
74
+ self.WEAK_TREND = 0.0030
75
+ self.STRONG_TREND = 0.0060
76
+ self.WEAK_SCALE = 0.25
77
+ self.MID_SCALE = 0.60
78
+
79
+ self.SMOOTH_ALPHA = 0.25
80
+
81
+ self.VOL_EXIT_MULT = 2.1
82
+ self.VOL_ENTER_MULT = 1.9
83
+
84
+ self.SL_PCT = None
85
+ self.TP_PCT = None
86
+
87
+ def on_start(self) -> None:
88
+ return None
89
+
90
+ def on_end(self) -> None:
91
+ return None
92
+
93
+ def _validate_symbol(self, symbol: str) -> None:
94
+ if self._symbol is None:
95
+ self._symbol = symbol
96
+ return
97
+
98
+ if symbol != self._symbol:
99
+ raise ValueError(
100
+ "BenchmarkTrendVolTarget is single-symbol only. "
101
+ f"Received {symbol!r} after {self._symbol!r}."
102
+ )
103
+
104
+ def on_market_data(self, bar: Bar) -> Optional[Signal]:
105
+ self._validate_symbol(bar.symbol)
106
+ px = float(bar.close)
107
+
108
+ if self.prev_close is None:
109
+ self.prev_close = px
110
+ self.ema20.update(px)
111
+ self.ema80.update(px)
112
+ self.ema200.update(px)
113
+ return None
114
+
115
+ r = (px / self.prev_close) - 1.0
116
+ self.prev_close = px
117
+
118
+ e20 = self.ema20.update(px)
119
+ e80 = self.ema80.update(px)
120
+ e200 = self.ema200.update(px)
121
+
122
+ trend = (e20 - e80) / px if px != 0.0 else 0.0
123
+
124
+ v = self.vol.update(r)
125
+ if v > 0.0 and not math.isnan(v):
126
+ self.vol_hist.append(v)
127
+
128
+ v_med = None
129
+ if len(self.vol_hist) >= 60:
130
+ vs = sorted(self.vol_hist)
131
+ v_med = vs[len(vs) // 2]
132
+
133
+ raw_target = 0.0
134
+ if v_med is not None and v > 0.0 and not any(map(math.isnan, [px, trend, v, v_med, e200])):
135
+ exit_th = v_med * self.VOL_EXIT_MULT
136
+ enter_th = v_med * self.VOL_ENTER_MULT
137
+
138
+ if (not self.vol_blocked) and v > exit_th:
139
+ self.vol_blocked = True
140
+ elif self.vol_blocked and v < enter_th:
141
+ self.vol_blocked = False
142
+
143
+ trend_gate = self.EXIT_TREND if self.target_weight > EPS else self.ENTER_TREND
144
+ if (not self.vol_blocked) and (px >= e200) and (trend >= trend_gate):
145
+ v_eff = max(v, self.VOL_FLOOR)
146
+ lev = max(0.0, min(self.TARGET_VOL / v_eff, self.MAX_POS))
147
+
148
+ strength = abs(trend)
149
+ if strength < self.WEAK_TREND:
150
+ lev *= self.WEAK_SCALE
151
+ elif strength < self.STRONG_TREND:
152
+ lev *= self.MID_SCALE
153
+
154
+ raw_target = lev
155
+
156
+ previous_target = self.target_weight
157
+ self.target_weight = max(
158
+ 0.0,
159
+ min(1.0, (1.0 - self.SMOOTH_ALPHA) * previous_target + self.SMOOTH_ALPHA * raw_target),
160
+ )
161
+
162
+ if v_med is None and self.target_weight <= EPS and previous_target <= EPS:
163
+ return None
164
+
165
+ metadata: dict[str, float] = {"target_weight": self.target_weight}
166
+ if self.SL_PCT is not None and self.target_weight > 0.0:
167
+ metadata["stop_loss"] = px * (1.0 - float(self.SL_PCT))
168
+ if self.TP_PCT is not None and self.target_weight > 0.0:
169
+ metadata["take_profit"] = px * (1.0 + float(self.TP_PCT))
170
+
171
+ return Signal(
172
+ time_stamp=bar.time_stamp,
173
+ symbol=bar.symbol,
174
+ signal_type=SignalType.BUY if self.target_weight > previous_target else SignalType.SELL,
175
+ ref_price=px,
176
+ quantity=None,
177
+ confidence=1.0,
178
+ metadata=metadata,
179
+ )
@@ -0,0 +1,26 @@
1
+ from .broker_base import Broker
2
+ from .commissions import CommissionModel, MakerTakerCommission, PerShareCommission
3
+ from .fills import BarParticipationFill, FillModel, PlannedFill, QueueAwareFill, RestingOrder, SimulationContext
4
+ from .ibkr import IBKRBroker
5
+ from .open_orders import OpenOrderQueries
6
+ from .order_book_sim import OrderBookSimBroker
7
+ from .simulated import SimBroker
8
+ from .simulation import SimulatedBroker
9
+
10
+ __all__ = [
11
+ "Broker",
12
+ "CommissionModel",
13
+ "MakerTakerCommission",
14
+ "PerShareCommission",
15
+ "BarParticipationFill",
16
+ "FillModel",
17
+ "PlannedFill",
18
+ "QueueAwareFill",
19
+ "RestingOrder",
20
+ "SimulationContext",
21
+ "IBKRBroker",
22
+ "OpenOrderQueries",
23
+ "OrderBookSimBroker",
24
+ "SimBroker",
25
+ "SimulatedBroker",
26
+ ]
@@ -0,0 +1,123 @@
1
+ from abc import ABC, abstractmethod
2
+ from datetime import datetime, timedelta
3
+
4
+ from ..core import metadata_keys
5
+ from ..core.types import Bar, CashFlow, Fill, Liquidity, MarketEvent, Order, OrderBook, PublicTrade
6
+
7
+
8
+ def order_expires_at(order: Order, default_max_age_seconds: float | None = None) -> datetime | None:
9
+ """When an order's time to live runs out: its own ``MAX_ORDER_AGE_SECONDS``, else the broker's default."""
10
+ value = (order.metadata or {}).get(metadata_keys.MAX_ORDER_AGE_SECONDS)
11
+ max_age = float(value) if value is not None and float(value) > 0.0 else default_max_age_seconds
12
+ if max_age is None:
13
+ return None
14
+ return order.time_stamp + timedelta(seconds=max_age)
15
+
16
+
17
+ def order_liquidity(order: Order) -> Liquidity:
18
+ """The liquidity an order declared: the field, else the older metadata key, else a resting maker."""
19
+ if order.liquidity is not None:
20
+ return order.liquidity
21
+ value = (order.metadata or {}).get(metadata_keys.LIQUIDITY)
22
+ return Liquidity(str(value).lower()) if value is not None else Liquidity.MAKER
23
+
24
+
25
+ def order_slot(order: Order) -> str | None:
26
+ slot = (order.metadata or {}).get(metadata_keys.ORDER_SLOT)
27
+ return None if slot is None else str(slot)
28
+
29
+
30
+ def cancels_remainder_after_first_fill(order: Order) -> bool:
31
+ return bool((order.metadata or {}).get(metadata_keys.CANCEL_REMAINDER_AFTER_FIRST_FILL))
32
+
33
+
34
+ class Broker(ABC):
35
+ # ----- Managing Connection ----- #
36
+ async def connect(self) -> None:
37
+ """
38
+ Optionally can be overridden by subclasses if connection management is needed on startup
39
+ (no-op for simulation brokers)
40
+ """
41
+ return None
42
+
43
+ async def disconnect(self) -> None:
44
+ """
45
+ Optionally can be overridden by subclasses if connection management is needed on shutdown
46
+ (no-op for simulation brokers)
47
+ """
48
+ return None
49
+
50
+ # ----- Market data ----- #
51
+ def on_bar(self, bar: Bar) -> None:
52
+ """
53
+ Consume the latest market bar before fills are collected.
54
+
55
+ Live brokers can ignore this hook. Simulation brokers can use it to
56
+ advance market time and fill orders against observed liquidity.
57
+ """
58
+ return None
59
+
60
+ def on_order_book(self, book: OrderBook) -> OrderBook:
61
+ """
62
+ Consume the latest order book before fills are collected.
63
+
64
+ Returns the book the strategy should see. The default returns it unchanged; a simulation
65
+ broker may return a copy adjusted for the strategy's own resting orders or consumed depth.
66
+ The portfolio is always marked from the raw book, never from this return value.
67
+ """
68
+ return book
69
+
70
+ def on_public_trade(self, trade: PublicTrade) -> None:
71
+ """Consume a public print before fills are collected. Live brokers can ignore this hook."""
72
+ return None
73
+
74
+ def on_market_event(self, event: MarketEvent) -> MarketEvent:
75
+ """Route a market event to the matching hook and return what the strategy should see."""
76
+ match event:
77
+ case Bar():
78
+ self.on_bar(event)
79
+ return event
80
+ case OrderBook():
81
+ return self.on_order_book(event)
82
+ case PublicTrade():
83
+ self.on_public_trade(event)
84
+ return event
85
+ raise TypeError(f"Unsupported market event: {type(event).__name__}")
86
+
87
+ # ----- Order lifecycle ----- #
88
+ def next_order_expiry_at(self) -> datetime | None:
89
+ """When the earliest resting order falls due, or ``None`` if the broker expires none."""
90
+ return None
91
+
92
+ def expire_orders(self, *, now: datetime) -> list[str]:
93
+ """
94
+ Expire resting orders past their time to live, returning the ids expired.
95
+
96
+ The default expires nothing, for a broker with no time to live. The ``ExecutionSystem``
97
+ drives this from the clock, so an order goes the moment it falls due rather than when its
98
+ symbol next ticks.
99
+ """
100
+ return []
101
+
102
+ # ----- Execution ----- #
103
+ @abstractmethod
104
+ def submit(self, order: Order) -> str | None:
105
+ """
106
+ Submit an order using a broker-specific API
107
+
108
+ Optionally returns a broker-specific order ID for tracking purposes
109
+ """
110
+ ...
111
+
112
+ @abstractmethod
113
+ def get_fills(self) -> list[Fill]:
114
+ """
115
+ Get fills since the last call
116
+
117
+ Implementations should return a possibly empty list, and drain any internal fill queue
118
+ """
119
+ ...
120
+
121
+ def get_cash_flows(self) -> list[CashFlow]:
122
+ """Cash flows booked since the last call, such as funding on an open future."""
123
+ return []
@@ -0,0 +1,42 @@
1
+ from ..brokerage.broker_base import Broker
2
+ from ..core.contracts import ContractRegistry
3
+ from .simulated import SimBroker
4
+ from .ibkr import IBKRBroker
5
+ from ..util.config import BrokerType, BrokerConfig, ConfigError
6
+
7
+
8
+ def build_broker(
9
+ broker_config: BrokerConfig, *, contracts: ContractRegistry | None = None
10
+ ) -> Broker:
11
+ if not isinstance(broker_config, BrokerConfig):
12
+ raise ConfigError("A valid broker configuration must be provided.")
13
+
14
+ if broker_config.type == BrokerType.SIMULATED:
15
+ cfg = broker_config.sim
16
+ if cfg is None:
17
+ return SimBroker()
18
+ return SimBroker(
19
+ spread_bps=cfg.spread_bps,
20
+ slippage_mean_bps=cfg.slippage_mean_bps,
21
+ slippage_std_bps=cfg.slippage_std_bps,
22
+ commission_per_share=cfg.commission_per_share,
23
+ partial_fill_probability=cfg.partial_fill_probability,
24
+ reject_probability=cfg.reject_probability,
25
+ max_fill_pct_of_bar_volume=cfg.max_fill_pct_of_bar_volume,
26
+ impact_bps_at_full_participation=cfg.impact_bps_at_full_participation,
27
+ min_latency_ms=cfg.min_latency_ms,
28
+ max_latency_ms=cfg.max_latency_ms,
29
+ seed=cfg.seed,
30
+ )
31
+ elif broker_config.type == BrokerType.IBKR:
32
+ if broker_config.ibkr is None:
33
+ raise ConfigError("IBKR configuration is missing.")
34
+ return IBKRBroker(
35
+ host=broker_config.ibkr.host,
36
+ port=broker_config.ibkr.port,
37
+ client_id=broker_config.ibkr.client_id,
38
+ mode=broker_config.mode,
39
+ contracts=contracts,
40
+ )
41
+ else:
42
+ raise ValueError(f"Unsupported broker type: {broker_config.type}")
@@ -0,0 +1,38 @@
1
+ from dataclasses import dataclass
2
+ from typing import Protocol
3
+
4
+ from ..core.types import Liquidity
5
+
6
+
7
+ class CommissionModel(Protocol):
8
+ """What a fill costs. Negative means the venue paid us."""
9
+
10
+ def charge(self, *, price: float, quantity: float, liquidity: Liquidity | None) -> float | None:
11
+ ...
12
+
13
+
14
+ @dataclass(frozen=True, slots=True)
15
+ class PerShareCommission:
16
+ per_share: float = 0.0
17
+
18
+ def charge(self, *, price: float, quantity: float, liquidity: Liquidity | None) -> float | None:
19
+ if not self.per_share:
20
+ return None
21
+ return quantity * self.per_share
22
+
23
+
24
+ @dataclass(frozen=True, slots=True)
25
+ class MakerTakerCommission:
26
+ """A rebate for adding liquidity, a fee for taking it, both in basis points of notional."""
27
+ maker_rebate_bps: float
28
+ taker_fee_bps: float
29
+
30
+ def __post_init__(self) -> None:
31
+ if self.maker_rebate_bps < 0.0 or self.taker_fee_bps < 0.0:
32
+ raise ValueError("commission rates must be non-negative")
33
+
34
+ def charge(self, *, price: float, quantity: float, liquidity: Liquidity | None) -> float:
35
+ notional = price * quantity
36
+ if liquidity is Liquidity.TAKER:
37
+ return notional * (self.taker_fee_bps / 10_000.0)
38
+ return -notional * (self.maker_rebate_bps / 10_000.0)