pymetrix-finance 0.1.0a1__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.
Files changed (70) hide show
  1. pymetrix_finance-0.1.0a1/.gitignore +10 -0
  2. pymetrix_finance-0.1.0a1/LICENSE +28 -0
  3. pymetrix_finance-0.1.0a1/PKG-INFO +58 -0
  4. pymetrix_finance-0.1.0a1/README.md +36 -0
  5. pymetrix_finance-0.1.0a1/THIRD-PARTY-NOTICES.md +38 -0
  6. pymetrix_finance-0.1.0a1/docs/tutorial.ipynb +307 -0
  7. pymetrix_finance-0.1.0a1/docs/tutorial.md +185 -0
  8. pymetrix_finance-0.1.0a1/pyproject.toml +45 -0
  9. pymetrix_finance-0.1.0a1/scripts/make_datasets.py +121 -0
  10. pymetrix_finance-0.1.0a1/scripts/make_tutorial_notebook.py +39 -0
  11. pymetrix_finance-0.1.0a1/src/pymetrix_finance/__init__.py +54 -0
  12. pymetrix_finance-0.1.0a1/src/pymetrix_finance/_version.py +1 -0
  13. pymetrix_finance-0.1.0a1/src/pymetrix_finance/app.py +1842 -0
  14. pymetrix_finance-0.1.0a1/src/pymetrix_finance/blacklitterman.py +146 -0
  15. pymetrix_finance-0.1.0a1/src/pymetrix_finance/contributions.py +153 -0
  16. pymetrix_finance-0.1.0a1/src/pymetrix_finance/copulas.py +1924 -0
  17. pymetrix_finance-0.1.0a1/src/pymetrix_finance/credit.py +274 -0
  18. pymetrix_finance-0.1.0a1/src/pymetrix_finance/datasets/__init__.py +34 -0
  19. pymetrix_finance-0.1.0a1/src/pymetrix_finance/datasets/event_returns.parquet +0 -0
  20. pymetrix_finance-0.1.0a1/src/pymetrix_finance/datasets/french.py +175 -0
  21. pymetrix_finance-0.1.0a1/src/pymetrix_finance/datasets/intraday_returns.parquet +0 -0
  22. pymetrix_finance-0.1.0a1/src/pymetrix_finance/datasets/option_chain.parquet +0 -0
  23. pymetrix_finance-0.1.0a1/src/pymetrix_finance/datasets/treasury_yields.parquet +0 -0
  24. pymetrix_finance-0.1.0a1/src/pymetrix_finance/datasets/yield_curves.parquet +0 -0
  25. pymetrix_finance-0.1.0a1/src/pymetrix_finance/events.py +199 -0
  26. pymetrix_finance-0.1.0a1/src/pymetrix_finance/mgarch.py +554 -0
  27. pymetrix_finance-0.1.0a1/src/pymetrix_finance/options.py +251 -0
  28. pymetrix_finance-0.1.0a1/src/pymetrix_finance/portfolio.py +306 -0
  29. pymetrix_finance-0.1.0a1/src/pymetrix_finance/realized.py +182 -0
  30. pymetrix_finance-0.1.0a1/src/pymetrix_finance/returns.py +173 -0
  31. pymetrix_finance-0.1.0a1/src/pymetrix_finance/risk.py +336 -0
  32. pymetrix_finance-0.1.0a1/src/pymetrix_finance/strategies.py +267 -0
  33. pymetrix_finance-0.1.0a1/src/pymetrix_finance/surface.py +338 -0
  34. pymetrix_finance-0.1.0a1/src/pymetrix_finance/termstructure.py +275 -0
  35. pymetrix_finance-0.1.0a1/src/pymetrix_finance/tvcopulas.py +738 -0
  36. pymetrix_finance-0.1.0a1/src/pymetrix_finance/vines.py +980 -0
  37. pymetrix_finance-0.1.0a1/src/pymetrix_finance/yields.py +225 -0
  38. pymetrix_finance-0.1.0a1/tests/conftest.py +47 -0
  39. pymetrix_finance-0.1.0a1/tests/french_stand_in.py +71 -0
  40. pymetrix_finance-0.1.0a1/tests/test_finance_black_litterman.py +90 -0
  41. pymetrix_finance-0.1.0a1/tests/test_finance_copula_bb_tawn.py +319 -0
  42. pymetrix_finance-0.1.0a1/tests/test_finance_copula_estimation.py +261 -0
  43. pymetrix_finance-0.1.0a1/tests/test_finance_copula_families.py +333 -0
  44. pymetrix_finance-0.1.0a1/tests/test_finance_copula_gof_d.py +79 -0
  45. pymetrix_finance-0.1.0a1/tests/test_finance_copula_multiplier.py +138 -0
  46. pymetrix_finance-0.1.0a1/tests/test_finance_copulas.py +89 -0
  47. pymetrix_finance-0.1.0a1/tests/test_finance_credit.py +56 -0
  48. pymetrix_finance-0.1.0a1/tests/test_finance_dcc_copula.py +141 -0
  49. pymetrix_finance-0.1.0a1/tests/test_finance_deco_vech.py +86 -0
  50. pymetrix_finance-0.1.0a1/tests/test_finance_dialogs_extra.py +155 -0
  51. pymetrix_finance-0.1.0a1/tests/test_finance_events.py +130 -0
  52. pymetrix_finance-0.1.0a1/tests/test_finance_french_download.py +87 -0
  53. pymetrix_finance-0.1.0a1/tests/test_finance_garch_t.py +104 -0
  54. pymetrix_finance-0.1.0a1/tests/test_finance_mgarch.py +120 -0
  55. pymetrix_finance-0.1.0a1/tests/test_finance_mgarch_paths.py +65 -0
  56. pymetrix_finance-0.1.0a1/tests/test_finance_options.py +148 -0
  57. pymetrix_finance-0.1.0a1/tests/test_finance_outside.py +57 -0
  58. pymetrix_finance-0.1.0a1/tests/test_finance_polish.py +70 -0
  59. pymetrix_finance-0.1.0a1/tests/test_finance_realized.py +109 -0
  60. pymetrix_finance-0.1.0a1/tests/test_finance_returns.py +201 -0
  61. pymetrix_finance-0.1.0a1/tests/test_finance_risk.py +147 -0
  62. pymetrix_finance-0.1.0a1/tests/test_finance_strategies.py +104 -0
  63. pymetrix_finance-0.1.0a1/tests/test_finance_surface.py +156 -0
  64. pymetrix_finance-0.1.0a1/tests/test_finance_termstructure.py +106 -0
  65. pymetrix_finance-0.1.0a1/tests/test_finance_tutorial.py +42 -0
  66. pymetrix_finance-0.1.0a1/tests/test_finance_tv_copulas.py +178 -0
  67. pymetrix_finance-0.1.0a1/tests/test_finance_vech.py +58 -0
  68. pymetrix_finance-0.1.0a1/tests/test_finance_vine_copulas.py +252 -0
  69. pymetrix_finance-0.1.0a1/tests/test_finance_vine_gof.py +134 -0
  70. pymetrix_finance-0.1.0a1/tests/test_public_surface.py +22 -0
