Skip to content

Commit 3d92154

Browse files
authored
Merge pull request #46 from AKKI0511/implement-advanced-market-impact-models
feat(backtest): add intrabar fills and borrow fees
2 parents ce203e4 + abe0bfe commit 3d92154

File tree

16 files changed

+726
-163
lines changed

16 files changed

+726
-163
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
- 📊 Data: YFinance/AlphaVantage loaders, caching, validation
2222
- 🧪 Features: technical indicators, custom signals, optional LLM sentiment
2323
- 🤖 Models: ensemble VotingClassifier (LR, RF, XGBoost) with Optuna tuning
24-
- 📈 Backtesting: execution costs, slippage, liquidity limits, market impact modeling, portfolio helpers
24+
- 📈 Backtesting: execution costs, slippage, liquidity limits, adaptive impact, intrabar fills, borrow fees
2525
- 🛡️ Risk management: drawdown and turnover guards
2626
- 📟 Live trading: real-time position manager with intraday risk controls
2727
- 🛠️ CLI: end‑to‑end pipeline, evaluation, and model backtest in one place

docs/README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,10 +132,11 @@ QuantTradeAI/
132132
- **Model persistence** and loading
133133

134134
### Backtesting
135-
- **Trade simulation** with realistic constraints
135+
- **Trade simulation** with limit/stop orders and intrabar tick fills
136+
- **Adaptive market impact modeling** with dynamic spreads and asymmetric coefficients
137+
- **Borrow fee accounting** for short positions
136138
- **Risk management** (stop-loss, take-profit)
137139
- **Performance metrics** (Sharpe ratio, max drawdown)
138-
- **Market impact modeling** for execution cost realism
139140
- **Position sizing** based on risk parameters
140141

141142
### Risk Management

docs/api/backtesting.md

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,18 @@ API documentation for trade simulation and performance metrics.
1616

1717
Simulates trades using label signals. The ``transaction_cost`` and ``slippage``
1818
arguments are shorthand for populating the ``execution`` configuration, which
19-
can also specify liquidity and market impact parameters.
19+
can also specify liquidity, market impact, borrow fees, and intrabar simulation
20+
parameters. The engine supports market, limit, and stop orders with partial
21+
fills.
2022

2123
**Parameters:**
2224
- `df` (pd.DataFrame or dict[str, pd.DataFrame]): Single DataFrame or mapping of symbol to DataFrame with Close prices and label column
2325
- `stop_loss_pct` (float, optional): Stop-loss percentage as decimal
2426
- `take_profit_pct` (float, optional): Take-profit percentage as decimal
2527
- `transaction_cost` (float, optional): Transaction cost in decimal bps
2628
- `slippage` (float, optional): Slippage cost in decimal bps
27-
- `execution` (dict, optional): Detailed execution settings including `transaction_costs`, `slippage`, `liquidity`, and `impact`
29+
- `execution` (dict, optional): Detailed execution settings including `transaction_costs`, `slippage`, `liquidity`, `impact`,
30+
`borrow_fee`, and `intrabar`
2831
- `portfolio` (PortfolioManager, optional): Portfolio manager required when `df` is a dictionary
2932

3033
**Returns:**
@@ -34,7 +37,7 @@ can also specify liquidity and market impact parameters.
3437
```python
3538
from quanttradeai import simulate_trades
3639

37-
# Simulate trades with market impact
40+
# Simulate trades with intrabar fills and borrow fees
3841
df_with_trades = simulate_trades(
3942
df,
4043
execution={
@@ -45,7 +48,9 @@ df_with_trades = simulate_trades(
4548
"beta": 0.0,
4649
"average_daily_volume": 1_000_000,
4750
"spread": 0.02,
48-
}
51+
},
52+
"intrabar": {"enabled": True, "synthetic_ticks": 20, "volatility": 0.01},
53+
"borrow_fee": {"enabled": True, "rate_bps": 100},
4954
},
5055
)
5156
```

