quantlite 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.
- QuantLite-0.1.0.dist-info/LICENSE +22 -0
- QuantLite-0.1.0.dist-info/METADATA +247 -0
- QuantLite-0.1.0.dist-info/RECORD +15 -0
- QuantLite-0.1.0.dist-info/WHEEL +5 -0
- QuantLite-0.1.0.dist-info/top_level.txt +1 -0
- quantlite/__init__.py +29 -0
- quantlite/backtesting.py +110 -0
- quantlite/data_generation.py +131 -0
- quantlite/instruments/__init__.py +2 -0
- quantlite/instruments/bond_pricing.py +53 -0
- quantlite/instruments/exotic_options.py +121 -0
- quantlite/instruments/option_pricing.py +60 -0
- quantlite/metrics.py +38 -0
- quantlite/monte_carlo.py +118 -0
- quantlite/visualisation.py +139 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Prasant Sudhakaran
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
|
22
|
+
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: QuantLite
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A robust quant finance library
|
|
5
|
+
Author-email: Prasant Sudhakaran <code@prasant.net>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2024 Prasant Sudhakaran
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in
|
|
18
|
+
all copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
26
|
+
THE SOFTWARE.
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
Keywords: quant,finance,monte carlo,exotic options
|
|
30
|
+
Requires-Python: >=3.8
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
License-File: LICENSE
|
|
33
|
+
Requires-Dist: numpy
|
|
34
|
+
Requires-Dist: pandas
|
|
35
|
+
Requires-Dist: scipy
|
|
36
|
+
Requires-Dist: matplotlib
|
|
37
|
+
Requires-Dist: mplfinance
|
|
38
|
+
|
|
39
|
+
# QuantLite
|
|
40
|
+
|
|
41
|
+
QuantLite is a feature-rich Python library for quantitative finance. It spans everything from **data generation** and **Monte Carlo** to **exotic options pricing**, **enhanced backtesting**, and **advanced visualisations**. Whether you’re exploring novel strategies or needing robust analytics, QuantLite aims to cover all your bases.
|
|
42
|
+
|
|
43
|
+
## Table of Contents
|
|
44
|
+
|
|
45
|
+
* [Installation](#installation)
|
|
46
|
+
* [Modules Overview](#modules-overview)
|
|
47
|
+
* [Data Generation](#data-generation)
|
|
48
|
+
* [Instruments (Bond, Vanilla Options, Exotic Options)](#instruments)
|
|
49
|
+
* [Monte Carlo](#monte-carlo)
|
|
50
|
+
* [Backtesting](#backtesting)
|
|
51
|
+
* [Visualisation](#visualisation)
|
|
52
|
+
* [Usage Examples & Synergy](#usage-examples--synergy)
|
|
53
|
+
* [1. Data Generation + Backtesting + Visualisation](#1-data-generation--backtesting--visualisation)
|
|
54
|
+
* [2. Monte Carlo + Backtesting + Visualisation](#2-monte-carlo--backtesting--visualisation)
|
|
55
|
+
* [3. Exotic Options Pricing](#3-exotic-options-pricing)
|
|
56
|
+
* [Roadmap](#roadmap)
|
|
57
|
+
* [Licence](#license)
|
|
58
|
+
* [Contact/Support](#contact)
|
|
59
|
+
|
|
60
|
+
## Installation
|
|
61
|
+
|
|
62
|
+
QuantLite is available on [PyPI](https://pypi.org/project/quantlite/). Install it simply by:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
pip install quantlite
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
(Ensure you’re using Python 3.8+.)
|
|
69
|
+
## Modules Overview
|
|
70
|
+
|
|
71
|
+
### 1. Data Generation
|
|
72
|
+
Location: `quantlite.data_generation`
|
|
73
|
+
* `geometric_brownian_motion`: Single-asset GBM path generation.
|
|
74
|
+
* `correlated_gbm`: Multi-asset correlated path generation using covariance matrices.
|
|
75
|
+
* `ornstein_uhlenbeck`: Mean-reverting process.
|
|
76
|
+
* `merton_jump_diffusion`: GBM with Poisson jump arrivals (Merton’s model).
|
|
77
|
+
|
|
78
|
+
#### Example:
|
|
79
|
+
```python
|
|
80
|
+
import quantlite.data_generation as qd
|
|
81
|
+
prices = qd.geometric_brownian_motion(S0=100, mu=0.05, sigma=0.2, steps=252)
|
|
82
|
+
print(prices[:10]) # First 10 days
|
|
83
|
+
```
|
|
84
|
+
### 2. Instruments (Bond, Vanilla Options, Exotic Options)
|
|
85
|
+
Location: `quantlite.instruments`
|
|
86
|
+
|
|
87
|
+
* Bond Pricing (bond_pricing.py): bond_price, bond_yield_to_maturity, bond_duration, etc.
|
|
88
|
+
* Vanilla Options (option_pricing.py): black_scholes_call, black_scholes_put, plus Greeks.
|
|
89
|
+
* Exotic Options (exotic_options.py): barrier_option_knock_out, asian_option_arithmetic
|
|
90
|
+
|
|
91
|
+
Example:
|
|
92
|
+
```python
|
|
93
|
+
from quantlite.instruments.option_pricing import black_scholes_call
|
|
94
|
+
call_val = black_scholes_call(S=100, K=95, T=1, r=0.01, sigma=0.2)
|
|
95
|
+
print("Vanilla call option price:", call_val)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### 3. Monte Carlo
|
|
99
|
+
Location: `quantlite.monte_carlo`
|
|
100
|
+
|
|
101
|
+
* run_monte_carlo_sims: Single-asset multi-sim approach with different random "modes."
|
|
102
|
+
* multi_asset_correlated_sim: Direct correlated multi-asset simulation (similar to * data_generation.correlated_gbm, but designed for scenario testing).
|
|
103
|
+
|
|
104
|
+
Example:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
import pandas as pd
|
|
108
|
+
from quantlite.monte_carlo import run_monte_carlo_sims
|
|
109
|
+
|
|
110
|
+
price_data = pd.Series([100, 101, 99, 102], index=[1,2,3,4])
|
|
111
|
+
def always_buy(idx, series):
|
|
112
|
+
return 1
|
|
113
|
+
|
|
114
|
+
mc_results = run_monte_carlo_sims(price_data, always_buy, n_sims=5)
|
|
115
|
+
for i, res in enumerate(mc_results):
|
|
116
|
+
print("Sim", i, "final value:", res["final_value"])
|
|
117
|
+
```
|
|
118
|
+
### 4. Backtesting
|
|
119
|
+
Location: `quantlite.backtesting`
|
|
120
|
+
|
|
121
|
+
A robust function `run_backtest` with partial capital, short-selling toggles, and transaction cost modelling.
|
|
122
|
+
|
|
123
|
+
Example:
|
|
124
|
+
```python
|
|
125
|
+
def run_backtest(
|
|
126
|
+
price_data,
|
|
127
|
+
signal_function,
|
|
128
|
+
initial_capital=10_000.0,
|
|
129
|
+
fee=0.0,
|
|
130
|
+
partial_capital=False,
|
|
131
|
+
capital_fraction=1.0,
|
|
132
|
+
allow_short=True,
|
|
133
|
+
per_share_cost=0.0
|
|
134
|
+
):
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### 5. Visualisation
|
|
138
|
+
Location: `quantlite.visualisation`
|
|
139
|
+
|
|
140
|
+
* `plot_time_series`: Basic line chart with optional indicators.
|
|
141
|
+
* `plot_ohlc`: Candlesticks or OHLC bars via mplfinance.
|
|
142
|
+
* `plot_return_distribution`: Histogram + KDE for returns.
|
|
143
|
+
* `plot_equity_curve`: Equity curve with optional drawdown shading.
|
|
144
|
+
* `plot_multiple_equity_curves`: Compare multiple strategies and optionally show rolling Sharpe.
|
|
145
|
+
|
|
146
|
+
Example:
|
|
147
|
+
|
|
148
|
+
```python
|
|
149
|
+
from quantlite.visualisation import plot_equity_curve
|
|
150
|
+
# Suppose we have a backtest result with result["portfolio_value"]
|
|
151
|
+
plot_equity_curve(result["portfolio_value"], drawdowns=True)
|
|
152
|
+
```
|
|
153
|
+
## Usage Examples & Synergy
|
|
154
|
+
Below are extended examples to show how modules can be combined.
|
|
155
|
+
|
|
156
|
+
### 1. Data Generation + Backtesting + Visualisation
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
import quantlite.data_generation as qd
|
|
160
|
+
from quantlite.backtesting import run_backtest
|
|
161
|
+
from quantlite.visualisation import plot_equity_curve
|
|
162
|
+
import pandas as pd
|
|
163
|
+
|
|
164
|
+
# 1. Create synthetic price data
|
|
165
|
+
prices_array = qd.merton_jump_diffusion(S0=100, mu=0.06, sigma=0.25, steps=252, rng_seed=42)
|
|
166
|
+
prices_series = pd.Series(prices_array, index=range(253))
|
|
167
|
+
|
|
168
|
+
# 2. Simple signal: Buy if today's price < yesterday's
|
|
169
|
+
def naive_signal(idx, series):
|
|
170
|
+
if idx == 0:
|
|
171
|
+
return 0
|
|
172
|
+
return 1 if series.iloc[idx] < series.iloc[idx-1] else 0
|
|
173
|
+
|
|
174
|
+
# 3. Run backtest with partial capital
|
|
175
|
+
result = run_backtest(prices_series, naive_signal, fee=1.0, partial_capital=True, capital_fraction=0.5)
|
|
176
|
+
|
|
177
|
+
# 4. Visualise
|
|
178
|
+
plot_equity_curve(result["portfolio_value"], drawdowns=True)
|
|
179
|
+
print("Final portfolio value:", result["final_value"])
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
### 2. Monte Carlo + Backtesting + Visualisation
|
|
183
|
+
```python
|
|
184
|
+
import pandas as pd
|
|
185
|
+
from quantlite.monte_carlo import run_monte_carlo_sims
|
|
186
|
+
from quantlite.visualisation import plot_multiple_equity_curves
|
|
187
|
+
|
|
188
|
+
prices = pd.Series([100, 101, 102, 103, 99, 98, 101, 102], index=range(8))
|
|
189
|
+
def always_long(idx, series):
|
|
190
|
+
return 1
|
|
191
|
+
|
|
192
|
+
# Multiple sims
|
|
193
|
+
results = run_monte_carlo_sims(prices, always_long, n_sims=3, mode="replace")
|
|
194
|
+
curves = {}
|
|
195
|
+
for i, res in enumerate(results):
|
|
196
|
+
curves[f"Sim {i}"] = res["portfolio_value"]
|
|
197
|
+
|
|
198
|
+
plot_multiple_equity_curves(curves_dict=curves, rolling_sharpe=True)
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
### 3. Exotic Options Pricing
|
|
202
|
+
```python
|
|
203
|
+
from quantlite.instruments.exotic_options import barrier_option_knock_out, asian_option_arithmetic
|
|
204
|
+
|
|
205
|
+
barrier_val = barrier_option_knock_out(
|
|
206
|
+
S0=120, K=100, H=90, T=1.0, r=0.01, sigma=0.2,
|
|
207
|
+
option_type="call", barrier_type="down-and-out",
|
|
208
|
+
steps=252, sims=10000, rng_seed=42
|
|
209
|
+
)
|
|
210
|
+
print("Knock-out barrier call value:", barrier_val)
|
|
211
|
+
|
|
212
|
+
asian_val = asian_option_arithmetic(
|
|
213
|
+
S0=120, K=100, T=1.0, r=0.01, sigma=0.2,
|
|
214
|
+
option_type="call", steps=252, sims=10000, rng_seed=42
|
|
215
|
+
)
|
|
216
|
+
print("Arithmetic average Asian call value:", asian_val)
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
## Roadmap
|
|
221
|
+
|
|
222
|
+
1. More Data Generation:
|
|
223
|
+
* Stochastic volatility (Heston model)
|
|
224
|
+
* Regime-switching
|
|
225
|
+
2. Deeper Monte Carlo:
|
|
226
|
+
* Correlated jumps
|
|
227
|
+
* Advanced param sweeps
|
|
228
|
+
* Multi-factor models
|
|
229
|
+
3. Backtesting Enhancements:
|
|
230
|
+
* Multi-asset portfolio rebalancing
|
|
231
|
+
* Advanced slippage
|
|
232
|
+
* Partial fills.
|
|
233
|
+
4. More Exotic Instruments:
|
|
234
|
+
* Up-and-out barrier
|
|
235
|
+
* Lookback options
|
|
236
|
+
5. Interactive Visualisation:
|
|
237
|
+
* Plotly or Bokeh integration
|
|
238
|
+
* Auto-report generation.
|
|
239
|
+
|
|
240
|
+
## Licence
|
|
241
|
+
This project is distributed under the MIT License.
|
|
242
|
+
See the LICENSE file for the full text.
|
|
243
|
+
|
|
244
|
+
## Contact/Support
|
|
245
|
+
**Need help or want to contribute?**
|
|
246
|
+
> Please open an issue on our [GitHub repo](https://github.com/prasants/quantlite).
|
|
247
|
+
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
quantlite/__init__.py,sha256=R7Yc_DMGPcf-nyhKSwd5crhRLDW-MT9eV7jI8EUq3Jo,492
|
|
2
|
+
quantlite/backtesting.py,sha256=EvyxR5QVZIIpl7e85pPJbkX0gt0yeYRg3JIjzzqUcZE,4031
|
|
3
|
+
quantlite/data_generation.py,sha256=8V306thn-5Z88azerLKKkz575AulqMBalkTZkYzTi2s,3442
|
|
4
|
+
quantlite/metrics.py,sha256=xPA8S-3XfNx3vJAZWr02xx5syt5MuioOnugU4L1Qo8A,1088
|
|
5
|
+
quantlite/monte_carlo.py,sha256=dztpwVSmQKf91LJBwBTnt6ypZ36mZYB5RVgQJ35VSlg,3742
|
|
6
|
+
quantlite/visualisation.py,sha256=tnwkGeGedUt1wtmqOQFzrEiap8y1Hx_8oPs99LViIQc,4329
|
|
7
|
+
quantlite/instruments/__init__.py,sha256=V2WzeuXr9SEUzmZ6kzcaS6V35fKdCR2Z7lDCFBFCquM,30
|
|
8
|
+
quantlite/instruments/bond_pricing.py,sha256=lFUmxJm4ymjKgs7HoyO3k7F5PF03sc2EiqDV7vmtO6Y,1849
|
|
9
|
+
quantlite/instruments/exotic_options.py,sha256=edeu-3MxZ_mRwXgH1UjxUwoszktP1vSrRsXRTIb0cLk,2951
|
|
10
|
+
quantlite/instruments/option_pricing.py,sha256=3y1eHKkyXxKppNL0_p7-SdoELCGfKLx_VhPoD6ZK8EA,1906
|
|
11
|
+
QuantLite-0.1.0.dist-info/LICENSE,sha256=4SaHm1ahebDKbT_8cqIabbg7rBb6XtXXi3Rm8nsunrM,1076
|
|
12
|
+
QuantLite-0.1.0.dist-info/METADATA,sha256=cycBMxGRXGoryRFpk1S5LAhiaT3gz8od4xxGdFmpwD8,8573
|
|
13
|
+
QuantLite-0.1.0.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
|
|
14
|
+
QuantLite-0.1.0.dist-info/top_level.txt,sha256=E2bUJxnZGOKg9YbwcjONyU9pasnGVEx_c5O90vhuu5w,10
|
|
15
|
+
QuantLite-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
quantlite
|
quantlite/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
2
|
+
|
|
3
|
+
from .metrics import (
|
|
4
|
+
annualised_return,
|
|
5
|
+
annualised_volatility,
|
|
6
|
+
sharpe_ratio,
|
|
7
|
+
max_drawdown
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
from .backtesting import run_backtest
|
|
11
|
+
|
|
12
|
+
from .data_generation import (
|
|
13
|
+
geometric_brownian_motion,
|
|
14
|
+
ornstein_uhlenbeck
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
from .visualisation import (
|
|
18
|
+
plot_time_series
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
from .instruments.bond_pricing import (
|
|
22
|
+
bond_price,
|
|
23
|
+
bond_yield_to_maturity
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
from .instruments.option_pricing import (
|
|
27
|
+
black_scholes_call,
|
|
28
|
+
black_scholes_put
|
|
29
|
+
)
|
quantlite/backtesting.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
|
|
3
|
+
def run_backtest(
|
|
4
|
+
price_data,
|
|
5
|
+
signal_function,
|
|
6
|
+
initial_capital=10_000.0,
|
|
7
|
+
fee=0.0,
|
|
8
|
+
partial_capital=False,
|
|
9
|
+
capital_fraction=1.0,
|
|
10
|
+
allow_short=True,
|
|
11
|
+
per_share_cost=0.0
|
|
12
|
+
):
|
|
13
|
+
"""
|
|
14
|
+
Enhanced backtest with partial capital allocation and short-selling toggles.
|
|
15
|
+
|
|
16
|
+
Parameters
|
|
17
|
+
----------
|
|
18
|
+
price_data : pd.Series
|
|
19
|
+
Price series of the asset.
|
|
20
|
+
signal_function : callable
|
|
21
|
+
(idx, price_data) -> +1 (long), -1 (short), or 0 (flat).
|
|
22
|
+
initial_capital : float
|
|
23
|
+
Starting capital.
|
|
24
|
+
fee : float
|
|
25
|
+
A flat transaction fee each time you change position.
|
|
26
|
+
partial_capital : bool
|
|
27
|
+
If True, we only allocate a fraction (capital_fraction) of current capital
|
|
28
|
+
to the position, leaving the rest in cash.
|
|
29
|
+
capital_fraction : float
|
|
30
|
+
Fraction of available capital allocated to the position. (e.g., 0.5 means half in the trade)
|
|
31
|
+
allow_short : bool
|
|
32
|
+
If False, signals that return -1 will be treated as 0 (no shorting allowed).
|
|
33
|
+
per_share_cost : float
|
|
34
|
+
Commission per share traded. e.g., 0.01 means 1 cent commission per share.
|
|
35
|
+
|
|
36
|
+
Returns
|
|
37
|
+
-------
|
|
38
|
+
dict
|
|
39
|
+
- "portfolio_value": pd.Series of portfolio value
|
|
40
|
+
- "positions": pd.Series of position size (in shares)
|
|
41
|
+
- "trades": list of (date, action, shares, price, cost)
|
|
42
|
+
- "final_value": float
|
|
43
|
+
"""
|
|
44
|
+
if not isinstance(price_data, pd.Series):
|
|
45
|
+
raise ValueError("price_data must be a pd.Series")
|
|
46
|
+
|
|
47
|
+
price_data = price_data.sort_index()
|
|
48
|
+
dates = price_data.index
|
|
49
|
+
capital = initial_capital
|
|
50
|
+
current_shares = 0
|
|
51
|
+
portfolio_values = []
|
|
52
|
+
positions = []
|
|
53
|
+
trades = []
|
|
54
|
+
|
|
55
|
+
for i, date in enumerate(dates):
|
|
56
|
+
price = price_data.iloc[i]
|
|
57
|
+
raw_signal = signal_function(i, price_data)
|
|
58
|
+
# If shorting is not allowed, clamp raw_signal to 0 or +1
|
|
59
|
+
if not allow_short and raw_signal < 0:
|
|
60
|
+
raw_signal = 0
|
|
61
|
+
# The new target position is raw_signal: 1 = long, -1 = short, 0 = flat
|
|
62
|
+
target_position = raw_signal
|
|
63
|
+
|
|
64
|
+
# Determine how many shares we want
|
|
65
|
+
# partial_capital => only a fraction of capital goes into shares
|
|
66
|
+
desired_capital_for_position = capital * capital_fraction if partial_capital else capital
|
|
67
|
+
if desired_capital_for_position < 0:
|
|
68
|
+
desired_capital_for_position = 0
|
|
69
|
+
|
|
70
|
+
if target_position == 0:
|
|
71
|
+
desired_shares = 0
|
|
72
|
+
else:
|
|
73
|
+
# If target_position == 1, we buy as many shares as desired_capital_for_position can afford
|
|
74
|
+
# If target_position == -1, we 'short' that many shares
|
|
75
|
+
# floor shares to an integer
|
|
76
|
+
desired_shares = int(desired_capital_for_position // price) * target_position
|
|
77
|
+
|
|
78
|
+
if desired_shares != current_shares:
|
|
79
|
+
# We have a trade
|
|
80
|
+
delta_shares = desired_shares - current_shares
|
|
81
|
+
trade_cost = fee # flat fee
|
|
82
|
+
# Add per-share cost
|
|
83
|
+
trade_cost += abs(delta_shares) * per_share_cost
|
|
84
|
+
|
|
85
|
+
# If delta_shares > 0 => buying; if < 0 => selling/covering
|
|
86
|
+
value_of_shares = delta_shares * price * -1 # negative for capital if buying
|
|
87
|
+
capital += value_of_shares - trade_cost # buy => capital decreases
|
|
88
|
+
|
|
89
|
+
trades.append((date,
|
|
90
|
+
"buy" if delta_shares > 0 else "sell",
|
|
91
|
+
delta_shares,
|
|
92
|
+
price,
|
|
93
|
+
trade_cost))
|
|
94
|
+
|
|
95
|
+
current_shares = desired_shares
|
|
96
|
+
|
|
97
|
+
# Compute portfolio value => capital + shares * price
|
|
98
|
+
port_val = capital + current_shares * price
|
|
99
|
+
portfolio_values.append(port_val)
|
|
100
|
+
positions.append(current_shares)
|
|
101
|
+
|
|
102
|
+
portfolio_series = pd.Series(portfolio_values, index=dates)
|
|
103
|
+
positions_series = pd.Series(positions, index=dates)
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
"portfolio_value": portfolio_series,
|
|
107
|
+
"positions": positions_series,
|
|
108
|
+
"trades": trades,
|
|
109
|
+
"final_value": portfolio_series.iloc[-1]
|
|
110
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
|
|
4
|
+
def geometric_brownian_motion(
|
|
5
|
+
S0=100.0,
|
|
6
|
+
mu=0.05,
|
|
7
|
+
sigma=0.2,
|
|
8
|
+
dt=1/252,
|
|
9
|
+
steps=252,
|
|
10
|
+
rng_seed=None,
|
|
11
|
+
return_as="array"
|
|
12
|
+
):
|
|
13
|
+
if steps < 1:
|
|
14
|
+
raise ValueError("steps must be >= 1")
|
|
15
|
+
if sigma < 0:
|
|
16
|
+
raise ValueError("sigma cannot be negative")
|
|
17
|
+
if rng_seed is not None:
|
|
18
|
+
np.random.seed(rng_seed)
|
|
19
|
+
|
|
20
|
+
prices = np.zeros(steps + 1)
|
|
21
|
+
prices[0] = S0
|
|
22
|
+
for i in range(1, steps + 1):
|
|
23
|
+
dW = np.random.normal(0, np.sqrt(dt))
|
|
24
|
+
prices[i] = prices[i-1] * np.exp((mu - 0.5*sigma**2)*dt + sigma*dW)
|
|
25
|
+
|
|
26
|
+
if return_as == "series":
|
|
27
|
+
return pd.Series(prices, index=range(steps+1), name="GBM")
|
|
28
|
+
return prices
|
|
29
|
+
|
|
30
|
+
def correlated_gbm(
|
|
31
|
+
S0_list,
|
|
32
|
+
mu_list,
|
|
33
|
+
cov_matrix,
|
|
34
|
+
steps=252,
|
|
35
|
+
dt=1/252,
|
|
36
|
+
rng_seed=None,
|
|
37
|
+
return_as="dataframe"
|
|
38
|
+
):
|
|
39
|
+
if rng_seed is not None:
|
|
40
|
+
np.random.seed(rng_seed)
|
|
41
|
+
|
|
42
|
+
n_assets = len(S0_list)
|
|
43
|
+
if len(mu_list) != n_assets:
|
|
44
|
+
raise ValueError("mu_list length must match S0_list")
|
|
45
|
+
if cov_matrix.shape != (n_assets, n_assets):
|
|
46
|
+
raise ValueError("cov_matrix must be NxN where N=len(S0_list)")
|
|
47
|
+
if steps < 1:
|
|
48
|
+
raise ValueError("steps must be >= 1")
|
|
49
|
+
|
|
50
|
+
L = np.linalg.cholesky(cov_matrix)
|
|
51
|
+
prices = np.zeros((steps+1, n_assets))
|
|
52
|
+
prices[0, :] = S0_list
|
|
53
|
+
|
|
54
|
+
for t in range(1, steps + 1):
|
|
55
|
+
z = np.random.normal(size=n_assets)
|
|
56
|
+
corr_z = L @ z
|
|
57
|
+
|
|
58
|
+
for i in range(n_assets):
|
|
59
|
+
sigma_i = np.sqrt(cov_matrix[i,i])
|
|
60
|
+
drift = (mu_list[i] - 0.5*sigma_i**2) * dt
|
|
61
|
+
dW = corr_z[i] * np.sqrt(dt)
|
|
62
|
+
prices[t, i] = prices[t-1, i] * np.exp(drift + sigma_i*dW)
|
|
63
|
+
|
|
64
|
+
if return_as == "dataframe":
|
|
65
|
+
cols = [f"Asset_{i}" for i in range(n_assets)]
|
|
66
|
+
return pd.DataFrame(prices, columns=cols)
|
|
67
|
+
return prices
|
|
68
|
+
|
|
69
|
+
def ornstein_uhlenbeck(
|
|
70
|
+
x0=0.0,
|
|
71
|
+
theta=0.07,
|
|
72
|
+
mu=0.0,
|
|
73
|
+
sigma=0.1,
|
|
74
|
+
dt=1/252,
|
|
75
|
+
steps=252,
|
|
76
|
+
rng_seed=None,
|
|
77
|
+
return_as="array"
|
|
78
|
+
):
|
|
79
|
+
if steps < 1:
|
|
80
|
+
raise ValueError("steps must be >= 1")
|
|
81
|
+
if sigma < 0:
|
|
82
|
+
raise ValueError("sigma cannot be negative")
|
|
83
|
+
|
|
84
|
+
if rng_seed is not None:
|
|
85
|
+
np.random.seed(rng_seed)
|
|
86
|
+
|
|
87
|
+
x_vals = np.zeros(steps + 1)
|
|
88
|
+
x_vals[0] = x0
|
|
89
|
+
|
|
90
|
+
for t in range(1, steps+1):
|
|
91
|
+
dx = theta*(mu - x_vals[t-1])*dt + sigma*np.sqrt(dt)*np.random.normal()
|
|
92
|
+
x_vals[t] = x_vals[t-1] + dx
|
|
93
|
+
|
|
94
|
+
if return_as == "series":
|
|
95
|
+
return pd.Series(x_vals, index=range(steps+1), name="OU")
|
|
96
|
+
return x_vals
|
|
97
|
+
|
|
98
|
+
def merton_jump_diffusion(
|
|
99
|
+
S0=100.0,
|
|
100
|
+
mu=0.05,
|
|
101
|
+
sigma=0.2,
|
|
102
|
+
lamb=0.5,
|
|
103
|
+
jump_mean=0.0,
|
|
104
|
+
jump_std=0.1,
|
|
105
|
+
dt=1/252,
|
|
106
|
+
steps=252,
|
|
107
|
+
rng_seed=None,
|
|
108
|
+
return_as="array"
|
|
109
|
+
):
|
|
110
|
+
if steps < 1:
|
|
111
|
+
raise ValueError("steps must be >= 1")
|
|
112
|
+
if rng_seed is not None:
|
|
113
|
+
np.random.seed(rng_seed)
|
|
114
|
+
|
|
115
|
+
prices = np.zeros(steps + 1)
|
|
116
|
+
prices[0] = S0
|
|
117
|
+
for t in range(1, steps+1):
|
|
118
|
+
N_t = np.random.poisson(lamb * dt)
|
|
119
|
+
jump_factor = 1.0
|
|
120
|
+
if N_t > 0:
|
|
121
|
+
total_log_jump = np.sum(np.random.normal(jump_mean, jump_std, N_t))
|
|
122
|
+
jump_factor = np.exp(total_log_jump)
|
|
123
|
+
|
|
124
|
+
dW = np.random.normal(0, np.sqrt(dt))
|
|
125
|
+
drift = (mu - 0.5*sigma**2) * dt
|
|
126
|
+
diffusion = sigma * dW
|
|
127
|
+
prices[t] = prices[t-1] * np.exp(drift + diffusion) * jump_factor
|
|
128
|
+
|
|
129
|
+
if return_as == "series":
|
|
130
|
+
return pd.Series(prices, index=range(steps+1), name="MJD")
|
|
131
|
+
return prices
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
def bond_price(face_value, coupon_rate, market_rate, maturity, payments_per_year=1):
|
|
2
|
+
"""
|
|
3
|
+
Calculates the price of a coupon bond.
|
|
4
|
+
|
|
5
|
+
payments_per_year : int
|
|
6
|
+
e.g., 2 for semi-annual, 4 for quarterly.
|
|
7
|
+
"""
|
|
8
|
+
coupon = face_value * coupon_rate / payments_per_year
|
|
9
|
+
periods = maturity * payments_per_year
|
|
10
|
+
rate_per_period = market_rate / payments_per_year
|
|
11
|
+
|
|
12
|
+
total = 0.0
|
|
13
|
+
for t in range(1, periods + 1):
|
|
14
|
+
total += coupon / ((1 + rate_per_period)**t)
|
|
15
|
+
total += face_value / ((1 + rate_per_period)**periods)
|
|
16
|
+
return total
|
|
17
|
+
|
|
18
|
+
def bond_duration(face_value, coupon_rate, market_rate, maturity, payments_per_year=1):
|
|
19
|
+
"""
|
|
20
|
+
Macaulay Duration for a standard coupon bond.
|
|
21
|
+
"""
|
|
22
|
+
coupon = face_value * coupon_rate / payments_per_year
|
|
23
|
+
periods = maturity * payments_per_year
|
|
24
|
+
rate_per_period = market_rate / payments_per_year
|
|
25
|
+
|
|
26
|
+
total_price = bond_price(face_value, coupon_rate, market_rate, maturity, payments_per_year)
|
|
27
|
+
weighted_sum = 0.0
|
|
28
|
+
|
|
29
|
+
for t in range(1, periods + 1):
|
|
30
|
+
# time in years from now
|
|
31
|
+
time = t / payments_per_year
|
|
32
|
+
pv = coupon / ((1 + rate_per_period)**t)
|
|
33
|
+
weighted_sum += time * pv
|
|
34
|
+
# Add principal redemption
|
|
35
|
+
weighted_sum += maturity * face_value / ((1 + rate_per_period)**periods)
|
|
36
|
+
|
|
37
|
+
return weighted_sum / total_price
|
|
38
|
+
|
|
39
|
+
def bond_yield_to_maturity(face_value, coupon_rate, current_price, maturity, payments_per_year=1, guess=0.05, tol=1e-7):
|
|
40
|
+
def price_at_rate(r):
|
|
41
|
+
return bond_price(face_value, coupon_rate, r, maturity, payments_per_year)
|
|
42
|
+
|
|
43
|
+
low, high = 0.0, 1.0
|
|
44
|
+
for _ in range(200):
|
|
45
|
+
mid = (low + high) / 2
|
|
46
|
+
diff = price_at_rate(mid) - current_price
|
|
47
|
+
if abs(diff) < tol:
|
|
48
|
+
return mid
|
|
49
|
+
if diff > 0:
|
|
50
|
+
low = mid
|
|
51
|
+
else:
|
|
52
|
+
high = mid
|
|
53
|
+
return (low + high) / 2
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import numpy as np
|
|
3
|
+
from scipy.stats import norm
|
|
4
|
+
|
|
5
|
+
def barrier_option_knock_out(
|
|
6
|
+
S0,
|
|
7
|
+
K,
|
|
8
|
+
H,
|
|
9
|
+
T,
|
|
10
|
+
r,
|
|
11
|
+
sigma,
|
|
12
|
+
option_type="call",
|
|
13
|
+
barrier_type="down-and-out",
|
|
14
|
+
steps=1000,
|
|
15
|
+
sims=10000,
|
|
16
|
+
rng_seed=None
|
|
17
|
+
):
|
|
18
|
+
"""
|
|
19
|
+
Monte Carlo pricing for a knock-out barrier option.
|
|
20
|
+
If the underlying price touches the barrier H, the option immediately becomes worthless (knocks out).
|
|
21
|
+
|
|
22
|
+
Parameters
|
|
23
|
+
----------
|
|
24
|
+
S0 : float
|
|
25
|
+
Initial underlying price.
|
|
26
|
+
K : float
|
|
27
|
+
Strike.
|
|
28
|
+
H : float
|
|
29
|
+
Barrier level.
|
|
30
|
+
T : float
|
|
31
|
+
Time to maturity (in years).
|
|
32
|
+
r : float
|
|
33
|
+
Risk-free interest rate.
|
|
34
|
+
sigma : float
|
|
35
|
+
Volatility.
|
|
36
|
+
option_type : str
|
|
37
|
+
"call" or "put".
|
|
38
|
+
barrier_type : str
|
|
39
|
+
For this example, "down-and-out" only. (You could extend to up-and-out, etc.)
|
|
40
|
+
steps : int
|
|
41
|
+
Number of time steps in each simulation path.
|
|
42
|
+
sims : int
|
|
43
|
+
Number of simulated paths.
|
|
44
|
+
rng_seed : int, optional
|
|
45
|
+
Reproducibility.
|
|
46
|
+
|
|
47
|
+
Returns
|
|
48
|
+
-------
|
|
49
|
+
float
|
|
50
|
+
Estimated option value.
|
|
51
|
+
"""
|
|
52
|
+
if rng_seed is not None:
|
|
53
|
+
np.random.seed(rng_seed)
|
|
54
|
+
|
|
55
|
+
dt = T / steps
|
|
56
|
+
disc_factor = math.exp(-r * T)
|
|
57
|
+
payoffs = []
|
|
58
|
+
|
|
59
|
+
for _ in range(sims):
|
|
60
|
+
price = S0
|
|
61
|
+
knocked_out = False
|
|
62
|
+
for __ in range(steps):
|
|
63
|
+
dW = np.random.normal(0, math.sqrt(dt))
|
|
64
|
+
price *= math.exp((r - 0.5 * sigma**2)*dt + sigma*dW)
|
|
65
|
+
|
|
66
|
+
# Barrier check
|
|
67
|
+
if barrier_type == "down-and-out":
|
|
68
|
+
if price <= H:
|
|
69
|
+
knocked_out = True
|
|
70
|
+
break
|
|
71
|
+
else:
|
|
72
|
+
# Extend for up-and-out, etc.
|
|
73
|
+
pass
|
|
74
|
+
|
|
75
|
+
if knocked_out:
|
|
76
|
+
payoffs.append(0.0)
|
|
77
|
+
else:
|
|
78
|
+
if option_type == "call":
|
|
79
|
+
payoffs.append(max(price - K, 0.0))
|
|
80
|
+
else: # put
|
|
81
|
+
payoffs.append(max(K - price, 0.0))
|
|
82
|
+
|
|
83
|
+
return disc_factor * np.mean(payoffs)
|
|
84
|
+
|
|
85
|
+
def asian_option_arithmetic(
|
|
86
|
+
S0,
|
|
87
|
+
K,
|
|
88
|
+
T,
|
|
89
|
+
r,
|
|
90
|
+
sigma,
|
|
91
|
+
option_type="call",
|
|
92
|
+
steps=1000,
|
|
93
|
+
sims=10000,
|
|
94
|
+
rng_seed=None
|
|
95
|
+
):
|
|
96
|
+
"""
|
|
97
|
+
Monte Carlo pricing of an arithmetic average price Asian option.
|
|
98
|
+
|
|
99
|
+
The payoff depends on the average of prices over the path.
|
|
100
|
+
"""
|
|
101
|
+
if rng_seed is not None:
|
|
102
|
+
np.random.seed(rng_seed)
|
|
103
|
+
|
|
104
|
+
dt = T / steps
|
|
105
|
+
disc_factor = math.exp(-r * T)
|
|
106
|
+
payoffs = []
|
|
107
|
+
|
|
108
|
+
for _ in range(sims):
|
|
109
|
+
price = S0
|
|
110
|
+
path_prices = [price]
|
|
111
|
+
for __ in range(steps):
|
|
112
|
+
dW = np.random.normal(0, math.sqrt(dt))
|
|
113
|
+
price *= math.exp((r - 0.5 * sigma**2)*dt + sigma*dW)
|
|
114
|
+
path_prices.append(price)
|
|
115
|
+
average_price = np.mean(path_prices)
|
|
116
|
+
if option_type == "call":
|
|
117
|
+
payoffs.append(max(average_price - K, 0.0))
|
|
118
|
+
else:
|
|
119
|
+
payoffs.append(max(K - average_price, 0.0))
|
|
120
|
+
|
|
121
|
+
return disc_factor * np.mean(payoffs)
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import math
|
|
2
|
+
from scipy.stats import norm
|
|
3
|
+
|
|
4
|
+
def black_scholes_call(S, K, T, r, sigma):
|
|
5
|
+
if T <= 0:
|
|
6
|
+
return max(S - K, 0.0)
|
|
7
|
+
d1 = (math.log(S/K) + (r + 0.5*sigma**2)*T) / (sigma * math.sqrt(T))
|
|
8
|
+
d2 = d1 - sigma * math.sqrt(T)
|
|
9
|
+
return S * norm.cdf(d1) - K * math.exp(-r*T) * norm.cdf(d2)
|
|
10
|
+
|
|
11
|
+
def black_scholes_put(S, K, T, r, sigma):
|
|
12
|
+
if T <= 0:
|
|
13
|
+
return max(K - S, 0.0)
|
|
14
|
+
d1 = (math.log(S/K) + (r + 0.5*sigma**2)*T) / (sigma * math.sqrt(T))
|
|
15
|
+
d2 = d1 - sigma * math.sqrt(T)
|
|
16
|
+
return K * math.exp(-r*T)*norm.cdf(-d2) - S*norm.cdf(-d1)
|
|
17
|
+
|
|
18
|
+
def black_scholes_greeks(S, K, T, r, sigma, option_type="call"):
|
|
19
|
+
"""
|
|
20
|
+
Returns a dictionary of Greeks for a European call or put using Black–Scholes.
|
|
21
|
+
|
|
22
|
+
Parameters
|
|
23
|
+
----------
|
|
24
|
+
option_type : str
|
|
25
|
+
"call" or "put"
|
|
26
|
+
|
|
27
|
+
Returns
|
|
28
|
+
-------
|
|
29
|
+
dict
|
|
30
|
+
Keys: "Delta", "Gamma", "Vega", "Theta", "Rho"
|
|
31
|
+
"""
|
|
32
|
+
if T <= 0:
|
|
33
|
+
# At expiry, greeks for digital payoff are ambiguous
|
|
34
|
+
return {"Delta": 0, "Gamma": 0, "Vega": 0, "Theta": 0, "Rho": 0}
|
|
35
|
+
|
|
36
|
+
d1 = (math.log(S/K) + (r + 0.5*sigma**2)*T) / (sigma * math.sqrt(T))
|
|
37
|
+
d2 = d1 - sigma * math.sqrt(T)
|
|
38
|
+
pdf_d1 = 1.0 / math.sqrt(2 * math.pi) * math.exp(-0.5 * d1**2)
|
|
39
|
+
|
|
40
|
+
if option_type.lower() == "call":
|
|
41
|
+
delta = norm.cdf(d1)
|
|
42
|
+
theta = (- (S * pdf_d1 * sigma) / (2 * math.sqrt(T))
|
|
43
|
+
- r * K * math.exp(-r*T) * norm.cdf(d2))
|
|
44
|
+
rho = K * T * math.exp(-r*T) * norm.cdf(d2)
|
|
45
|
+
else: # put
|
|
46
|
+
delta = norm.cdf(d1) - 1
|
|
47
|
+
theta = (- (S * pdf_d1 * sigma) / (2 * math.sqrt(T))
|
|
48
|
+
+ r * K * math.exp(-r*T) * norm.cdf(-d2))
|
|
49
|
+
rho = -K * T * math.exp(-r*T) * norm.cdf(-d2)
|
|
50
|
+
|
|
51
|
+
gamma = pdf_d1 / (S * sigma * math.sqrt(T))
|
|
52
|
+
vega = S * math.sqrt(T) * pdf_d1
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
"Delta": delta,
|
|
56
|
+
"Gamma": gamma,
|
|
57
|
+
"Vega": vega,
|
|
58
|
+
"Theta": theta,
|
|
59
|
+
"Rho": rho
|
|
60
|
+
}
|
quantlite/metrics.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
|
|
4
|
+
def annualised_return(returns, freq=252):
|
|
5
|
+
if isinstance(returns, pd.Series):
|
|
6
|
+
returns = returns.values
|
|
7
|
+
arr = np.array(returns)
|
|
8
|
+
if len(arr) == 0:
|
|
9
|
+
return 0.0
|
|
10
|
+
cumulative = (1 + arr).prod()
|
|
11
|
+
return cumulative ** (freq / len(arr)) - 1
|
|
12
|
+
|
|
13
|
+
def annualised_volatility(returns, freq=252):
|
|
14
|
+
if isinstance(returns, pd.Series):
|
|
15
|
+
returns = returns.values
|
|
16
|
+
arr = np.array(returns)
|
|
17
|
+
if len(arr) == 0:
|
|
18
|
+
return 0.0
|
|
19
|
+
return np.std(arr, ddof=1) * np.sqrt(freq)
|
|
20
|
+
|
|
21
|
+
def sharpe_ratio(returns, risk_free_rate=0.0, freq=252):
|
|
22
|
+
ar = annualised_return(returns, freq=freq)
|
|
23
|
+
av = annualised_volatility(returns, freq=freq)
|
|
24
|
+
if av == 0:
|
|
25
|
+
return float("nan")
|
|
26
|
+
return (ar - risk_free_rate) / av
|
|
27
|
+
|
|
28
|
+
def max_drawdown(returns):
|
|
29
|
+
if isinstance(returns, pd.Series):
|
|
30
|
+
returns = returns.values
|
|
31
|
+
arr = np.array(returns)
|
|
32
|
+
if len(arr) == 0:
|
|
33
|
+
return 0.0
|
|
34
|
+
cum = (1 + arr).cumprod()
|
|
35
|
+
roll_max = np.maximum.accumulate(cum)
|
|
36
|
+
drawdown = (cum - roll_max) / roll_max
|
|
37
|
+
return drawdown.min()
|
|
38
|
+
|
quantlite/monte_carlo.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from .backtesting import run_backtest
|
|
4
|
+
|
|
5
|
+
def run_monte_carlo_sims(
|
|
6
|
+
price_data,
|
|
7
|
+
signal_function,
|
|
8
|
+
n_sims=100,
|
|
9
|
+
noise_scale=0.01,
|
|
10
|
+
mode="perturb",
|
|
11
|
+
rng_seed=None
|
|
12
|
+
):
|
|
13
|
+
"""
|
|
14
|
+
(Unchanged from previous) Runs multiple random simulations for a single-asset case.
|
|
15
|
+
"""
|
|
16
|
+
if rng_seed is not None:
|
|
17
|
+
np.random.seed(rng_seed)
|
|
18
|
+
|
|
19
|
+
if not isinstance(price_data, pd.Series):
|
|
20
|
+
raise ValueError("price_data must be a pandas Series")
|
|
21
|
+
|
|
22
|
+
results = []
|
|
23
|
+
base_index = price_data.index
|
|
24
|
+
base_values = price_data.values
|
|
25
|
+
|
|
26
|
+
for _ in range(n_sims):
|
|
27
|
+
if mode == "perturb":
|
|
28
|
+
noise = np.random.normal(loc=0.0, scale=noise_scale, size=len(base_values))
|
|
29
|
+
sim_vals = base_values * (1 + noise)
|
|
30
|
+
elif mode == "gbm":
|
|
31
|
+
sim_vals = _simulate_gbm_series(base_values[0], len(base_values))
|
|
32
|
+
elif mode == "replace":
|
|
33
|
+
daily_returns = np.random.normal(loc=0.0, scale=noise_scale, size=len(base_values) - 1)
|
|
34
|
+
sim_vals = [base_values[0]]
|
|
35
|
+
for dr in daily_returns:
|
|
36
|
+
sim_vals.append(sim_vals[-1] * (1 + dr))
|
|
37
|
+
else:
|
|
38
|
+
raise ValueError("Unknown mode. Choose from ['perturb', 'gbm', 'replace'].")
|
|
39
|
+
|
|
40
|
+
sim_prices = pd.Series(sim_vals, index=base_index)
|
|
41
|
+
result = run_backtest(sim_prices, signal_function)
|
|
42
|
+
results.append(result)
|
|
43
|
+
|
|
44
|
+
return results
|
|
45
|
+
|
|
46
|
+
def multi_asset_correlated_sim(
|
|
47
|
+
S0_list,
|
|
48
|
+
mu_list,
|
|
49
|
+
cov_matrix,
|
|
50
|
+
steps=252,
|
|
51
|
+
dt=1/252,
|
|
52
|
+
rng_seed=None
|
|
53
|
+
):
|
|
54
|
+
"""
|
|
55
|
+
Generates correlated multi-asset price paths using a GBM approach.
|
|
56
|
+
|
|
57
|
+
Parameters
|
|
58
|
+
----------
|
|
59
|
+
S0_list : list of floats
|
|
60
|
+
Initial prices for each asset (e.g., [100.0, 50.0]).
|
|
61
|
+
mu_list : list of floats
|
|
62
|
+
Annual drift for each asset (e.g., [0.05, 0.02] for 5% and 2%).
|
|
63
|
+
cov_matrix : 2D numpy array
|
|
64
|
+
Covariance matrix for the assets' returns. Should be size NxN where N is len(S0_list).
|
|
65
|
+
steps : int
|
|
66
|
+
Number of time steps to simulate.
|
|
67
|
+
dt : float
|
|
68
|
+
Time step in years (1/252 for daily).
|
|
69
|
+
rng_seed : int, optional
|
|
70
|
+
Seed for reproducibility.
|
|
71
|
+
|
|
72
|
+
Returns
|
|
73
|
+
-------
|
|
74
|
+
pandas.DataFrame
|
|
75
|
+
DataFrame of shape (steps+1, len(S0_list)), each column is an asset price path.
|
|
76
|
+
Index is a simple range for time steps (0 to steps).
|
|
77
|
+
"""
|
|
78
|
+
if rng_seed is not None:
|
|
79
|
+
np.random.seed(rng_seed)
|
|
80
|
+
|
|
81
|
+
n_assets = len(S0_list)
|
|
82
|
+
if len(mu_list) != n_assets:
|
|
83
|
+
raise ValueError("mu_list must have the same length as S0_list")
|
|
84
|
+
if cov_matrix.shape != (n_assets, n_assets):
|
|
85
|
+
raise ValueError("cov_matrix dimension mismatch with S0_list")
|
|
86
|
+
|
|
87
|
+
# Cholesky decomposition for correlation
|
|
88
|
+
L = np.linalg.cholesky(cov_matrix)
|
|
89
|
+
|
|
90
|
+
# Initialize the result array
|
|
91
|
+
prices = np.zeros((steps + 1, n_assets))
|
|
92
|
+
prices[0, :] = S0_list
|
|
93
|
+
|
|
94
|
+
for t in range(1, steps + 1):
|
|
95
|
+
# Draw standard normal
|
|
96
|
+
z = np.random.normal(size=n_assets)
|
|
97
|
+
# Correlate them
|
|
98
|
+
correlated_z = L @ z
|
|
99
|
+
|
|
100
|
+
for i in range(n_assets):
|
|
101
|
+
# GBM step
|
|
102
|
+
dW = correlated_z[i] * np.sqrt(dt)
|
|
103
|
+
drift = (mu_list[i] - 0.5 * cov_matrix[i, i]) * dt
|
|
104
|
+
prices[t, i] = prices[t - 1, i] * np.exp(drift + dW)
|
|
105
|
+
|
|
106
|
+
columns = [f"Asset_{i}" for i in range(n_assets)]
|
|
107
|
+
return pd.DataFrame(prices, columns=columns)
|
|
108
|
+
|
|
109
|
+
def _simulate_gbm_series(S0, steps, mu=0.05, sigma=0.2, dt=1/252):
|
|
110
|
+
"""
|
|
111
|
+
A helper for single-asset GBM (unchanged from older version).
|
|
112
|
+
"""
|
|
113
|
+
vals = [S0]
|
|
114
|
+
for _ in range(steps - 1):
|
|
115
|
+
dW = np.random.normal(0, np.sqrt(dt))
|
|
116
|
+
new_val = vals[-1] * np.exp((mu - 0.5*sigma**2)*dt + sigma*dW)
|
|
117
|
+
vals.append(new_val)
|
|
118
|
+
return np.array(vals)
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
import numpy as np
|
|
3
|
+
import matplotlib.pyplot as plt
|
|
4
|
+
import mplfinance as mpf
|
|
5
|
+
from scipy.stats import norm
|
|
6
|
+
|
|
7
|
+
def plot_time_series(data, title="Time Series", indicators=None, figsize=(10, 5), grid=True):
|
|
8
|
+
# (Same as before)
|
|
9
|
+
if isinstance(data, pd.Series):
|
|
10
|
+
data = data.to_frame("Main Series")
|
|
11
|
+
|
|
12
|
+
plt.figure(figsize=figsize)
|
|
13
|
+
for col in data.columns:
|
|
14
|
+
plt.plot(data.index, data[col], label=col)
|
|
15
|
+
|
|
16
|
+
if indicators:
|
|
17
|
+
for label, series in indicators.items():
|
|
18
|
+
plt.plot(series.index, series.values, label=label, linestyle='--')
|
|
19
|
+
|
|
20
|
+
plt.title(title)
|
|
21
|
+
plt.xlabel("Date / Index")
|
|
22
|
+
plt.ylabel("Value")
|
|
23
|
+
if grid:
|
|
24
|
+
plt.grid(alpha=0.3)
|
|
25
|
+
plt.legend()
|
|
26
|
+
plt.show()
|
|
27
|
+
|
|
28
|
+
def plot_ohlc(df, title="Candlestick Chart", type="candle", volume=True, style="yahoo"):
|
|
29
|
+
# (Same as before)
|
|
30
|
+
if not {"Open", "High", "Low", "Close"}.issubset(df.columns):
|
|
31
|
+
raise ValueError("DataFrame must have columns: Open, High, Low, Close")
|
|
32
|
+
|
|
33
|
+
mpf.plot(
|
|
34
|
+
df,
|
|
35
|
+
type=type,
|
|
36
|
+
volume=volume if "Volume" in df.columns else False,
|
|
37
|
+
style=style,
|
|
38
|
+
title=title
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
def plot_return_distribution(returns, title="Return Distribution", bins=50, figsize=(8, 4)):
|
|
42
|
+
# (Same as before)
|
|
43
|
+
returns = pd.Series(returns).dropna()
|
|
44
|
+
plt.figure(figsize=figsize)
|
|
45
|
+
plt.hist(returns, bins=bins, density=True, alpha=0.6, color='g', label='Histogram')
|
|
46
|
+
returns.plot(kind='kde', label='KDE', color='black')
|
|
47
|
+
plt.title(title)
|
|
48
|
+
plt.xlabel("Return")
|
|
49
|
+
plt.ylabel("Density")
|
|
50
|
+
plt.legend()
|
|
51
|
+
plt.grid(alpha=0.3)
|
|
52
|
+
plt.show()
|
|
53
|
+
|
|
54
|
+
def plot_equity_curve(equity_series, drawdowns=False, figsize=(10,5)):
|
|
55
|
+
# (Same as before)
|
|
56
|
+
if not isinstance(equity_series, pd.Series):
|
|
57
|
+
equity_series = pd.Series(equity_series)
|
|
58
|
+
|
|
59
|
+
plt.figure(figsize=figsize)
|
|
60
|
+
plt.plot(equity_series.index, equity_series.values, label='Equity Curve')
|
|
61
|
+
plt.title("Equity Curve")
|
|
62
|
+
plt.xlabel("Date / Index")
|
|
63
|
+
plt.ylabel("Value")
|
|
64
|
+
plt.grid(alpha=0.3)
|
|
65
|
+
|
|
66
|
+
if drawdowns:
|
|
67
|
+
roll_max = equity_series.cummax()
|
|
68
|
+
dd = (equity_series - roll_max) / roll_max
|
|
69
|
+
dd_mask = dd < 0
|
|
70
|
+
plt.fill_between(equity_series.index, equity_series.values, roll_max, where=dd_mask, color='red', alpha=0.2, label='Drawdown')
|
|
71
|
+
|
|
72
|
+
plt.legend()
|
|
73
|
+
plt.show()
|
|
74
|
+
|
|
75
|
+
def plot_multiple_equity_curves(
|
|
76
|
+
curves_dict,
|
|
77
|
+
title="Multiple Equity Curves",
|
|
78
|
+
rolling_sharpe=False,
|
|
79
|
+
window=30,
|
|
80
|
+
figsize=(10,5)
|
|
81
|
+
):
|
|
82
|
+
"""
|
|
83
|
+
Plots multiple equity curves on the same figure.
|
|
84
|
+
Optionally shows their rolling Sharpe ratio in a sub-plot.
|
|
85
|
+
|
|
86
|
+
Parameters
|
|
87
|
+
----------
|
|
88
|
+
curves_dict : dict
|
|
89
|
+
{ "Label A": pd.Series, "Label B": pd.Series, ... }
|
|
90
|
+
Each value should be an equity curve (e.g., from a backtest).
|
|
91
|
+
rolling_sharpe : bool
|
|
92
|
+
If True, create a second subplot showing rolling Sharpe for each curve.
|
|
93
|
+
window : int
|
|
94
|
+
Rolling window size (in days) for Sharpe.
|
|
95
|
+
"""
|
|
96
|
+
# Convert all to same date index (if possible)
|
|
97
|
+
plt.figure(figsize=figsize)
|
|
98
|
+
|
|
99
|
+
n_subplots = 2 if rolling_sharpe else 1
|
|
100
|
+
ax1 = plt.subplot(n_subplots,1,1)
|
|
101
|
+
ax1.set_title(title)
|
|
102
|
+
|
|
103
|
+
for label, eq in curves_dict.items():
|
|
104
|
+
eq = eq.sort_index()
|
|
105
|
+
ax1.plot(eq.index, eq.values, label=label)
|
|
106
|
+
|
|
107
|
+
ax1.set_xlabel("Date / Index")
|
|
108
|
+
ax1.set_ylabel("Equity Value")
|
|
109
|
+
ax1.grid(alpha=0.3)
|
|
110
|
+
ax1.legend()
|
|
111
|
+
|
|
112
|
+
if rolling_sharpe:
|
|
113
|
+
ax2 = plt.subplot(n_subplots,1,2)
|
|
114
|
+
ax2.set_title("Rolling Sharpe")
|
|
115
|
+
for label, eq in curves_dict.items():
|
|
116
|
+
eq = eq.sort_index()
|
|
117
|
+
# Compute daily returns
|
|
118
|
+
daily_returns = eq.pct_change().dropna()
|
|
119
|
+
roll_sharpe = _rolling_sharpe(daily_returns, window=window)
|
|
120
|
+
ax2.plot(roll_sharpe.index, roll_sharpe.values, label=f"{label} RS")
|
|
121
|
+
|
|
122
|
+
ax2.set_xlabel("Date / Index")
|
|
123
|
+
ax2.set_ylabel("Sharpe")
|
|
124
|
+
ax2.grid(alpha=0.3)
|
|
125
|
+
ax2.legend()
|
|
126
|
+
|
|
127
|
+
plt.tight_layout()
|
|
128
|
+
plt.show()
|
|
129
|
+
|
|
130
|
+
def _rolling_sharpe(returns, window=30):
|
|
131
|
+
"""
|
|
132
|
+
Computes a rolling Sharpe ratio over a given window,
|
|
133
|
+
assuming a 0% risk-free rate for simplicity.
|
|
134
|
+
"""
|
|
135
|
+
roll_mean = returns.rolling(window).mean()
|
|
136
|
+
roll_std = returns.rolling(window).std()
|
|
137
|
+
# avoid division by zero
|
|
138
|
+
sharpe = roll_mean / (roll_std + 1e-9)
|
|
139
|
+
return sharpe
|