@@ -0,0 +1,10 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .pytest_cache/
5
+ .pytest_tmp/
6
+ .venv/
7
+ build/
8
+ dist/
9
+ .ipynb_checkpoints/
10
+ hs_err_pid*.log
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Geoffrey Heenan
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,58 @@
1
+ Metadata-Version: 2.5
2
+ Name: pymetrix-finance
3
+ Version: 0.1.0a1
4
+ Summary: Financial econometrics for pymetrix: risk and backtests, multivariate GARCH, copulas, portfolios and strategies, options and volatility surfaces, yield curves, credit
5
+ Project-URL: Homepage, https://github.com/GeoffHeenan/pymetrix
6
+ Project-URL: Source, https://github.com/GeoffHeenan/pymetrix/tree/main/packages/pymetrix-finance
7
+ Project-URL: Issues, https://github.com/GeoffHeenan/pymetrix/issues
8
+ Project-URL: Changelog, https://github.com/GeoffHeenan/pymetrix/blob/main/CHANGELOG.md
9
+ Author: Geoffrey Heenan
10
+ License-Expression: BSD-3-Clause
11
+ License-File: LICENSE
12
+ License-File: THIRD-PARTY-NOTICES.md
13
+ Requires-Python: >=3.11
14
+ Requires-Dist: pymetrix>=0.1.0a8
15
+ Provides-Extra: test
16
+ Requires-Dist: arch; extra == 'test'
17
+ Requires-Dist: linearmodels; extra == 'test'
18
+ Requires-Dist: pytest>=9.0.3; extra == 'test'
19
+ Requires-Dist: quantlib; extra == 'test'
20
+ Requires-Dist: statsmodels; extra == 'test'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # pymetrix-finance
24
+
25
+ Financial econometrics for [pymetrix](https://github.com/GeoffHeenan/pymetrix), as a plugin: value at risk and expected shortfall with their
26
+ backtests, multivariate GARCH (CCC, DCC, asymmetric DCC, BEKK), copulas (Gaussian, t, Archimedean, BB1, BB6, BB7,
27
+ BB8, Tawn, rotated; fitted or rank margins; family comparison and goodness of fit by parametric or multiplier
28
+ bootstrap; R-, C- and D-vines with a Rosenblatt-transform goodness-of-fit test; Patton's time-varying copulas and DCC
29
+ copulas of several series), risk contributions, returns and performance,
30
+ factor models and the GRS test, portfolios and strategy backtests, event studies, realised volatility and HAR, option
31
+ pricing, implied volatility and volatility surfaces (SVI, SABR, Heston), yield curves and the dynamic Nelson-Siegel
32
+ model, bonds, and credit risk (Merton, CDS).
33
+
34
+ ```
35
+ pip install pymetrix[finance] # or: pip install pymetrix-finance
36
+ ```
37
+
38
+ ```python
39
+ from pymetrix import Dataset
40
+ from pymetrix_finance import performance, value_at_risk # also importable from pymetrix once installed
41
+
42
+ ff = Dataset.example("french") # downloaded from Kenneth French's data library on first use, then cached
43
+ value_at_risk(ff, "mkt_rf", level=0.99, method="garch", dist="t", asymmetric=True).backtests()
44
+ ```
45
+
46
+ In the app, everything is under the **Finance** menu and workspace. The [tutorial](https://github.com/GeoffHeenan/pymetrix/blob/main/packages/pymetrix-finance/docs/tutorial.md) (also a
47
+ [notebook](https://github.com/GeoffHeenan/pymetrix/blob/main/packages/pymetrix-finance/docs/tutorial.ipynb)) walks through it on the example datasets, and its tests check what it says. The Fama-French returns (`french`)
48
+ are not shipped, as Kenneth French's data library gives no licence to redistribute them: the first
49
+ `Dataset.example("french")` downloads them from the library and keeps them in `~/.pymetrix/cache/datasets/`.
50
+
51
+ The plugin needs nothing beyond pymetrix's own dependencies. Its checks are listed in pymetrix's
52
+ [validation page](https://github.com/GeoffHeenan/pymetrix/blob/main/docs/validation.md#finance-the-bundled-plugin); arch and QuantLib are used there as test
53
+ oracles only. License: BSD-3-Clause.
54
+
55
+ ## Development
56
+
57
+ From the repository root: `pip install -e packages/pymetrix-finance`, then `python -m pytest`; the repository's test
58
+ run includes this package's tests, which skip when it is not installed.
@@ -0,0 +1,36 @@
1
+ # pymetrix-finance
2
+
3
+ Financial econometrics for [pymetrix](https://github.com/GeoffHeenan/pymetrix), as a plugin: value at risk and expected shortfall with their
4
+ backtests, multivariate GARCH (CCC, DCC, asymmetric DCC, BEKK), copulas (Gaussian, t, Archimedean, BB1, BB6, BB7,
5
+ BB8, Tawn, rotated; fitted or rank margins; family comparison and goodness of fit by parametric or multiplier
6
+ bootstrap; R-, C- and D-vines with a Rosenblatt-transform goodness-of-fit test; Patton's time-varying copulas and DCC
7
+ copulas of several series), risk contributions, returns and performance,
8
+ factor models and the GRS test, portfolios and strategy backtests, event studies, realised volatility and HAR, option
9
+ pricing, implied volatility and volatility surfaces (SVI, SABR, Heston), yield curves and the dynamic Nelson-Siegel
10
+ model, bonds, and credit risk (Merton, CDS).
11
+
12
+ ```
13
+ pip install pymetrix[finance] # or: pip install pymetrix-finance
14
+ ```
15
+
16
+ ```python
17
+ from pymetrix import Dataset
18
+ from pymetrix_finance import performance, value_at_risk # also importable from pymetrix once installed
19
+
20
+ ff = Dataset.example("french") # downloaded from Kenneth French's data library on first use, then cached
21
+ value_at_risk(ff, "mkt_rf", level=0.99, method="garch", dist="t", asymmetric=True).backtests()
22
+ ```
23
+
24
+ In the app, everything is under the **Finance** menu and workspace. The [tutorial](https://github.com/GeoffHeenan/pymetrix/blob/main/packages/pymetrix-finance/docs/tutorial.md) (also a
25
+ [notebook](https://github.com/GeoffHeenan/pymetrix/blob/main/packages/pymetrix-finance/docs/tutorial.ipynb)) walks through it on the example datasets, and its tests check what it says. The Fama-French returns (`french`)
26
+ are not shipped, as Kenneth French's data library gives no licence to redistribute them: the first
27
+ `Dataset.example("french")` downloads them from the library and keeps them in `~/.pymetrix/cache/datasets/`.
28
+
29
+ The plugin needs nothing beyond pymetrix's own dependencies. Its checks are listed in pymetrix's
30
+ [validation page](https://github.com/GeoffHeenan/pymetrix/blob/main/docs/validation.md#finance-the-bundled-plugin); arch and QuantLib are used there as test
31
+ oracles only. License: BSD-3-Clause.
32
+
33
+ ## Development
34
+
35
+ From the repository root: `pip install -e packages/pymetrix-finance`, then `python -m pytest`; the repository's test
36
+ run includes this package's tests, which skip when it is not installed.
@@ -0,0 +1,38 @@
1
+ # Third-party notices: pymetrix-finance
2
+
3
+ The plugin's own code, documentation and simulated data are under the BSD-3-Clause licence in `LICENSE`. One of its
4
+ bundled datasets comes from elsewhere, and one example is downloaded when first used; this notice ships with the
5
+ plugin's sdist and wheel. Each dataset also records its source in its own metadata
6
+ (`Dataset.example(name).meta.license`). pymetrix's own notices are in `THIRD-PARTY-NOTICES.md` in the `pymetrix`
7
+ package.
8
+
9
+ ## US Treasury yields (Federal Reserve H.15, via FRED)
10
+
11
+ `src/pymetrix_finance/datasets/treasury_yields.parquet` (`Dataset.example("treasury_yields")`).
12
+
13
+ Constant-maturity Treasury yields, monthly, 1982-2026, from the Board of Governors of the Federal Reserve System's
14
+ H.15 release, retrieved through FRED (https://fred.stlouisfed.org/), Federal Reserve Bank of St. Louis. The H.15
15
+ series are the Board's and in the public domain under its website terms (https://www.federalreserve.gov/disclaimer.htm:
16
+ "may be copied and distributed without permission"; the Board is cited as the source); FRED is credited as the source
17
+ it was retrieved from.
18
+
19
+ ## Fama-French factors and portfolios (Kenneth R. French Data Library): downloaded, not shipped
20
+
21
+ `Dataset.example("french")`: monthly factor and portfolio returns, January 1949 to March 2017, from the Kenneth R.
22
+ French Data Library (https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html). The library's files
23
+ are marked "Copyright Eugene F. Fama and Kenneth R. French" and the library states no licence to redistribute them,
24
+ so the plugin does not ship them: the first load downloads five of the library's CSV files and keeps the dataset in
25
+ the user's cache (`~/.pymetrix/cache/datasets/french.parquet`, `src/pymetrix_finance/datasets/french.py`). The data
26
+ remain Eugene F. Fama's and Kenneth R. French's.
27
+
28
+ ## Simulated datasets (BSD-3-Clause)
29
+
30
+ `event_returns`, `intraday_returns`, `option_chain` and `yield_curves` are simulated by pymetrix and are under the
31
+ plugin's own licence.
32
+
33
+ ## Reference values in the tests
34
+
35
+ `tests/test_finance_outside.py` transcribes a few published numbers, attributed where they are used, to check the
36
+ Black-Litterman results against: the correlations, volatilities, market weights and returns (equilibrium and with
37
+ the first view) of Table 1 of He, G. and Litterman, R. (1999), *The intuition behind Black-Litterman model
38
+ portfolios* (Goldman Sachs).
@@ -0,0 +1,307 @@
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Finance with pymetrix: a tutorial\n",
8
+ "\n",
9
+ "This page walks through the finance plugin (`pymetrix-finance`, bundled with pymetrix) on its example datasets:\n",
10
+ "returns and performance, factor models, portfolios and their risk, value at risk, volatility from intraday data,\n",
11
+ "event studies, yield curves and options. Each step is also a dialog in the app's **Finance** menu, and the app\n",
12
+ "writes it as code in the **Script** window. The [user guide](../../../docs/guide.md) has the detail on each function, and the\n",
13
+ "plugin's help topics (in Help → Help contents) the background and references.\n",
14
+ "\n",
15
+ "The code blocks run in order, as one script; a test runs them as written, so they stay correct. The same page is a\n",
16
+ "notebook, `docs/finance-tutorial.ipynb`. Two datasets are\n",
17
+ "real: the Fama-French returns (Kenneth French's data library) and US Treasury yields (the Federal Reserve's H.15, from\n",
18
+ "FRED). The rest are simulated, with the true values in each dataset's description, so you can see the methods recover\n",
19
+ "them. The Fama-French returns are the one download: the library's files are Eugene Fama's and Kenneth French's\n",
20
+ "copyright, so pymetrix does not ship them, and the first `Dataset.example(\"french\")` fetches them from the library\n",
21
+ "(an internet connection is needed once) and keeps them in `~/.pymetrix/cache/datasets/`. The library revises its\n",
22
+ "history now and then, so your numbers may differ slightly from the ones described here. Returns are fractions per\n",
23
+ "period (0.01 for 1%) throughout.\n",
24
+ "\n",
25
+ "## 1. Returns and performance"
26
+ ]
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "metadata": {},
31
+ "source": [
32
+ "import numpy as np\n",
33
+ "from pymetrix import Dataset, performance\n",
34
+ "\n",
35
+ "ff = Dataset.example(\"french\") # monthly, 1949-2017: factors, industries, sorted portfolios (downloaded once)\n",
36
+ "print(ff.meta.description)\n",
37
+ "\n",
38
+ "perf = performance(ff, [\"mkt_rf\", \"smb\", \"hml\", \"mom\"], kind=\"simple\")\n",
39
+ "perf.table() # annual return and volatility, Sharpe (with its standard error), drawdowns..."
40
+ ],
41
+ "execution_count": null,
42
+ "outputs": []
43
+ },
44
+ {
45
+ "cell_type": "markdown",
46
+ "metadata": {},
47
+ "source": [
48
+ "`perf.plot()` draws the growth of 1 invested and the drawdowns. Momentum has the highest Sharpe ratio here, and by\n",
49
+ "far the fattest left tail: compare its skewness and kurtosis with the market's. With prices rather than returns,\n",
50
+ "`returns(data, [\"spx\"])` adds log or simple returns first.\n",
51
+ "\n",
52
+ "## 2. A factor model"
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "metadata": {},
58
+ "source": [
59
+ "from pymetrix import factor_model\n",
60
+ "\n",
61
+ "industries = [\"nodur\", \"durbl\", \"manuf\", \"enrgy\", \"hlth\", \"money\"]\n",
62
+ "fm = factor_model(ff, industries, [\"mkt_rf\", \"smb\", \"hml\"], rf=\"rf\")\n",
63
+ "fm.summary() # alphas, betas with Newey-West t statistics, R2, the GRS test\n",
64
+ "p_grs = fm.test[1]"
65
+ ],
66
+ "execution_count": null,
67
+ "outputs": []
68
+ },
69
+ {
70
+ "cell_type": "markdown",
71
+ "metadata": {},
72
+ "source": [
73
+ "Each industry's excess return is regressed on the three Fama-French factors. The Gibbons-Ross-Shanken test asks\n",
74
+ "whether all six alphas are zero together; here it rejects, largely on health care's positive alpha.\n",
75
+ "`fm.rolling_betas(60)` shows how the exposures moved over five-year windows.\n",
76
+ "\n",
77
+ "## 3. A portfolio and where its risk comes from"
78
+ ]
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "metadata": {},
83
+ "source": [
84
+ "from pymetrix import optimize_portfolio, risk_contributions\n",
85
+ "\n",
86
+ "rf = float(ff[\"rf\"].mean())\n",
87
+ "port = optimize_portfolio(ff, industries, objective=\"max_sharpe\", rf=rf) # long only, by default\n",
88
+ "port.weights_table()\n",
89
+ "frontier = port.frontier(20) # the efficient frontier within the same bounds\n",
90
+ "\n",
91
+ "rc = risk_contributions(ff, industries, port.weights, level=0.99)\n",
92
+ "rc.table() # marginal and component VaR and ES; the components add up\n",
93
+ "assert abs(rc.frame()[\"component VaR\"].sum() - rc.var) < 1e-12"
94
+ ],
95
+ "execution_count": null,
96
+ "outputs": []
97
+ },
98
+ {
99
+ "cell_type": "markdown",
100
+ "metadata": {},
101
+ "source": [
102
+ "Non-durables carry the largest weight and the largest share of the portfolio's risk. `objective=\"min_variance\"`\n",
103
+ "or `\"target_return\"` (with `target_return=`) give the other classic portfolios, and `cov=` takes a covariance matrix or a\n",
104
+ "fitted multivariate GARCH.\n",
105
+ "\n",
106
+ "### Would it have worked?"
107
+ ]
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "from pymetrix import backtest_strategy\n",
114
+ "\n",
115
+ "bt = backtest_strategy(ff, industries, [\"equal_weight\", \"min_variance\", \"max_sharpe\", \"risk_parity\"],\n",
116
+ " window=60, rebalance=12, cost=0.002, rf=\"rf\")\n",
117
+ "bt.performance() # out of sample, net of 20 basis points per unit of turnover"
118
+ ],
119
+ "execution_count": null,
120
+ "outputs": []
121
+ },
122
+ {
123
+ "cell_type": "markdown",
124
+ "metadata": {},
125
+ "source": [
126
+ "Each year the weights are re-estimated from the five years before. Out of sample, minimum variance has the best\n",
127
+ "Sharpe ratio and maximum Sharpe the worst, with the most turnover: estimated means are too noisy to optimise on.\n",
128
+ "\n",
129
+ "## 4. Value at risk, and checking it"
130
+ ]
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "metadata": {},
135
+ "source": [
136
+ "from pymetrix import value_at_risk\n",
137
+ "\n",
138
+ "risk = value_at_risk(ff, \"mkt_rf\", level=0.99, method=\"garch\", window=120)\n",
139
+ "risk.backtests() # Kupiec, Christoffersen, dynamic quantile, McNeil-Frey, Basel zone\n",
140
+ "\n",
141
+ "fat = value_at_risk(ff, \"mkt_rf\", level=0.99, method=\"garch\", window=120, dist=\"t\", asymmetric=True)\n",
142
+ "cf = value_at_risk(ff, \"mkt_rf\", level=0.99, method=\"cornish_fisher\", window=120)\n",
143
+ "counts = {\"normal GARCH\": risk.violations, \"t-GJR GARCH\": fat.violations, \"Cornish-Fisher\": cf.violations}"
144
+ ],
145
+ "execution_count": null,
146
+ "outputs": []
147
+ },
148
+ {
149
+ "cell_type": "markdown",
150
+ "metadata": {},
151
+ "source": [
152
+ "Each month's VaR uses only the months before it; about 7 of the 699 months should exceed a 99% VaR. A normal\n",
153
+ "GARCH(1,1) is too thin-tailed for monthly market returns: its violations are nearly three times that, and the\n",
154
+ "backtests say so. Student-t errors with the GJR asymmetry help, but not enough, as the market's monthly crashes are\n",
155
+ "fatter-tailed still; Cornish-Fisher, which adapts to the window's skewness and kurtosis, passes the Kupiec test.\n",
156
+ "\n",
157
+ "## 5. Volatility from intraday returns"
158
+ ]
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "metadata": {},
163
+ "source": [
164
+ "from pymetrix import har, realized_measures\n",
165
+ "\n",
166
+ "intraday = Dataset.example(\"intraday_returns\") # 250 days of 78 five-minute returns, with ten jumps\n",
167
+ "daily = realized_measures(intraday, \"r\") # one row a day: rv, bv, the jump test, rvol\n",
168
+ "jump_days = daily.frame.index[daily.frame[\"jump\"] > 0]\n",
169
+ "print(len(jump_days), \"jump days found;\", intraday.meta.description.split(\"ten days: \")[1])\n",
170
+ "\n",
171
+ "fit = har(daily, \"rv\", log=True) # tomorrow's realised variance from its daily, weekly, monthly averages\n",
172
+ "fit.summary()\n",
173
+ "tomorrow = fit.value_at_risk(0.99) # a one-day VaR from the HAR's variance forecast"
174
+ ],
175
+ "execution_count": null,
176
+ "outputs": []
177
+ },
178
+ {
179
+ "cell_type": "markdown",
180
+ "metadata": {},
181
+ "source": [
182
+ "Bipower variation measures each day's variance without its jumps, realised variance with them; the\n",
183
+ "Barndorff-Nielsen-Shephard test compares the two and finds the planted jump days.\n",
184
+ "\n",
185
+ "## 6. An event study"
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "metadata": {},
191
+ "source": [
192
+ "from pymetrix import abnormal_returns\n",
193
+ "\n",
194
+ "er = Dataset.example(\"event_returns\") # 20 firms and the market; each firm has one event worth +2%\n",
195
+ "listed = er.meta.description.split(\"on the day: \")[1]\n",
196
+ "events = {e.split()[0]: e.split()[1] for e in listed.split(\"; \")}\n",
197
+ "\n",
198
+ "ev = abnormal_returns(er, events, market=\"mkt\", car_window=(0, 0))\n",
199
+ "ev.tests() # cross-sectional t, Patell, BMP and rank tests\n",
200
+ "mean_car = float(ev.car().mean()) # close to the true 0.02"
201
+ ],
202
+ "execution_count": null,
203
+ "outputs": []
204
+ },
205
+ {
206
+ "cell_type": "markdown",
207
+ "metadata": {},
208
+ "source": [
209
+ "Normal returns come from each firm's market model over trading days -250 to -11. `ev.plot()` shows the cumulative\n",
210
+ "average abnormal return around the event, and `car_window=(-1, 1)` tests a three-day window.\n",
211
+ "\n",
212
+ "## 7. Yield curves"
213
+ ]
214
+ },
215
+ {
216
+ "cell_type": "code",
217
+ "metadata": {},
218
+ "source": [
219
+ "from pymetrix import yield_curve\n",
220
+ "\n",
221
+ "treasury = Dataset.example(\"treasury_yields\") # US Treasury constant-maturity yields, monthly, from FRED\n",
222
+ "names = [\"m3\", \"m6\", \"y1\", \"y2\", \"y3\", \"y5\", \"y7\", \"y10\", \"y20\", \"y30\"]\n",
223
+ "years = [0.25, 0.5, 1, 2, 3, 5, 7, 10, 20, 30]\n",
224
+ "yc = yield_curve(treasury, names, years)\n",
225
+ "yc.table() # the fit at each maturity (a few basis points), and the decay\n",
226
+ "ahead = yc.forecast(12) # a year ahead from an AR(1) for each factor (Diebold-Li)\n",
227
+ "sv = yield_curve(treasury, names, years, model=\"svensson\") # a second hump fits the short end better\n",
228
+ "\n",
229
+ "simulated = yield_curve(Dataset.example(\"yield_curves\"), names, years) # made with decay 0.7308\n",
230
+ "assert abs(simulated.lam - 0.7308) < 0.05"
231
+ ],
232
+ "execution_count": null,
233
+ "outputs": []
234
+ },
235
+ {
236
+ "cell_type": "markdown",
237
+ "metadata": {},
238
+ "source": [
239
+ "Yields are in percent. The 20-year series is missing from 1987 to 1993 and the 30-year from 2002 to 2006, when the\n",
240
+ "Treasury did not issue them; each month is fitted on the maturities it has. On the simulated curves the decay comes\n",
241
+ "out close to the true 0.7308 and the AR(1) coefficients near the true 0.99, 0.95 and 0.8. `yc.factors` is an\n",
242
+ "ordinary table: put it into a VAR for the factors' joint dynamics.\n",
243
+ "\n",
244
+ "## 8. Options"
245
+ ]
246
+ },
247
+ {
248
+ "cell_type": "code",
249
+ "metadata": {},
250
+ "source": [
251
+ "from pymetrix import implied_volatility, option_price\n",
252
+ "\n",
253
+ "put = option_price(spot=100, strike=95, expiry=0.5, rate=0.03, vol=0.2, dividend=0.01, kind=\"put\", american=True)\n",
254
+ "put.table() # the price and Greeks, from a binomial tree\n",
255
+ "\n",
256
+ "chain = Dataset.example(\"option_chain\") # out-of-the-money puts and calls at five expiries\n",
257
+ "smile = implied_volatility(chain, \"price\", \"strike\", \"expiry\", spot=100, rate=0.03, dividend=0.01, kind=\"cp\")\n",
258
+ "error = np.nanmax(np.abs(smile.frame[\"implied vol\"].to_numpy() - chain[\"true_vol\"].to_numpy()))\n",
259
+ "assert error < 1e-3 # the volatilities the prices were made with, to the prices' rounding"
260
+ ],
261
+ "execution_count": null,
262
+ "outputs": []
263
+ },
264
+ {
265
+ "cell_type": "markdown",
266
+ "metadata": {},
267
+ "source": [
268
+ "`smile.plot()` draws the skew, one line per expiry: puts below the spot are dearer in volatility than calls above\n",
269
+ "it, as in equity index markets."
270
+ ]
271
+ },
272
+ {
273
+ "cell_type": "code",
274
+ "metadata": {},
275
+ "source": [
276
+ "from pymetrix import vol_surface\n",
277
+ "\n",
278
+ "surf = vol_surface(chain, \"price\", \"strike\", \"expiry\", spot=100, rate=0.03, dividend=0.01, kind=\"cp\", model=\"svi\")\n",
279
+ "surf.arbitrage() # butterfly and calendar checks, expiry by expiry\n",
280
+ "heston = vol_surface(chain, \"price\", \"strike\", \"expiry\", spot=100, rate=0.03, dividend=0.01, kind=\"cp\", model=\"heston\")"
281
+ ],
282
+ "execution_count": null,
283
+ "outputs": []
284
+ },
285
+ {
286
+ "cell_type": "markdown",
287
+ "metadata": {},
288
+ "source": [
289
+ "SVI fits each expiry's smile to within a few hundredths of a volatility point and passes the arbitrage checks over the\n",
290
+ "quotes. Heston, with one set of parameters for every expiry, cannot: its smiles flatten as expiry grows and these do\n",
291
+ "not, and its summary says its parameters have reached their bounds. `surf.plot()` shows market and model smiles."
292
+ ]
293
+ }
294
+ ],
295
+ "metadata": {
296
+ "kernelspec": {
297
+ "display_name": "Python 3",
298
+ "language": "python",
299
+ "name": "python3"
300
+ },
301
+ "language_info": {
302
+ "name": "python"
303
+ }
304
+ },
305
+ "nbformat": 4,
306
+ "nbformat_minor": 5
307
+ }