docs/configuration.md

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -114,15 +114,32 @@ execution:
114114
model: linear # linear, square_root, almgren_chriss
115115
alpha: 0.0
116116
beta: 0.0
117+
alpha_buy: 0.0 # optional asymmetric coefficients
118+
alpha_sell: 0.0
117119
decay: 0.0 # temporary impact decay rate
120+
decay_volume_coeff: 0.0
118121
spread: 0.0 # bid-ask spread per share
122+
spread_model: {type: dynamic}
119123
average_daily_volume: 0
124+
borrow_fee:
125+
enabled: false
126+
rate_bps: 0
127+
intrabar:
128+
enabled: false
129+
drift: 0.0
130+
volatility: 0.0
131+
synthetic_ticks: 0
120132
```
121133
122-
The `impact` block activates market impact modeling. Parameters `alpha`,
123-
`beta`, and optional `gamma` control the chosen model, while `decay` and
124-
`spread` apply temporary impact decay and bid-ask spread costs. Default
125-
parameter sets per asset class can be defined in `config/impact_config.yaml`.
134+
The `impact` block activates market impact modeling. Parameters `alpha`/`beta`
135+
and their buy/sell counterparts control the chosen model, while `decay`,
136+
`decay_volume_coeff`, and `spread_model` enable dynamic spread and volume-based
137+
decay. Default parameter sets per asset class can be defined in
138+
`config/impact_config.yaml`.
139+
140+
The `borrow_fee` block applies financing costs to short positions, and the
141+
`intrabar` block enables tick-level fill simulation with optional synthetic
142+
Brownian motion ticks.
126143

127144
### Position Manager
128145

docs/quick-reference.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ classifier.save_model("models/trained/AAPL")
7171
```python
7272
from quanttradeai import simulate_trades, compute_metrics
7373

74-
# Simulate trades with market impact
74+
# Simulate trades with intrabar fills and market impact
7575
df_trades = simulate_trades(
7676
df_labeled,
7777
execution={
@@ -81,7 +81,9 @@ df_trades = simulate_trades(
8181
"alpha": 0.5,
8282
"beta": 0.0,
8383
"average_daily_volume": 1_000_000,
84-
}
84+
},
85+
"intrabar": {"enabled": True, "synthetic_ticks": 20, "volatility": 0.01},
86+
"borrow_fee": {"enabled": True, "rate_bps": 100},
8587
},
8688
)
8789

quanttradeai/__init__.py

