riskoptima 2.8.2__tar.gz → 2.8.3__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.
- {riskoptima-2.8.2 → riskoptima-2.8.3}/PKG-INFO +8 -2
- {riskoptima-2.8.2 → riskoptima-2.8.3}/README.md +7 -1
- {riskoptima-2.8.2 → riskoptima-2.8.3}/pyproject.toml +1 -1
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/__init__.py +20 -1
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/_version.py +1 -1
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/backtest/sma.py +99 -44
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/credit/models.py +2 -1
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/optim/mean_variance.py +43 -0
- riskoptima-2.8.3/riskoptima/options/black_scholes.py +72 -0
- riskoptima-2.8.3/riskoptima/options/greeks.py +49 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/rates/conventions.py +17 -5
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/rates/curve.py +2 -1
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/risk/factor_model.py +2 -1
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/risk/markov_regime.py +83 -2
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/riskoptima.py +140 -90
- riskoptima-2.8.2/riskoptima/options/black_scholes.py +0 -53
- riskoptima-2.8.2/riskoptima/options/greeks.py +0 -60
- {riskoptima-2.8.2 → riskoptima-2.8.3}/LICENSE +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/backtest/__init__.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/backtest/engine.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/backtest/portfolio.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/backtest/strategy.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/branding.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/core/__init__.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/core/types.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/credit/__init__.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/credit/metrics.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/credit/portfolio.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/credit/simulation.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/data/__init__.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/data/synthetic_credit_portfolio.csv +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/data/synthetic_market_returns.csv +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/dislocation/__init__.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/dislocation/engine.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/dislocation/reporting.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/optim/__init__.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/optim/_forecast.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/optim/constraints.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/optim/costs.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/optim/covariance.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/options/__init__.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/options/analytics.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/options/binomial.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/options/implied_vol.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/options/monte_carlo.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/rates/__init__.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/rates/calibration.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/reporting/__init__.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/reporting/market_risk.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/reporting/markov_regimes.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/reporting/sophistication.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/risk/__init__.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/risk/_tail.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/risk/attribution.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/risk/scenarios.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/volatility/__init__.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/volatility/estimators.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/volatility/implied.py +0 -0
- {riskoptima-2.8.2 → riskoptima-2.8.3}/riskoptima/volatility/ohlc.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: riskoptima
|
|
3
|
-
Version: 2.8.
|
|
3
|
+
Version: 2.8.3
|
|
4
4
|
Summary: RiskOptima is a powerful Python toolkit for financial risk analysis, portfolio optimization, and advanced quantitative modeling. It integrates state-of-the-art methodologies, including Monte Carlo simulations, Value at Risk (VaR), Conditional VaR (CVaR), Black-Scholes, Heston, and Merton Jump Diffusion models, to aid investors in making data-driven investment decisions.
|
|
5
5
|
License: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -63,6 +63,12 @@ https://pypistats.org/packages/riskoptima
|
|
|
63
63
|
|
|
64
64
|
RiskOptima is for research and educational use only. Its reports and scores are **not investment advice** or recommendations to buy, sell or hold any instrument. Models and third-party data may be incomplete or inaccurate; past performance does not guarantee future results. Independently verify inputs and results before making investment decisions.
|
|
65
65
|
|
|
66
|
+
## What's New in 2.8.3
|
|
67
|
+
|
|
68
|
+
- Shared Black-Scholes pricing and Greeks preserve the legacy reporting units and handle expiry correctly. U.S. 30/360 now applies the February month-end rules.
|
|
69
|
+
- Legacy portfolio sampling can enforce final weight bounds, and SMA trade logs support next-close execution for signals observed at the close.
|
|
70
|
+
- Fitted Markov models can filter later observations with fixed parameters. Standalone numerical imports load without the legacy plotting and data adapters. [Full release notes](https://github.com/JordiCorbilla/RiskOptima/blob/main/docs/RELEASE_NOTES_v2.8.3.md)
|
|
71
|
+
|
|
66
72
|
## What's New in 2.8.2
|
|
67
73
|
|
|
68
74
|
- Corrected risk-neutral Merton jump-diffusion pricing, point-in-time backtesting, and chronological validation of stock return forecasts.
|
|
@@ -481,7 +487,7 @@ Run notebooks from the repository root so local sample paths and the checkout re
|
|
|
481
487
|
Notebook setup cells do not upgrade RiskOptima automatically. In a fresh environment, install the desired release before opening Jupyter:
|
|
482
488
|
|
|
483
489
|
```bash
|
|
484
|
-
python -m pip install "riskoptima==2.8.
|
|
490
|
+
python -m pip install "riskoptima==2.8.3" jupyter
|
|
485
491
|
python -m jupyter lab
|
|
486
492
|
```
|
|
487
493
|
|
|
@@ -32,6 +32,12 @@ https://pypistats.org/packages/riskoptima
|
|
|
32
32
|
|
|
33
33
|
RiskOptima is for research and educational use only. Its reports and scores are **not investment advice** or recommendations to buy, sell or hold any instrument. Models and third-party data may be incomplete or inaccurate; past performance does not guarantee future results. Independently verify inputs and results before making investment decisions.
|
|
34
34
|
|
|
35
|
+
## What's New in 2.8.3
|
|
36
|
+
|
|
37
|
+
- Shared Black-Scholes pricing and Greeks preserve the legacy reporting units and handle expiry correctly. U.S. 30/360 now applies the February month-end rules.
|
|
38
|
+
- Legacy portfolio sampling can enforce final weight bounds, and SMA trade logs support next-close execution for signals observed at the close.
|
|
39
|
+
- Fitted Markov models can filter later observations with fixed parameters. Standalone numerical imports load without the legacy plotting and data adapters. [Full release notes](https://github.com/JordiCorbilla/RiskOptima/blob/main/docs/RELEASE_NOTES_v2.8.3.md)
|
|
40
|
+
|
|
35
41
|
## What's New in 2.8.2
|
|
36
42
|
|
|
37
43
|
- Corrected risk-neutral Merton jump-diffusion pricing, point-in-time backtesting, and chronological validation of stock return forecasts.
|
|
@@ -450,7 +456,7 @@ Run notebooks from the repository root so local sample paths and the checkout re
|
|
|
450
456
|
Notebook setup cells do not upgrade RiskOptima automatically. In a fresh environment, install the desired release before opening Jupyter:
|
|
451
457
|
|
|
452
458
|
```bash
|
|
453
|
-
python -m pip install "riskoptima==2.8.
|
|
459
|
+
python -m pip install "riskoptima==2.8.3" jupyter
|
|
454
460
|
python -m jupyter lab
|
|
455
461
|
```
|
|
456
462
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "riskoptima"
|
|
3
|
-
version = "2.8.
|
|
3
|
+
version = "2.8.3"
|
|
4
4
|
description = "RiskOptima is a powerful Python toolkit for financial risk analysis, portfolio optimization, and advanced quantitative modeling. It integrates state-of-the-art methodologies, including Monte Carlo simulations, Value at Risk (VaR), Conditional VaR (CVaR), Black-Scholes, Heston, and Merton Jump Diffusion models, to aid investors in making data-driven investment decisions."
|
|
5
5
|
authors = ["Jordi Corbilla <jordi.coll.corbilla@gmail.com>"]
|
|
6
6
|
license = "MIT"
|
|
@@ -13,8 +13,9 @@
|
|
|
13
13
|
# Created Date: 2025
|
|
14
14
|
# ---------------------------------------------------------------------------
|
|
15
15
|
|
|
16
|
+
from typing import TYPE_CHECKING
|
|
17
|
+
|
|
16
18
|
from ._version import __version__
|
|
17
|
-
from .riskoptima import RiskOptima
|
|
18
19
|
from .core import MarketData, Portfolio, BacktestConfig, RiskReport
|
|
19
20
|
from .risk import (
|
|
20
21
|
FactorRiskModel,
|
|
@@ -52,6 +53,24 @@ from .rates import (
|
|
|
52
53
|
reprice_curve_instruments,
|
|
53
54
|
)
|
|
54
55
|
|
|
56
|
+
|
|
57
|
+
if TYPE_CHECKING:
|
|
58
|
+
from .riskoptima import RiskOptima as RiskOptima
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def __getattr__(name: str):
|
|
62
|
+
if name != "RiskOptima":
|
|
63
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
64
|
+
from .riskoptima import RiskOptima
|
|
65
|
+
|
|
66
|
+
globals()[name] = RiskOptima
|
|
67
|
+
return RiskOptima
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def __dir__() -> list[str]:
|
|
71
|
+
return sorted(globals().keys() | {"RiskOptima"})
|
|
72
|
+
|
|
73
|
+
|
|
55
74
|
__all__ = [
|
|
56
75
|
"RiskOptima",
|
|
57
76
|
"__version__",
|
|
@@ -48,8 +48,22 @@ def _close_frame(prices) -> pd.DataFrame:
|
|
|
48
48
|
data.columns = ["Close"]
|
|
49
49
|
else:
|
|
50
50
|
raise ValueError("prices must contain a Close column or a single price column")
|
|
51
|
-
data
|
|
52
|
-
|
|
51
|
+
data = _ordered_closes(data)
|
|
52
|
+
if isinstance(prices, (pd.Series, pd.DataFrame)):
|
|
53
|
+
data.attrs.update(prices.attrs)
|
|
54
|
+
return data
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _ordered_closes(data: pd.DataFrame) -> pd.DataFrame:
|
|
58
|
+
if not data.index.is_unique or data.index.hasnans:
|
|
59
|
+
raise ValueError("price rows must have unique, non-missing index values")
|
|
60
|
+
data = data.copy()
|
|
61
|
+
close = pd.to_numeric(data["Close"], errors="coerce")
|
|
62
|
+
data["Close"] = close.where(np.isfinite(close))
|
|
63
|
+
data = data.dropna(subset=["Close"]).sort_index()
|
|
64
|
+
if data["Close"].le(0).any():
|
|
65
|
+
raise ValueError("close prices must be positive")
|
|
66
|
+
return data
|
|
53
67
|
|
|
54
68
|
|
|
55
69
|
def download_close_prices(ticker: str, start: str, end: str) -> pd.DataFrame:
|
|
@@ -58,7 +72,10 @@ def download_close_prices(ticker: str, start: str, end: str) -> pd.DataFrame:
|
|
|
58
72
|
"""
|
|
59
73
|
import yfinance as yf
|
|
60
74
|
|
|
61
|
-
|
|
75
|
+
prices = yf.download(ticker, start=start, end=end, progress=False, auto_adjust=False)[["Close"]].copy()
|
|
76
|
+
prices.attrs.update(source="Yahoo Finance", symbol=ticker, price_field="Close", auto_adjust=False,
|
|
77
|
+
index_role="session_date")
|
|
78
|
+
return prices
|
|
62
79
|
|
|
63
80
|
|
|
64
81
|
def build_sma_signal_frame(prices, short_window: int = 20, long_window: int = 50) -> pd.DataFrame:
|
|
@@ -84,59 +101,87 @@ def build_sma_signal_frame(prices, short_window: int = 20, long_window: int = 50
|
|
|
84
101
|
df["Signal"] = 0
|
|
85
102
|
df.loc[bullish, "Signal"] = 1
|
|
86
103
|
df.loc[bearish, "Signal"] = -1
|
|
104
|
+
df.attrs["signal_observation"] = "close"
|
|
87
105
|
return df
|
|
88
106
|
|
|
89
107
|
|
|
108
|
+
def _sma_order(entry, price, signal, stop_loss, take_profit):
|
|
109
|
+
if entry is None:
|
|
110
|
+
return "Buy Signal" if signal == 1 else None
|
|
111
|
+
if signal == -1:
|
|
112
|
+
return "Sell Signal"
|
|
113
|
+
pnl = (price - entry[1]) / entry[1]
|
|
114
|
+
if stop_loss is not None and pnl <= -stop_loss:
|
|
115
|
+
return "Stop Loss"
|
|
116
|
+
if take_profit is not None and pnl >= take_profit:
|
|
117
|
+
return "Take Profit"
|
|
118
|
+
return None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _fill_sma_order(trades, ticker, order, entry, date, price):
|
|
122
|
+
if order is None:
|
|
123
|
+
return entry
|
|
124
|
+
if entry is None:
|
|
125
|
+
return date, price
|
|
126
|
+
entry_date, entry_price = entry
|
|
127
|
+
trades.append(
|
|
128
|
+
{
|
|
129
|
+
"Ticker": ticker,
|
|
130
|
+
"Entry Date": entry_date,
|
|
131
|
+
"Exit Date": date,
|
|
132
|
+
"Entry Price": entry_price,
|
|
133
|
+
"Exit Price": price,
|
|
134
|
+
"Return": (price - entry_price) / entry_price,
|
|
135
|
+
"Exit Reason": order,
|
|
136
|
+
}
|
|
137
|
+
)
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
|
|
90
141
|
def trades_from_sma_signals(
|
|
91
142
|
signal_frame: pd.DataFrame,
|
|
92
143
|
ticker: str,
|
|
93
144
|
stop_loss: float | None = None,
|
|
94
145
|
take_profit: float | None = None,
|
|
146
|
+
*,
|
|
147
|
+
execution: str = "same_close",
|
|
95
148
|
) -> pd.DataFrame:
|
|
149
|
+
"""Convert crossover signals and close-based risk triggers to a trade log.
|
|
150
|
+
|
|
151
|
+
The compatibility default fills at the signal close. Use next_close
|
|
152
|
+
for signals observed at the close. It fills at the next available
|
|
153
|
+
close, including exits triggered by stops or take profits. Missing
|
|
154
|
+
closes cannot trigger or fill an order. Returns contain closed trades.
|
|
96
155
|
"""
|
|
97
|
-
|
|
98
|
-
"""
|
|
99
|
-
required = {"Close", "Signal"}
|
|
100
|
-
missing = required - set(signal_frame.columns)
|
|
156
|
+
missing = {"Close", "Signal"} - set(signal_frame.columns)
|
|
101
157
|
if missing:
|
|
102
158
|
raise ValueError(f"signal_frame is missing required columns: {sorted(missing)}")
|
|
159
|
+
if execution not in {"same_close", "next_close"}:
|
|
160
|
+
raise ValueError("execution must be 'same_close' or 'next_close'")
|
|
161
|
+
for parameter, threshold in (("stop_loss", stop_loss), ("take_profit", take_profit)):
|
|
162
|
+
if threshold is not None and (not np.isfinite(threshold) or threshold < 0):
|
|
163
|
+
raise ValueError(f"{parameter} must be non-negative and finite")
|
|
164
|
+
|
|
165
|
+
bars = _ordered_closes(signal_frame.loc[:, ["Close", "Signal"]])
|
|
166
|
+
if not bars["Signal"].isin([-1, 0, 1]).all():
|
|
167
|
+
raise ValueError("Signal must contain only -1, 0, or 1")
|
|
168
|
+
trades: list[dict] = []
|
|
169
|
+
entry = None
|
|
170
|
+
pending = None
|
|
171
|
+
for date, close, signal in bars.itertuples():
|
|
172
|
+
price = float(close)
|
|
173
|
+
if execution == "next_close":
|
|
174
|
+
entry = _fill_sma_order(trades, ticker, pending, entry, date, price)
|
|
175
|
+
order = _sma_order(entry, price, signal, stop_loss, take_profit)
|
|
176
|
+
if execution == "same_close":
|
|
177
|
+
entry = _fill_sma_order(trades, ticker, order, entry, date, price)
|
|
178
|
+
else:
|
|
179
|
+
pending = order
|
|
103
180
|
|
|
104
|
-
trades =
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
for exit_date, row in signal_frame.iterrows():
|
|
110
|
-
price = float(row["Close"])
|
|
111
|
-
signal = int(row["Signal"])
|
|
112
|
-
|
|
113
|
-
if position is None and signal == 1:
|
|
114
|
-
position = "long"
|
|
115
|
-
entry_price = price
|
|
116
|
-
entry_date = exit_date
|
|
117
|
-
elif position == "long":
|
|
118
|
-
assert entry_price is not None
|
|
119
|
-
pnl = (price - entry_price) / entry_price
|
|
120
|
-
hit_stop = stop_loss is not None and pnl <= -stop_loss
|
|
121
|
-
hit_take = take_profit is not None and pnl >= take_profit
|
|
122
|
-
|
|
123
|
-
if signal == -1 or hit_stop or hit_take:
|
|
124
|
-
trades.append(
|
|
125
|
-
{
|
|
126
|
-
"Ticker": ticker,
|
|
127
|
-
"Entry Date": entry_date,
|
|
128
|
-
"Exit Date": exit_date,
|
|
129
|
-
"Entry Price": entry_price,
|
|
130
|
-
"Exit Price": price,
|
|
131
|
-
"Return": pnl,
|
|
132
|
-
"Exit Reason": (
|
|
133
|
-
"Sell Signal" if signal == -1 else "Stop Loss" if hit_stop else "Take Profit"
|
|
134
|
-
),
|
|
135
|
-
}
|
|
136
|
-
)
|
|
137
|
-
position = None
|
|
138
|
-
|
|
139
|
-
return pd.DataFrame(trades, columns=TRADE_COLUMNS)
|
|
181
|
+
result = pd.DataFrame(trades, columns=TRADE_COLUMNS)
|
|
182
|
+
result.attrs.update(signal_frame.attrs)
|
|
183
|
+
result.attrs["execution"] = execution
|
|
184
|
+
return result
|
|
140
185
|
|
|
141
186
|
|
|
142
187
|
def run_sma_strategy_with_risk(
|
|
@@ -148,13 +193,17 @@ def run_sma_strategy_with_risk(
|
|
|
148
193
|
short_window: int = 20,
|
|
149
194
|
long_window: int = 50,
|
|
150
195
|
prices: pd.DataFrame | None = None,
|
|
196
|
+
*,
|
|
197
|
+
execution: str = "same_close",
|
|
151
198
|
) -> pd.DataFrame:
|
|
152
199
|
"""
|
|
153
200
|
Runs an SMA crossover strategy for one ticker and returns a trade log.
|
|
154
201
|
"""
|
|
155
202
|
price_data = prices if prices is not None else download_close_prices(ticker, start, end)
|
|
156
203
|
signals = build_sma_signal_frame(price_data, short_window=short_window, long_window=long_window)
|
|
157
|
-
return trades_from_sma_signals(
|
|
204
|
+
return trades_from_sma_signals(
|
|
205
|
+
signals, ticker=ticker, stop_loss=stop_loss, take_profit=take_profit, execution=execution,
|
|
206
|
+
)
|
|
158
207
|
|
|
159
208
|
|
|
160
209
|
def run_strategy_on_portfolio(
|
|
@@ -165,6 +214,8 @@ def run_strategy_on_portfolio(
|
|
|
165
214
|
take_profit: float | None = None,
|
|
166
215
|
short_window: int = 20,
|
|
167
216
|
long_window: int = 50,
|
|
217
|
+
*,
|
|
218
|
+
execution: str = "same_close",
|
|
168
219
|
) -> pd.DataFrame:
|
|
169
220
|
"""
|
|
170
221
|
Runs the SMA strategy across an asset table with Asset and Weight columns.
|
|
@@ -182,6 +233,7 @@ def run_strategy_on_portfolio(
|
|
|
182
233
|
take_profit=take_profit,
|
|
183
234
|
short_window=short_window,
|
|
184
235
|
long_window=long_window,
|
|
236
|
+
execution=execution,
|
|
185
237
|
)
|
|
186
238
|
if trades_df.empty:
|
|
187
239
|
continue
|
|
@@ -273,6 +325,8 @@ def run_and_plot_sma_strategy(
|
|
|
273
325
|
take_profit=None,
|
|
274
326
|
short_window: int = 20,
|
|
275
327
|
long_window: int = 50,
|
|
328
|
+
*,
|
|
329
|
+
execution: str = "same_close",
|
|
276
330
|
):
|
|
277
331
|
"""
|
|
278
332
|
Runs and plots SMA signals plus cumulative weighted trade returns.
|
|
@@ -286,6 +340,7 @@ def run_and_plot_sma_strategy(
|
|
|
286
340
|
take_profit=take_profit,
|
|
287
341
|
short_window=short_window,
|
|
288
342
|
long_window=long_window,
|
|
343
|
+
execution=execution,
|
|
289
344
|
)
|
|
290
345
|
|
|
291
346
|
for ticker in asset_table["Asset"]:
|
|
@@ -10,13 +10,14 @@ from __future__ import annotations
|
|
|
10
10
|
|
|
11
11
|
import numpy as np
|
|
12
12
|
from scipy.stats import norm
|
|
13
|
-
from sklearn.linear_model import LogisticRegression
|
|
14
13
|
|
|
15
14
|
|
|
16
15
|
def logistic_pd_model(X_train, y_train):
|
|
17
16
|
"""
|
|
18
17
|
Fits a logistic regression probability-of-default model.
|
|
19
18
|
"""
|
|
19
|
+
from sklearn.linear_model import LogisticRegression
|
|
20
|
+
|
|
20
21
|
model = LogisticRegression(max_iter=1000)
|
|
21
22
|
return model.fit(X_train, y_train)
|
|
22
23
|
|
|
@@ -239,3 +239,46 @@ def optimize_min_variance(
|
|
|
239
239
|
raise ValueError(f"Minimum variance optimization failed: {result.message}")
|
|
240
240
|
opt_result = _format_result(result, "min_variance", expected_returns, cov, 0.0, constraints, previous_weights, factor_exposures, metadata)
|
|
241
241
|
return opt_result if return_result else opt_result.weights
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _bounded_allocation_candidates(n_assets, n_sims, lower, upper, rng):
|
|
245
|
+
"""Sample feasible long-only allocations with randomized assignment order."""
|
|
246
|
+
# At each draw, leave enough budget for the remaining assets' bounds.
|
|
247
|
+
order = rng.random((n_sims, n_assets)).argsort(axis=1)
|
|
248
|
+
rows = np.arange(n_sims)
|
|
249
|
+
weights = np.empty((n_sims, n_assets))
|
|
250
|
+
remaining = np.ones(n_sims)
|
|
251
|
+
for step in range(n_assets - 1):
|
|
252
|
+
assets_after = n_assets - step - 1
|
|
253
|
+
lo = np.maximum(lower, remaining - assets_after * upper)
|
|
254
|
+
hi = np.minimum(upper, remaining - assets_after * lower)
|
|
255
|
+
draw = lo + np.maximum(hi - lo, 0.0) * rng.random(n_sims)
|
|
256
|
+
weights[rows, order[:, step]] = draw
|
|
257
|
+
remaining -= draw
|
|
258
|
+
weights[rows, order[:, -1]] = remaining
|
|
259
|
+
return np.clip(weights, lower, upper)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _bounded_monte_carlo_weights(expected_returns, cov, volatility_cap, lower, upper, n_sims, rng):
|
|
263
|
+
"""Select the best sampled Sharpe subject to final weights and volatility."""
|
|
264
|
+
n_assets = len(expected_returns)
|
|
265
|
+
equal_weight = 1.0 / n_assets
|
|
266
|
+
if equal_weight in (lower, upper):
|
|
267
|
+
candidates = np.full((1, n_assets), equal_weight)
|
|
268
|
+
else:
|
|
269
|
+
min_risk = optimize_min_variance(cov, constraints=Constraints(weight_bounds=(lower, upper)))
|
|
270
|
+
samples = _bounded_allocation_candidates(n_assets, n_sims, lower, upper, rng)
|
|
271
|
+
candidates = np.vstack([min_risk.to_numpy(), samples])
|
|
272
|
+
|
|
273
|
+
values = cov.to_numpy()
|
|
274
|
+
variances = np.einsum("ij,jk,ik->i", candidates, values, candidates, optimize=True)
|
|
275
|
+
volatility = np.sqrt(np.maximum(variances, 0.0))
|
|
276
|
+
feasible = volatility <= np.nextafter(volatility_cap, np.inf)
|
|
277
|
+
if not feasible.any():
|
|
278
|
+
raise ValueError("No portfolio satisfies the maximum volatility constraint.")
|
|
279
|
+
candidates = candidates[feasible]
|
|
280
|
+
volatility = volatility[feasible]
|
|
281
|
+
returns = candidates @ expected_returns
|
|
282
|
+
# Preserve the legacy score of zero for an undefined zero-volatility Sharpe.
|
|
283
|
+
scores = np.divide(returns, volatility, out=np.zeros_like(returns), where=volatility > 0)
|
|
284
|
+
return candidates[np.argmax(scores)]
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
###############################################################################
|
|
2
|
+
# black_scholes.py
|
|
3
|
+
###############################################################################
|
|
4
|
+
# Product: RiskOptima
|
|
5
|
+
# Author: Jordi Corbilla
|
|
6
|
+
# Description: Black-Scholes option pricing
|
|
7
|
+
###############################################################################
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from scipy.special import ndtr
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _option_type(option_type: str) -> str:
|
|
16
|
+
value = option_type.lower()
|
|
17
|
+
if value not in {"call", "put"}:
|
|
18
|
+
raise ValueError("option_type must be 'call' or 'put'")
|
|
19
|
+
return value
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _validate_option_inputs(values, *, greeks=False):
|
|
23
|
+
if not all(np.isfinite(value).all() for value in values):
|
|
24
|
+
raise ValueError("S, K, T, r, sigma, and q must be finite")
|
|
25
|
+
S, K, T, _, sigma, _ = values
|
|
26
|
+
if np.any(S <= 0) or np.any(K <= 0):
|
|
27
|
+
raise ValueError("S and K must be positive")
|
|
28
|
+
if greeks:
|
|
29
|
+
if np.any(T <= 0) or np.any(sigma <= 0):
|
|
30
|
+
raise ValueError("T and sigma must be positive for Black-Scholes Greeks")
|
|
31
|
+
elif np.any(T < 0) or np.any(sigma < 0):
|
|
32
|
+
raise ValueError("T and sigma must be non-negative")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _scalar_option_inputs(S, K, T, r, sigma, q, *, greeks=False):
|
|
36
|
+
values = np.asarray([S, K, T, r, sigma, q], dtype=float)
|
|
37
|
+
if values.shape != (6,):
|
|
38
|
+
raise ValueError("Black-Scholes option inputs must be scalars")
|
|
39
|
+
_validate_option_inputs(values, greeks=greeks)
|
|
40
|
+
return values
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _d1_d2(S, K, T, r, q, stddev):
|
|
44
|
+
d1 = (np.log(S / K) + (r - q) * T) / stddev + 0.5 * stddev
|
|
45
|
+
return d1, d1 - stddev
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _black_scholes_price(S, K, T, r, sigma, q, *, option_type):
|
|
49
|
+
"""Price validated scalar or compatible array inputs."""
|
|
50
|
+
stddev = sigma * np.sqrt(T)
|
|
51
|
+
sign = 1 if option_type == "call" else -1
|
|
52
|
+
discounted_spot = S * np.exp(-q * T)
|
|
53
|
+
discounted_strike = K * np.exp(-r * T)
|
|
54
|
+
deterministic = stddev == 0
|
|
55
|
+
if np.all(deterministic):
|
|
56
|
+
return np.maximum(sign * (discounted_spot - discounted_strike), 0.0)
|
|
57
|
+
|
|
58
|
+
has_deterministic = np.any(deterministic)
|
|
59
|
+
safe_stddev = np.where(deterministic, 1.0, stddev) if has_deterministic else stddev
|
|
60
|
+
d1, d2 = _d1_d2(S, K, T, r, q, safe_stddev)
|
|
61
|
+
price = sign * (discounted_spot * ndtr(sign * d1) - discounted_strike * ndtr(sign * d2))
|
|
62
|
+
if has_deterministic:
|
|
63
|
+
intrinsic = np.maximum(sign * (discounted_spot - discounted_strike), 0.0)
|
|
64
|
+
return np.where(deterministic, intrinsic, price)
|
|
65
|
+
return price
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def black_scholes_price(S, K, T, r, sigma, option_type="call", q=0.0):
|
|
69
|
+
"""Price a European option with scalar inputs and continuously compounded rates."""
|
|
70
|
+
option_type = _option_type(option_type)
|
|
71
|
+
values = _scalar_option_inputs(S, K, T, r, sigma, q)
|
|
72
|
+
return float(_black_scholes_price(*values, option_type=option_type))
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
###############################################################################
|
|
2
|
+
# greeks.py
|
|
3
|
+
###############################################################################
|
|
4
|
+
# Product: RiskOptima
|
|
5
|
+
# Author: Jordi Corbilla
|
|
6
|
+
# Description: Option Greeks
|
|
7
|
+
###############################################################################
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
from scipy.special import ndtr
|
|
13
|
+
|
|
14
|
+
from .black_scholes import _d1_d2, _option_type, _scalar_option_inputs
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _black_scholes_greeks(S, K, T, r, sigma, q, *, option_type):
|
|
18
|
+
"""Compute Greeks of validated scalar or compatible array inputs."""
|
|
19
|
+
sqrt_t = np.sqrt(T)
|
|
20
|
+
stddev = sigma * sqrt_t
|
|
21
|
+
d1, d2 = _d1_d2(S, K, T, r, q, stddev)
|
|
22
|
+
discount_q = np.exp(-q * T)
|
|
23
|
+
discount_r = np.exp(-r * T)
|
|
24
|
+
|
|
25
|
+
density = np.exp(-0.5 * d1**2) / np.sqrt(2.0 * np.pi)
|
|
26
|
+
sign = 1 if option_type == "call" else -1
|
|
27
|
+
nd1, nd2 = ndtr(sign * d1), ndtr(sign * d2)
|
|
28
|
+
return {
|
|
29
|
+
"delta": sign * discount_q * nd1,
|
|
30
|
+
"gamma": discount_q * density / (S * stddev),
|
|
31
|
+
"theta": (
|
|
32
|
+
-S * discount_q * density * sigma / (2 * sqrt_t)
|
|
33
|
+
+ sign * (q * S * discount_q * nd1 - r * K * discount_r * nd2)
|
|
34
|
+
),
|
|
35
|
+
"vega": S * discount_q * density * sqrt_t,
|
|
36
|
+
"rho": sign * K * T * discount_r * nd2,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def black_scholes_greeks(S, K, T, r, sigma, option_type="call", q=0.0):
|
|
41
|
+
"""Compute European option Greeks for scalar inputs.
|
|
42
|
+
|
|
43
|
+
Theta is per year of calendar-time passage. Vega and rho are per
|
|
44
|
+
unit change in decimal volatility and continuous decimal rate.
|
|
45
|
+
"""
|
|
46
|
+
option_type = _option_type(option_type)
|
|
47
|
+
values = _scalar_option_inputs(S, K, T, r, sigma, q, greeks=True)
|
|
48
|
+
greeks = _black_scholes_greeks(*values, option_type=option_type)
|
|
49
|
+
return {name: float(value) for name, value in greeks.items()}
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
from __future__ import annotations
|
|
10
10
|
|
|
11
|
+
from calendar import monthrange
|
|
11
12
|
from dataclasses import dataclass
|
|
12
13
|
from typing import Iterable
|
|
13
14
|
|
|
@@ -22,8 +23,9 @@ _DAY_COUNT_ALIASES = {
|
|
|
22
23
|
"ACT365F": "ACT/365F",
|
|
23
24
|
"ACTUAL/365F": "ACT/365F",
|
|
24
25
|
"30/360": "30/360",
|
|
25
|
-
"30/360
|
|
26
|
-
"
|
|
26
|
+
"30/360 BOND BASIS": "30/360",
|
|
27
|
+
"30/360 US": "30/360 US",
|
|
28
|
+
"30U/360": "30/360 US",
|
|
27
29
|
}
|
|
28
30
|
|
|
29
31
|
|
|
@@ -37,9 +39,15 @@ def normalize_day_count(convention: str) -> str:
|
|
|
37
39
|
|
|
38
40
|
|
|
39
41
|
def year_fraction(start_date, end_date, convention: str = "ACT/360") -> float:
|
|
40
|
-
"""Return
|
|
41
|
-
|
|
42
|
-
|
|
42
|
+
"""Return a calendar-date accrual fraction under a market convention.
|
|
43
|
+
|
|
44
|
+
The bare 30/360 alias retains Bond Basis. Select 30/360 US (30U/360)
|
|
45
|
+
for the U.S. rules that also adjust end-of-February dates.
|
|
46
|
+
"""
|
|
47
|
+
start_ts, end_ts = pd.Timestamp(start_date), pd.Timestamp(end_date)
|
|
48
|
+
if pd.isna(start_ts) or pd.isna(end_ts):
|
|
49
|
+
raise ValueError("start_date and end_date must be valid calendar dates")
|
|
50
|
+
start, end = start_ts.date(), end_ts.date()
|
|
43
51
|
if end < start:
|
|
44
52
|
raise ValueError("end_date must be on or after start_date")
|
|
45
53
|
|
|
@@ -51,6 +59,10 @@ def year_fraction(start_date, end_date, convention: str = "ACT/360") -> float:
|
|
|
51
59
|
|
|
52
60
|
start_day = min(start.day, 30)
|
|
53
61
|
end_day = end.day
|
|
62
|
+
if day_count == "30/360 US" and start.month == 2 and start.day == monthrange(start.year, 2)[1]:
|
|
63
|
+
start_day = 30
|
|
64
|
+
if end.month == 2 and end_day == monthrange(end.year, 2)[1]:
|
|
65
|
+
end_day = 30
|
|
54
66
|
if start_day == 30 and end_day == 31:
|
|
55
67
|
end_day = 30
|
|
56
68
|
days_360 = 360 * (end.year - start.year) + 30 * (end.month - start.month) + end_day - start_day
|
|
@@ -11,7 +11,6 @@ from __future__ import annotations
|
|
|
11
11
|
from dataclasses import dataclass
|
|
12
12
|
from typing import Iterable, Mapping
|
|
13
13
|
|
|
14
|
-
import matplotlib.pyplot as plt
|
|
15
14
|
import numpy as np
|
|
16
15
|
import pandas as pd
|
|
17
16
|
from scipy.interpolate import CubicSpline
|
|
@@ -455,6 +454,8 @@ def plot_yield_curve(
|
|
|
455
454
|
):
|
|
456
455
|
"""Plot zero and short forward rates with calibrated curve knots."""
|
|
457
456
|
if ax is None:
|
|
457
|
+
import matplotlib.pyplot as plt
|
|
458
|
+
|
|
458
459
|
_, ax = plt.subplots(figsize=(10, 5.5))
|
|
459
460
|
if tenors is None:
|
|
460
461
|
tenors = np.linspace(max(0.01, curve.tenors[1] / 10), curve.tenors[-1], 240)
|
|
@@ -13,7 +13,6 @@ from typing import Optional
|
|
|
13
13
|
|
|
14
14
|
import numpy as np
|
|
15
15
|
import pandas as pd
|
|
16
|
-
import statsmodels.api as sm
|
|
17
16
|
|
|
18
17
|
from riskoptima.optim.covariance import _tag_covariance, _validate_covariance, _validate_periods_per_year
|
|
19
18
|
|
|
@@ -26,6 +25,8 @@ class FactorRiskModel:
|
|
|
26
25
|
specific_var: Optional[pd.Series] = None
|
|
27
26
|
|
|
28
27
|
def fit(self, asset_returns: pd.DataFrame):
|
|
28
|
+
import statsmodels.api as sm
|
|
29
|
+
|
|
29
30
|
assets = pd.DataFrame(asset_returns).apply(pd.to_numeric, errors="coerce")
|
|
30
31
|
factors = pd.DataFrame(self.factor_returns).apply(pd.to_numeric, errors="coerce")
|
|
31
32
|
assets = assets.replace([np.inf, -np.inf], np.nan)
|