Premchan369 commited on
Commit
94aee56
·
verified ·
1 Parent(s): ea7542e

Add transaction cost model - market impact, square-root law, realistic slippage

Browse files
Files changed (1) hide show
  1. transaction_cost_model.py +120 -0
transaction_cost_model.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """transaction_cost_model.py — Realistic Transaction Cost & Market Impact
2
+
3
+ Models market impact using the square-root law (Almgren et al. 2005),
4
+ permanent/temporary impact decomposition, bid-ask spread costs, and
5
+ slippage estimation. Essential for honest backtest PnL.
6
+
7
+ References:
8
+ - Almgren et al. 2005: "Direct Estimation of Equity Market Impact"
9
+ - Kissell & Glantz 2003: "Optimal Trading Strategies"
10
+ - Gatheral 2010: "No-Dynamic-Arbitrage and Market Impact"
11
+ """
12
+ import numpy as np, pandas as pd
13
+
14
+ class TransactionCostModel:
15
+ """Models all trading costs: spread, impact, slippage, fees."""
16
+
17
+ def __init__(self, base_bps=5.0, fee_bps=1.0, impact_model='square_root',
18
+ eta=0.6, gamma=0.5, sigma_daily=0.02):
19
+ """
20
+ Args:
21
+ base_bps: half-spread in basis points (bid-ask / 2)
22
+ fee_bps: commission fee in basis points per trade
23
+ impact_model: 'square_root', 'linear', 'log'
24
+ eta: impact exponent (0.6 = square root law)
25
+ gamma: participation rate sensitivity
26
+ sigma_daily: daily volatility for impact scaling
27
+ """
28
+ self.base_bps = base_bps / 10000.0
29
+ self.fee_bps = fee_bps / 10000.0
30
+ self.impact_model = impact_model
31
+ self.eta = eta
32
+ self.gamma = gamma
33
+ self.sigma = sigma_daily
34
+
35
+ def spread_cost(self, side='buy'):
36
+ """Half-spread cost."""
37
+ return self.base_bps # Always pay half spread
38
+
39
+ def market_impact(self, volume, adv, participation=None):
40
+ """Market impact cost using square-root law.
41
+
42
+ Args:
43
+ volume: shares to trade
44
+ adv: average daily volume
45
+ participation: fraction of ADV (if None, computed from volume/adv)
46
+ """
47
+ if adv <= 0: return 0.0
48
+ x = participation if participation is not None else volume / adv
49
+ if self.impact_model == 'square_root':
50
+ return self.gamma * self.sigma * (x ** self.eta)
51
+ elif self.impact_model == 'linear':
52
+ return self.gamma * self.sigma * x
53
+ elif self.impact_model == 'log':
54
+ return self.gamma * self.sigma * np.log(1 + x)
55
+ return 0.0
56
+
57
+ def temporary_impact(self, volume, adv, urgency=1.0):
58
+ """Temporary impact (decays)."""
59
+ return self.market_impact(volume, adv) * urgency * 0.5
60
+
61
+ def permanent_impact(self, volume, adv):
62
+ """Permanent impact (persists)."""
63
+ return self.market_impact(volume, adv) * 0.3
64
+
65
+ def total_cost(self, volume, adv, side='buy', participation=None, urgency=1.0):
66
+ """Total transaction cost as fraction of notional."""
67
+ spread = self.spread_cost(side)
68
+ temp = self.temporary_impact(volume, adv, urgency)
69
+ perm = self.permanent_impact(volume, adv)
70
+ fee = self.fee_bps
71
+ return spread + temp + perm + fee
72
+
73
+ def apply_to_returns(self, returns, turnover, adv_ratio=0.01):
74
+ """Apply costs to a return series given turnover.
75
+
76
+ Args:
77
+ returns: pd.Series of strategy returns
78
+ turnover: pd.Series of daily turnover (0-1)
79
+ adv_ratio: typical participation rate
80
+ """
81
+ costs = turnover * self.total_cost(1.0, 1.0/adv_ratio if adv_ratio > 0 else 1.0)
82
+ net_returns = returns - costs
83
+ return net_returns, costs
84
+
85
+ def optimal_participation_rate(self, urgency=1.0, risk_aversion=1e-6):
86
+ """Optimal participation rate balancing impact vs risk.
87
+
88
+ Based on Almgren-Chriss: minimize impact + lambda * variance.
89
+ """
90
+ # Approximate solution: x* ~ (sigma / (2 * gamma * eta * lambda))^(1/(eta-1))
91
+ if self.eta >= 1.0: return 0.05 # Default conservative
92
+ ratio = self.sigma / (2 * self.gamma * self.eta * risk_aversion * urgency)
93
+ return max(0.01, min(0.5, ratio ** (1.0 / (self.eta - 1.0))))
94
+
95
+ def cost_report(self, volume=100000, adv=10000000, side='buy'):
96
+ """Generate human-readable cost breakdown."""
97
+ part = volume / adv
98
+ spread = self.spread_cost(side) * 10000
99
+ temp = self.temporary_impact(volume, adv) * 10000
100
+ perm = self.permanent_impact(volume, adv) * 10000
101
+ fee = self.fee_bps * 10000
102
+ total = spread + temp + perm + fee
103
+ return f"""## Transaction Cost Breakdown
104
+
105
+ | Component | bps | % of Total |
106
+ |-----------|-----|------------|
107
+ | Spread | {spread:.1f} | {spread/total*100:.0f}% |
108
+ | Temp Impact | {temp:.1f} | {temp/total*100:.0f}% |
109
+ | Perm Impact | {perm:.1f} | {perm/total*100:.0f}% |
110
+ | Fees | {fee:.1f} | {fee/total*100:.0f}% |
111
+ | **Total** | **{total:.1f}** | **100%** |
112
+
113
+ Participation rate: {part*100:.2f}%
114
+ Model: {self.impact_model} (eta={self.eta})
115
+ Optimal participation: {self.optimal_participation_rate()*100:.2f}%
116
+ """
117
+
118
+ if __name__ == '__main__':
119
+ tcm = TransactionCostModel(base_bps=3.0, fee_bps=0.5, impact_model='square_root')
120
+ print(tcm.cost_report(volume=500000, adv=10000000))