Lines changed: 76 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -1,72 +1,76 @@
1-
"""QuantTradeAI
2-
=================
3-
4-
High-level interface for the QuantTradeAI toolkit. The package bundles
5-
data acquisition, feature engineering, model training and backtesting
6-
utilities for quantitative trading research.
7-
8-
Public API:
9-
- ``DataSource`` and concrete implementations
10-
- ``DataLoader`` and ``DataProcessor``
11-
- ``MomentumClassifier`` model
12-
- ``PortfolioManager`` and risk helpers
13-
- ``simulate_trades`` and ``compute_metrics`` for backtesting
14-
15-
Quick Start:
16-
```python
17-
from quanttradeai import DataLoader, DataProcessor, MomentumClassifier
18-
19-
loader = DataLoader()
20-
data = loader.fetch_data()
21-
processor = DataProcessor()
22-
processed = {s: processor.process_data(df) for s, df in data.items()}
23-
model = MomentumClassifier()
24-
```
25-
"""
26-
27-
from .data.datasource import (
28-
DataSource,
29-
YFinanceDataSource,
30-
AlphaVantageDataSource,
31-
WebSocketDataSource,
32-
)
33-
34-
# Lazily import optional dependencies to keep lightweight usage possible
35-
from .data.loader import DataLoader
36-
from .data.processor import DataProcessor
37-
38-
try: # pragma: no cover - optional heavy dependency
39-
from .models.classifier import MomentumClassifier
40-
except Exception: # pragma: no cover - tolerate missing ML libs
41-
MomentumClassifier = None # type: ignore[assignment]
42-
from .trading.portfolio import PortfolioManager
43-
from .trading.risk import apply_stop_loss_take_profit, position_size
44-
from .backtest import (
45-
simulate_trades,
46-
compute_metrics,
47-
MarketImpactModel,
48-
LinearImpactModel,
49-
SquareRootImpactModel,
50-
AlmgrenChrissModel,
51-
ImpactCalculator,
52-
)
53-
54-
__all__ = [
55-
"DataSource",
56-
"YFinanceDataSource",
57-
"AlphaVantageDataSource",
58-
"WebSocketDataSource",
59-
"DataLoader",
60-
"DataProcessor",
61-
"MomentumClassifier",
62-
"PortfolioManager",
63-
"apply_stop_loss_take_profit",
64-
"position_size",
65-
"simulate_trades",
66-
"compute_metrics",
67-
"MarketImpactModel",
68-
"LinearImpactModel",
69-
"SquareRootImpactModel",
70-
"AlmgrenChrissModel",
71-
"ImpactCalculator",
72-
]
1+
"""QuantTradeAI
2+
=================
3+
4+
High-level interface for the QuantTradeAI toolkit. The package bundles
5+
data acquisition, feature engineering, model training and backtesting
6+
utilities for quantitative trading research.
7+
8+
Public API:
9+
- ``DataSource`` and concrete implementations
10+
- ``DataLoader`` and ``DataProcessor``
11+
- ``MomentumClassifier`` model
12+
- ``PortfolioManager`` and risk helpers
13+
- ``simulate_trades`` and ``compute_metrics`` for backtesting
14+
15+
Quick Start:
16+
```python
17+
from quanttradeai import DataLoader, DataProcessor, MomentumClassifier
18+
19+
loader = DataLoader()
20+
data = loader.fetch_data()
21+
processor = DataProcessor()
22+
processed = {s: processor.process_data(df) for s, df in data.items()}
23+
model = MomentumClassifier()
24+
```
25+
"""
26+
27+
from .data.datasource import (
28+
DataSource,
29+
YFinanceDataSource,
30+
AlphaVantageDataSource,
31+
WebSocketDataSource,
32+
)
33+
34+
# Lazily import optional dependencies to keep lightweight usage possible
35+
from .data.loader import DataLoader
36+
from .data.processor import DataProcessor
37+
38+
try: # pragma: no cover - optional heavy dependency
39+
from .models.classifier import MomentumClassifier
40+
except Exception: # pragma: no cover - tolerate missing ML libs
41+
MomentumClassifier = None # type: ignore[assignment]
42+
from .trading.portfolio import PortfolioManager
43+
from .trading.risk import apply_stop_loss_take_profit, position_size
44+
from .backtest import (
45+
simulate_trades,
46+
compute_metrics,
47+
MarketImpactModel,
48+
LinearImpactModel,
49+
SquareRootImpactModel,
50+
AlmgrenChrissModel,
51+
ImpactCalculator,
52+
DynamicSpreadModel,
53+
BacktestEngine,
54+
)
55+
56+
__all__ = [
57+
"DataSource",
58+
"YFinanceDataSource",
59+
"AlphaVantageDataSource",
60+
"WebSocketDataSource",
61+
"DataLoader",
62+
"DataProcessor",
63+
"MomentumClassifier",
64+
"PortfolioManager",
65+
"apply_stop_loss_take_profit",
66+
"position_size",
67+
"simulate_trades",
68+
"compute_metrics",
69+
"MarketImpactModel",
70+
"LinearImpactModel",
71+
"SquareRootImpactModel",
72+
"AlmgrenChrissModel",
73+
"ImpactCalculator",
74+
"DynamicSpreadModel",
75+
"BacktestEngine",
76+
]

quanttradeai/backtest/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,14 @@
1515
"""
1616

1717
from .backtester import simulate_trades, compute_metrics
18+
from .engine import BacktestEngine
1819
from .impact import (
1920
MarketImpactModel,
2021
LinearImpactModel,
2122
SquareRootImpactModel,
2223
AlmgrenChrissModel,
2324
ImpactCalculator,
25+
DynamicSpreadModel,
2426
)
2527

2628
__all__ = [
@@ -31,4 +33,6 @@
3133
"SquareRootImpactModel",
3234
"AlmgrenChrissModel",
3335
"ImpactCalculator",
36+
"DynamicSpreadModel",
37+
"BacktestEngine",
3438
]

0 commit comments

Comments
 (0)