tensorquantlib 0.3.0__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 (82) hide show
  1. tensorquantlib-0.3.0/LICENSE +21 -0
  2. tensorquantlib-0.3.0/PKG-INFO +602 -0
  3. tensorquantlib-0.3.0/README.md +558 -0
  4. tensorquantlib-0.3.0/pyproject.toml +128 -0
  5. tensorquantlib-0.3.0/setup.cfg +4 -0
  6. tensorquantlib-0.3.0/src/tensorquantlib/__init__.py +313 -0
  7. tensorquantlib-0.3.0/src/tensorquantlib/__main__.py +315 -0
  8. tensorquantlib-0.3.0/src/tensorquantlib/backtest/__init__.py +48 -0
  9. tensorquantlib-0.3.0/src/tensorquantlib/backtest/engine.py +240 -0
  10. tensorquantlib-0.3.0/src/tensorquantlib/backtest/metrics.py +320 -0
  11. tensorquantlib-0.3.0/src/tensorquantlib/backtest/strategy.py +348 -0
  12. tensorquantlib-0.3.0/src/tensorquantlib/core/__init__.py +6 -0
  13. tensorquantlib-0.3.0/src/tensorquantlib/core/ops.py +70 -0
  14. tensorquantlib-0.3.0/src/tensorquantlib/core/second_order.py +465 -0
  15. tensorquantlib-0.3.0/src/tensorquantlib/core/tensor.py +928 -0
  16. tensorquantlib-0.3.0/src/tensorquantlib/data/__init__.py +16 -0
  17. tensorquantlib-0.3.0/src/tensorquantlib/data/market.py +160 -0
  18. tensorquantlib-0.3.0/src/tensorquantlib/finance/__init__.py +52 -0
  19. tensorquantlib-0.3.0/src/tensorquantlib/finance/american.py +263 -0
  20. tensorquantlib-0.3.0/src/tensorquantlib/finance/basket.py +291 -0
  21. tensorquantlib-0.3.0/src/tensorquantlib/finance/black_scholes.py +219 -0
  22. tensorquantlib-0.3.0/src/tensorquantlib/finance/credit.py +199 -0
  23. tensorquantlib-0.3.0/src/tensorquantlib/finance/exotics.py +885 -0
  24. tensorquantlib-0.3.0/src/tensorquantlib/finance/fx.py +204 -0
  25. tensorquantlib-0.3.0/src/tensorquantlib/finance/greeks.py +133 -0
  26. tensorquantlib-0.3.0/src/tensorquantlib/finance/heston.py +543 -0
  27. tensorquantlib-0.3.0/src/tensorquantlib/finance/implied_vol.py +277 -0
  28. tensorquantlib-0.3.0/src/tensorquantlib/finance/ir_derivatives.py +203 -0
  29. tensorquantlib-0.3.0/src/tensorquantlib/finance/jump_diffusion.py +203 -0
  30. tensorquantlib-0.3.0/src/tensorquantlib/finance/local_vol.py +146 -0
  31. tensorquantlib-0.3.0/src/tensorquantlib/finance/rates.py +381 -0
  32. tensorquantlib-0.3.0/src/tensorquantlib/finance/risk.py +344 -0
  33. tensorquantlib-0.3.0/src/tensorquantlib/finance/variance_reduction.py +420 -0
  34. tensorquantlib-0.3.0/src/tensorquantlib/finance/volatility.py +355 -0
  35. tensorquantlib-0.3.0/src/tensorquantlib/py.typed +0 -0
  36. tensorquantlib-0.3.0/src/tensorquantlib/tt/__init__.py +43 -0
  37. tensorquantlib-0.3.0/src/tensorquantlib/tt/decompose.py +576 -0
  38. tensorquantlib-0.3.0/src/tensorquantlib/tt/ops.py +386 -0
  39. tensorquantlib-0.3.0/src/tensorquantlib/tt/pricing.py +304 -0
  40. tensorquantlib-0.3.0/src/tensorquantlib/tt/surrogate.py +634 -0
  41. tensorquantlib-0.3.0/src/tensorquantlib/utils/__init__.py +5 -0
  42. tensorquantlib-0.3.0/src/tensorquantlib/utils/validation.py +126 -0
  43. tensorquantlib-0.3.0/src/tensorquantlib/viz/__init__.py +27 -0
  44. tensorquantlib-0.3.0/src/tensorquantlib/viz/plots.py +331 -0
  45. tensorquantlib-0.3.0/src/tensorquantlib.egg-info/PKG-INFO +602 -0
  46. tensorquantlib-0.3.0/src/tensorquantlib.egg-info/SOURCES.txt +80 -0
  47. tensorquantlib-0.3.0/src/tensorquantlib.egg-info/dependency_links.txt +1 -0
  48. tensorquantlib-0.3.0/src/tensorquantlib.egg-info/requires.txt +23 -0
  49. tensorquantlib-0.3.0/src/tensorquantlib.egg-info/top_level.txt +1 -0
  50. tensorquantlib-0.3.0/tests/test_american.py +74 -0
  51. tensorquantlib-0.3.0/tests/test_backtest.py +579 -0
  52. tensorquantlib-0.3.0/tests/test_basket.py +167 -0
  53. tensorquantlib-0.3.0/tests/test_benchmark_validation.py +575 -0
  54. tensorquantlib-0.3.0/tests/test_black_scholes.py +142 -0
  55. tensorquantlib-0.3.0/tests/test_coverage_gaps.py +203 -0
  56. tensorquantlib-0.3.0/tests/test_credit.py +132 -0
  57. tensorquantlib-0.3.0/tests/test_data.py +147 -0
  58. tensorquantlib-0.3.0/tests/test_edge_cases.py +439 -0
  59. tensorquantlib-0.3.0/tests/test_exotics.py +292 -0
  60. tensorquantlib-0.3.0/tests/test_fx.py +125 -0
  61. tensorquantlib-0.3.0/tests/test_heston.py +88 -0
  62. tensorquantlib-0.3.0/tests/test_implied_vol.py +80 -0
  63. tensorquantlib-0.3.0/tests/test_integration.py +427 -0
  64. tensorquantlib-0.3.0/tests/test_ir_derivatives.py +132 -0
  65. tensorquantlib-0.3.0/tests/test_jump_diffusion.py +88 -0
  66. tensorquantlib-0.3.0/tests/test_local_vol.py +85 -0
  67. tensorquantlib-0.3.0/tests/test_new_ops.py +159 -0
  68. tensorquantlib-0.3.0/tests/test_ops.py +261 -0
  69. tensorquantlib-0.3.0/tests/test_rates.py +184 -0
  70. tensorquantlib-0.3.0/tests/test_risk.py +140 -0
  71. tensorquantlib-0.3.0/tests/test_second_order.py +291 -0
  72. tensorquantlib-0.3.0/tests/test_surrogate.py +228 -0
  73. tensorquantlib-0.3.0/tests/test_tensor.py +113 -0
  74. tensorquantlib-0.3.0/tests/test_tt_arithmetic.py +210 -0
  75. tensorquantlib-0.3.0/tests/test_tt_cross.py +272 -0
  76. tensorquantlib-0.3.0/tests/test_tt_decompose.py +241 -0
  77. tensorquantlib-0.3.0/tests/test_tt_ops.py +256 -0
  78. tensorquantlib-0.3.0/tests/test_tt_pricing.py +150 -0
  79. tensorquantlib-0.3.0/tests/test_validation.py +125 -0
  80. tensorquantlib-0.3.0/tests/test_variance_reduction.py +103 -0
  81. tensorquantlib-0.3.0/tests/test_viz.py +112 -0
  82. tensorquantlib-0.3.0/tests/test_volatility.py +175 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TensorQuantLib Contributors
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 all
13
+ 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 THE
21
+ SOFTWARE.
@@ -0,0 +1,602 @@
1
+ Metadata-Version: 2.4
2
+ Name: tensorquantlib
3
+ Version: 0.3.0
4
+ Summary: Comprehensive quantitative finance library with tensor-train compression, autodiff, and stochastic models
5
+ Author: TensorQuantLib Contributors
6
+ License: MIT
7
+ Project-URL: Repository, https://github.com/raswanthmalai19/TensorQuantLib
8
+ Project-URL: Documentation, https://raswanthmalai19.github.io/TensorQuantLib./
9
+ Project-URL: Bug Tracker, https://github.com/raswanthmalai19/TensorQuantLib/issues
10
+ Project-URL: Changelog, https://github.com/raswanthmalai19/TensorQuantLib/blob/main/CHANGELOG.md
11
+ Keywords: quantitative finance,tensor train,autodiff,options pricing,basket options,surrogate model,tensor decomposition,black-scholes,heston,american options,exotic options,implied volatility,risk management,monte carlo,variance reduction
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Intended Audience :: Financial and Insurance Industry
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
20
+ Classifier: Topic :: Office/Business :: Financial
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: numpy>=1.24
26
+ Requires-Dist: scipy>=1.10
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=7.0; extra == "dev"
29
+ Requires-Dist: pytest-cov; extra == "dev"
30
+ Requires-Dist: matplotlib>=3.7; extra == "dev"
31
+ Requires-Dist: mypy>=1.0; extra == "dev"
32
+ Requires-Dist: ruff>=0.4; extra == "dev"
33
+ Requires-Dist: pre-commit>=3.0; extra == "dev"
34
+ Provides-Extra: viz
35
+ Requires-Dist: matplotlib>=3.7; extra == "viz"
36
+ Provides-Extra: docs
37
+ Requires-Dist: sphinx>=7.0; extra == "docs"
38
+ Requires-Dist: sphinx-autodoc-typehints>=1.25; extra == "docs"
39
+ Provides-Extra: data
40
+ Requires-Dist: yfinance>=0.2; extra == "data"
41
+ Provides-Extra: all
42
+ Requires-Dist: tensorquantlib[data,dev,docs,viz]; extra == "all"
43
+ Dynamic: license-file
44
+
45
+ # TensorQuantLib
46
+
47
+ [![CI](https://github.com/raswanthmalai19/TensorQuantLib/actions/workflows/ci.yml/badge.svg)](https://github.com/raswanthmalai19/TensorQuantLib/actions/workflows/ci.yml)
48
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
49
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
50
+ [![Coverage: 98%](https://img.shields.io/badge/coverage-98%25-brightgreen.svg)](https://github.com/raswanthmalai19/TensorQuantLib)
51
+ [![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://docs.astral.sh/ruff/)
52
+ [![Typed: mypy strict](https://img.shields.io/badge/typed-mypy%20strict-blue.svg)](https://mypy-lang.org/)
53
+ [![Tests: 588](https://img.shields.io/badge/tests-588%20passing-brightgreen.svg)](https://github.com/raswanthmalai19/TensorQuantLib/actions)
54
+ [![Docs](https://img.shields.io/badge/docs-GitHub%20Pages-blue.svg)](https://raswanthmalai19.github.io/TensorQuantLib./)
55
+
56
+ **A comprehensive quantitative finance library with tensor-train compression, automatic differentiation, and stochastic models — built from scratch with NumPy and SciPy.**
57
+
58
+ TensorQuantLib provides a complete toolkit for derivatives pricing, risk management, and portfolio analysis. It compresses high-dimensional pricing surfaces using **Tensor-Train (TT) decomposition**, prices options with **Black-Scholes, Heston, American, Exotic, and Monte Carlo engines**, and computes Greeks via a custom **reverse-mode autodiff engine** — including second-order Greeks (Gamma, Vanna, Volga).
59
+
60
+ > **No PyTorch. No TensorFlow. No JAX.** Custom autograd, custom TT-SVD, custom stochastic models — built entirely with NumPy and SciPy.
61
+
62
+ ---
63
+
64
+ ## Documentation
65
+
66
+ Complete documentation with API reference, tutorials, and examples:
67
+ **[https://raswanthmalai19.github.io/TensorQuantLib./](https://raswanthmalai19.github.io/TensorQuantLib./)**
68
+
69
+ ### Quick Links
70
+ - [**API Reference**](https://raswanthmalai19.github.io/TensorQuantLib./api.html) — Full module documentation
71
+ - [**Quick Start**](https://raswanthmalai19.github.io/TensorQuantLib./quickstart.html) — Getting started guide
72
+ - [**Theory**](https://raswanthmalai19.github.io/TensorQuantLib./theory.html) — Mathematical foundations
73
+ - [**Changelog**](https://raswanthmalai19.github.io/TensorQuantLib./changelog.html) — Version history
74
+
75
+ ---
76
+
77
+ ## Features
78
+
79
+ | Module | Capability | Description |
80
+ |--------|-----------|-------------|
81
+ | **Core** | Autograd Engine | Reverse-mode AD — 23+ differentiable ops (sin, cos, tanh, softmax, clip, where, abs) |
82
+ | **Core** | Second-Order AD | Hessians, HVPs, mixed partials, Gamma/Vanna/Volga via autodiff |
83
+ | **Black-Scholes** | Analytic Pricing | BS call/put + full Greeks (Delta, Gamma, Vega, Theta, Rho) |
84
+ | **Implied Vol** | IV Solvers | Brent, Newton-Raphson, batch IV, volatility surface builder |
85
+ | **Heston** | Stochastic Vol | Semi-analytic (Gil-Pelaez CF), QE Monte Carlo, calibration |
86
+ | **American** | Early Exercise | Longstaff-Schwartz LSM, exercise boundary, Greeks |
87
+ | **Exotics** | Exotic Options | Asian (arithmetic/geometric), Digital (cash/asset), Barrier (8 types), Lookback, Cliquet, Rainbow |
88
+ | **Volatility** | Vol Surface Models | SABR (Hagan 2002), SVI (Gatheral 2004), calibration to market data |
89
+ | **Rates** | Interest Rate Models | Vasicek, CIR, Nelson-Siegel, yield curve bootstrapping |
90
+ | **FX** | FX Derivatives | Garman-Kohlhagen, FX Greeks, FX forwards, quanto options |
91
+ | **Credit** | Credit Risk | Merton structural model, CDS pricing, hazard rates, survival probabilities |
92
+ | **Jump-Diffusion** | Jump Models | Merton jump-diffusion, Kou double-exponential |
93
+ | **Local Vol** | Local Volatility | Dupire local vol, local vol Monte Carlo |
94
+ | **IR Derivatives** | Rate Products | Black-76 caps/floors, swaptions, swap rates, swaption parity |
95
+ | **Variance Reduction** | MC Efficiency | Antithetic, control variate, QMC (Sobol), importance sampling, stratified |
96
+ | **Risk** | Risk Metrics | VaR (parametric/historical/MC), CVaR, scenario analysis, portfolio Greeks |
97
+ | **Backtesting** | Strategy Testing | Backtesting engine, strategy framework, performance metrics (Sharpe, Sortino, max drawdown) |
98
+ | **TT Compression** | Tensor Trains | TT-SVD, TT-cross, rounding, arithmetic, surrogate pricing |
99
+ | **Basket Options** | Multi-Asset | Correlated GBM Monte Carlo, analytic moment-matching (Gentle 1993) |
100
+ | **Visualization** | Plots | Pricing surfaces, Greek surfaces, TT-rank charts |
101
+ | **Data** | Market Data | Yahoo Finance integration, historical prices, options chains |
102
+ | **CLI** | Command Line | `python -m tensorquantlib` — info, price, greeks, demo |
103
+
104
+ ---
105
+
106
+ ## Installation
107
+
108
+ ### pip install (recommended)
109
+
110
+ ```bash
111
+ pip install git+https://github.com/raswanthmalai19/TensorQuantLib.git
112
+ ```
113
+
114
+ ### With optional dependencies
115
+
116
+ ```bash
117
+ # Visualization support
118
+ pip install "git+https://github.com/raswanthmalai19/TensorQuantLib.git#egg=tensorquantlib[viz]"
119
+
120
+ # Market data support
121
+ pip install "git+https://github.com/raswanthmalai19/TensorQuantLib.git#egg=tensorquantlib[data]"
122
+
123
+ # Everything
124
+ pip install "git+https://github.com/raswanthmalai19/TensorQuantLib.git#egg=tensorquantlib[all]"
125
+ ```
126
+
127
+ ### Clone & install (development)
128
+
129
+ ```bash
130
+ git clone https://github.com/raswanthmalai19/TensorQuantLib.git
131
+ cd TensorQuantLib
132
+ pip install -e ".[dev]"
133
+ python -m pytest tests/ -q # 588 passed
134
+ ```
135
+
136
+ ---
137
+
138
+ ## Performance at a Glance
139
+
140
+ > Measured on Apple M1. Numbers scale linearly on multi-core servers.
141
+
142
+ | Workflow | Latency | Notes |
143
+ |---|---|---|
144
+ | `black_scholes` / `bs_greeks` | **< 5 µs** | Analytic; production vanilla book default |
145
+ | `barrier_price` | **< 5 µs** | Rubinstein-Reiner closed form |
146
+ | `garman_kohlhagen` | **< 5 µs** | FX vanilla |
147
+ | `vasicek_bond_price` | **< 1 µs** | Closed-form A(T)/B(T) |
148
+ | `implied_vol` | **< 1 ms** | Brent solver |
149
+ | `heston_price` (CF) | **~1 ms** | 100-pt Gaussian quadrature |
150
+ | `TTSurrogate.evaluate` 3D | **1.5 µs** | After one-time 2 ms build |
151
+ | `TTSurrogate.evaluate` 5D | **~5 µs** | 42× memory compression vs full grid |
152
+ | `heston_price_mc` | 200–500 ms | Validation only; use CF for live pricing |
153
+ | `HestonCalibrator.fit` | 5–15 s default → **< 0.5 s** optimised | See [Performance Guide](docs/performance.rst) |
154
+
155
+ **Rule of thumb**: for anything that needs a price in a hot loop, use the analytic
156
+ or CF pricer. Build a `TTSurrogate` once at startup to replace any MC pricer with
157
+ µs-latency evaluation. See the full
158
+ [Performance & Production Guide](docs/performance.rst) for tuning knobs,
159
+ parallel calibration, memory profiling, and the production checklist.
160
+
161
+ ---
162
+
163
+ ## Quick Start
164
+
165
+ ### Black-Scholes with Autodiff Greeks
166
+
167
+ ```python
168
+ from tensorquantlib import Tensor, bs_price_tensor
169
+ import numpy as np
170
+
171
+ S = Tensor(np.array([100.0]), requires_grad=True)
172
+ price = bs_price_tensor(S, K=100, T=1.0, r=0.05, sigma=0.2)
173
+ price.backward()
174
+
175
+ print(f"Price: {price.item():.4f}") # 10.4506
176
+ print(f"Delta: {S.grad[0]:.4f}") # 0.6368
177
+ ```
178
+
179
+ ### Heston Stochastic Volatility
180
+
181
+ ```python
182
+ from tensorquantlib import HestonParams, heston_price, heston_price_mc
183
+
184
+ params = HestonParams(kappa=2.0, theta=0.04, xi=0.3, rho=-0.7, v0=0.04)
185
+
186
+ # Semi-analytic (characteristic function)
187
+ price = heston_price(S=100, K=100, T=1.0, r=0.05, params=params)
188
+
189
+ # Monte Carlo with QE scheme
190
+ mc_price, mc_se = heston_price_mc(
191
+ S=100, K=100, T=1.0, r=0.05, params=params,
192
+ n_paths=100_000, scheme='qe', return_stderr=True,
193
+ )
194
+ ```
195
+
196
+ ### American Options (Longstaff-Schwartz)
197
+
198
+ ```python
199
+ from tensorquantlib import american_option_lsm
200
+
201
+ price, se = american_option_lsm(
202
+ S=100, K=100, T=1.0, r=0.05, sigma=0.2,
203
+ option_type='put', n_paths=100_000, n_steps=100,
204
+ )
205
+ ```
206
+
207
+ ### Implied Volatility
208
+
209
+ ```python
210
+ from tensorquantlib import implied_vol, iv_surface
211
+ import numpy as np
212
+
213
+ iv = implied_vol(market_price=10.45, S=100, K=100, T=1.0, r=0.05)
214
+ # iv ≈ 0.20
215
+
216
+ # Build a full IV surface
217
+ strikes = np.linspace(80, 120, 9)
218
+ expiries = np.array([0.25, 0.5, 1.0])
219
+ surface = iv_surface(S=100, r=0.05, sigma=0.2, strikes=strikes, expiries=expiries)
220
+ ```
221
+
222
+ ### Exotic Options
223
+
224
+ ```python
225
+ from tensorquantlib import asian_price_mc, barrier_price, digital_price
226
+
227
+ # Arithmetic Asian call
228
+ asian = asian_price_mc(S=100, K=100, T=1.0, r=0.05, sigma=0.2)
229
+
230
+ # Cash-or-nothing digital
231
+ digital = digital_price(S=100, K=100, T=1.0, r=0.05, sigma=0.2)
232
+
233
+ # Down-and-out barrier call
234
+ barrier = barrier_price(
235
+ S=100, K=100, T=1.0, r=0.05, sigma=0.2,
236
+ barrier=90, barrier_type='down-and-out',
237
+ )
238
+ ```
239
+
240
+ ### Volatility Surface Models (SABR & SVI)
241
+
242
+ ```python
243
+ from tensorquantlib import sabr_implied_vol, svi_implied_vol
244
+ import numpy as np
245
+
246
+ # SABR implied volatility
247
+ vol = sabr_implied_vol(F=100, K=100, T=1.0, alpha=0.3, beta=0.5, rho=-0.3, nu=0.4)
248
+
249
+ # SVI parameterization (k = log-moneyness ln(K/F))
250
+ k = np.linspace(-0.2, 0.2, 50) # log-moneyness grid
251
+ vols = svi_implied_vol(k, T=1.0, a=0.04, b=0.1, rho=-0.3, m=0.0, sigma=0.1)
252
+ ```
253
+
254
+ ### Interest Rate Models
255
+
256
+ ```python
257
+ from tensorquantlib import vasicek_bond_price, cir_bond_price, nelson_siegel
258
+ import numpy as np
259
+
260
+ # Vasicek zero-coupon bond
261
+ bond = vasicek_bond_price(r0=0.05, kappa=0.3, theta=0.05, sigma=0.02, T=5.0)
262
+
263
+ # CIR bond price
264
+ cir = cir_bond_price(r0=0.05, kappa=0.5, theta=0.05, sigma=0.1, T=5.0)
265
+
266
+ # Nelson-Siegel yield curve
267
+ maturities = np.array([0.25, 0.5, 1, 2, 5, 10, 30])
268
+ yields = nelson_siegel(maturities, beta0=0.05, beta1=-0.02, beta2=0.03, tau=1.5)
269
+ ```
270
+
271
+ ### FX Options
272
+
273
+ ```python
274
+ from tensorquantlib import garman_kohlhagen, fx_forward
275
+
276
+ # Garman-Kohlhagen European FX option
277
+ price = garman_kohlhagen(S=1.25, K=1.30, T=0.5, r_d=0.05, r_f=0.02, sigma=0.1)
278
+
279
+ # FX forward rate
280
+ fwd = fx_forward(S=1.25, r_d=0.05, r_f=0.02, T=1.0)
281
+ ```
282
+
283
+ ### Credit Risk
284
+
285
+ ```python
286
+ from tensorquantlib import merton_default_prob, cds_spread
287
+
288
+ # Merton structural model — probability of default
289
+ pd = merton_default_prob(V=100, D=80, T=1.0, r=0.05, sigma_V=0.25)
290
+
291
+ # CDS spread (from constant hazard rate)
292
+ spread = cds_spread(hazard_rate=0.02, T=5.0, recovery=0.4, r=0.03)
293
+ ```
294
+
295
+ ### Second-Order Greeks (Autodiff)
296
+
297
+ ```python
298
+ from tensorquantlib import second_order_greeks, bs_price_tensor
299
+
300
+ result = second_order_greeks(
301
+ price_fn=bs_price_tensor,
302
+ S=100, K=100, T=1.0, r=0.05, sigma=0.2,
303
+ )
304
+ # result = {'gamma': ..., 'vanna': ..., 'volga': ...}
305
+ ```
306
+
307
+ ### Risk Metrics
308
+
309
+ ```python
310
+ from tensorquantlib import var_parametric, cvar
311
+ import numpy as np
312
+
313
+ returns = np.random.normal(0.0005, 0.02, 252)
314
+ var_95 = var_parametric(returns, confidence=0.95)
315
+ es_95 = cvar(returns, confidence=0.95)
316
+ ```
317
+
318
+ ### TT Compression Surrogate
319
+
320
+ ```python
321
+ from tensorquantlib import TTSurrogate
322
+
323
+ surr = TTSurrogate.from_basket_analytic(
324
+ S0_ranges=[(80, 120)] * 3,
325
+ K=100, T=1.0, r=0.05,
326
+ sigma=[0.20, 0.25, 0.30],
327
+ weights=[1/3, 1/3, 1/3],
328
+ n_points=30, eps=1e-4,
329
+ )
330
+
331
+ surr.print_summary()
332
+ price = surr.evaluate([100.0, 105.0, 95.0])
333
+ greeks = surr.greeks([100.0, 105.0, 95.0])
334
+ ```
335
+
336
+ ### CLI
337
+
338
+ ```bash
339
+ python -m tensorquantlib info # Library info
340
+ python -m tensorquantlib price # Price an option
341
+ python -m tensorquantlib greeks # Compute Greeks
342
+ python -m tensorquantlib demo # Run quick demo
343
+ ```
344
+
345
+ ---
346
+
347
+ ## Benchmark Results
348
+
349
+ ### TT Compression — Memory Scaling
350
+
351
+ | Assets | Full Grid | TT Size | Compression Ratio |
352
+ |--------|-----------|---------|-------------------|
353
+ | 2 | 0.002 MB | 3.3 KB | 1x |
354
+ | 3 | 0.026 MB | 28 KB | 1x |
355
+ | 4 | 0.39 MB | 91 KB | **4x** |
356
+ | **5** | **5.79 MB** | **142 KB** | **42x** |
357
+
358
+ Full numbers: [`benchmarks/RESULTS.md`](benchmarks/RESULTS.md)
359
+
360
+ ---
361
+
362
+ ## Architecture
363
+
364
+ ```
365
+ tensorquantlib/
366
+ ├── core/
367
+ │ ├── tensor.py # Tensor class — reverse-mode autograd, 23+ ops
368
+ │ ├── second_order.py # Hessians, HVPs, Gamma/Vanna/Volga autodiff
369
+ │ └── ops.py # Public re-exports
370
+ ├── finance/
371
+ │ ├── black_scholes.py # Analytic + Tensor BS pricing, full Greeks
372
+ │ ├── implied_vol.py # Brent/Newton IV, batch, surface builder
373
+ │ ├── heston.py # Semi-analytic CF, QE MC, calibration, Greeks
374
+ │ ├── american.py # Longstaff-Schwartz LSM, grid, Greeks
375
+ │ ├── exotics.py # Asian, Digital, Barrier, Lookback, Cliquet, Rainbow
376
+ │ ├── volatility.py # SABR & SVI vol surface models + calibration
377
+ │ ├── rates.py # Vasicek, CIR, Nelson-Siegel, yield bootstrapping
378
+ │ ├── fx.py # Garman-Kohlhagen FX options, forwards, quanto
379
+ │ ├── credit.py # Merton structural model, CDS pricing
380
+ │ ├── jump_diffusion.py # Merton & Kou jump-diffusion
381
+ │ ├── local_vol.py # Dupire local vol, local vol MC
382
+ │ ├── ir_derivatives.py # Black-76 caps/floors, swaptions
383
+ │ ├── variance_reduction.py # Antithetic, CV, QMC, IS, stratified
384
+ │ ├── risk.py # VaR, CVaR, scenario analysis, portfolio risk
385
+ │ ├── greeks.py # Autograd-based Greeks
386
+ │ └── basket.py # MC basket pricing, analytic grid construction
387
+ ├── tt/
388
+ │ ├── decompose.py # TT-SVD, TT-cross, TT-rounding
389
+ │ ├── ops.py # tt_eval, tt_to_full, arithmetic (12 ops)
390
+ │ ├── surrogate.py # TTSurrogate end-to-end pipeline
391
+ │ └── pricing.py # Pre-built TT surrogates (Heston, American, exotic)
392
+ ├── backtest/
393
+ │ ├── engine.py # Backtesting engine with portfolio tracking
394
+ │ ├── strategy.py # Strategy base class + built-in strategies
395
+ │ └── metrics.py # Sharpe, Sortino, max drawdown, Calmar, etc.
396
+ ├── data/
397
+ │ └── market.py # Yahoo Finance integration, options chains
398
+ ├── viz/
399
+ │ └── plots.py # Pricing surfaces, Greek surfaces, rank plots
400
+ ├── utils/
401
+ │ └── validation.py # Numerical gradient checking
402
+ └── __main__.py # CLI entry point
403
+ ```
404
+
405
+ ---
406
+
407
+ ## Test Coverage
408
+
409
+ | Module | Tests | Description |
410
+ |--------|-------|-------------|
411
+ | Core autograd engine | 73 | Forward/backward pass, all 23+ ops, broadcasting |
412
+ | Second-order autodiff | 12 | Hessian, HVP, mixed partials, second-order Greeks |
413
+ | Black-Scholes + Greeks | 32 | Pricing, put-call parity, all 5 Greeks |
414
+ | Implied volatility | 18 | Brent, Newton, batch, surface, edge cases |
415
+ | Heston model | 22 | Semi-analytic, MC (QE/Euler), calibration, Greeks |
416
+ | American options | 15 | LSM, grid, Greeks, put-call comparison |
417
+ | Exotic options | 28 | Asian, digital, barrier, lookback, cliquet, rainbow |
418
+ | Volatility models | 14 | SABR, SVI, calibration, surface construction |
419
+ | Interest rates | 20 | Vasicek, CIR, Nelson-Siegel, bootstrapping |
420
+ | FX options | 12 | Garman-Kohlhagen, Greeks, forwards, quanto |
421
+ | Credit risk | 14 | Merton, CDS, hazard rates, survival probabilities |
422
+ | Jump-diffusion | 10 | Merton, Kou, analytic vs MC |
423
+ | Local volatility | 8 | Dupire, local vol MC |
424
+ | IR derivatives | 14 | Caps, floors, swaptions, swap rate |
425
+ | Variance reduction | 20 | Antithetic, CV, QMC, IS, stratified |
426
+ | Risk metrics | 18 | VaR (3 methods), CVaR, scenarios, portfolio |
427
+ | Backtesting | 12 | Engine, strategies, metrics |
428
+ | TT decomposition & ops | 34 | SVD, cross, rounding, arithmetic (12 ops) |
429
+ | TT surrogate & pricing | 20 | Surrogate construction, evaluation, Greeks |
430
+ | Visualization | 21 | Pricing surfaces, Greek surfaces, rank plots |
431
+ | Integration & edge cases | 57 | Cross-module, boundary conditions, numerics |
432
+ | **Total** | **588** | **98% line coverage** |
433
+
434
+ ```bash
435
+ python -m pytest tests/ -v
436
+ python -m pytest tests/ --cov=tensorquantlib --cov-report=term-missing
437
+ ```
438
+
439
+ ---
440
+
441
+ ## API Reference
442
+
443
+ 150+ public functions and classes exported from the top-level package:
444
+
445
+ ```python
446
+ from tensorquantlib import (
447
+ # Core autograd
448
+ Tensor,
449
+ tensor_sin, tensor_cos, tensor_tanh, tensor_abs,
450
+ tensor_clip, tensor_where, tensor_softmax,
451
+
452
+ # Second-order autodiff
453
+ hvp, hessian, hessian_diag, vhp, mixed_partial,
454
+ gamma_autograd, vanna_autograd, volga_autograd, second_order_greeks,
455
+
456
+ # Black-Scholes
457
+ bs_price_numpy, bs_price_tensor,
458
+ bs_delta, bs_gamma, bs_vega, bs_theta, bs_rho,
459
+ compute_greeks, compute_greeks_vectorized,
460
+
461
+ # Implied volatility
462
+ implied_vol, implied_vol_batch, implied_vol_nr, iv_surface,
463
+
464
+ # Heston
465
+ HestonParams, HestonCalibrator,
466
+ heston_price, heston_price_mc, heston_greeks,
467
+
468
+ # American options
469
+ american_option_lsm, american_option_grid, american_greeks,
470
+
471
+ # Exotics
472
+ asian_price_mc, asian_geometric_price,
473
+ digital_price, digital_price_mc, digital_greeks,
474
+ barrier_price, barrier_price_mc,
475
+ lookback_fixed_analytic, lookback_floating_analytic, lookback_price_mc,
476
+ cliquet_price_mc, rainbow_price_mc,
477
+
478
+ # Volatility surface
479
+ sabr_implied_vol, sabr_calibrate,
480
+ svi_raw, svi_implied_vol, svi_calibrate, svi_surface,
481
+
482
+ # Interest rates
483
+ vasicek_bond_price, vasicek_yield, vasicek_option_price, vasicek_simulate,
484
+ cir_bond_price, cir_yield, cir_simulate, feller_condition,
485
+ nelson_siegel, nelson_siegel_calibrate, bootstrap_yield_curve,
486
+
487
+ # FX options
488
+ garman_kohlhagen, gk_greeks, fx_forward, quanto_option,
489
+
490
+ # Credit risk
491
+ merton_default_prob, merton_credit_spread,
492
+ survival_probability, hazard_rate_from_spread,
493
+ cds_spread, cds_price,
494
+
495
+ # Jump-diffusion
496
+ merton_jump_price, merton_jump_price_mc, kou_jump_price_mc,
497
+
498
+ # Local volatility
499
+ dupire_local_vol, local_vol_mc,
500
+
501
+ # IR derivatives (Black-76)
502
+ black76_caplet, black76_floorlet, cap_price, floor_price,
503
+ swap_rate, swaption_price, swaption_parity,
504
+
505
+ # Variance reduction
506
+ bs_price_antithetic, asian_price_cv, bs_price_qmc,
507
+ bs_price_importance, bs_price_stratified, compare_variance_reduction,
508
+
509
+ # Risk
510
+ PortfolioRisk, OptionPosition,
511
+ var_parametric, var_historical, var_mc, cvar,
512
+ scenario_analysis, greeks_portfolio,
513
+
514
+ # Basket
515
+ simulate_basket, build_pricing_grid, build_pricing_grid_analytic,
516
+
517
+ # TT compression
518
+ TTSurrogate,
519
+ tt_svd, tt_round, tt_cross,
520
+ tt_eval, tt_eval_batch, tt_to_full,
521
+ tt_ranks, tt_memory, tt_error, tt_compression_ratio,
522
+ tt_add, tt_scale, tt_hadamard, tt_dot, tt_frobenius_norm,
523
+
524
+ # TT-accelerated pricers
525
+ heston_surrogate, american_surrogate,
526
+ exotic_surrogate, jump_diffusion_surrogate,
527
+
528
+ # Visualization
529
+ plot_pricing_surface, plot_greeks_surface, plot_tt_ranks,
530
+ )
531
+ ```
532
+
533
+ ---
534
+
535
+ ## Dependencies
536
+
537
+ | Package | Version | Purpose |
538
+ |---------|---------|---------|
539
+ | `numpy` | >= 1.24 | Core numerics |
540
+ | `scipy` | >= 1.10 | Special functions, optimization, integration |
541
+ | `matplotlib` | >= 3.7 | Visualization (optional `[viz]`) |
542
+ | `yfinance` | >= 0.2 | Market data (optional `[data]`) |
543
+
544
+ ---
545
+
546
+ ## References
547
+
548
+ - Oseledets, I.V. (2011). *Tensor-Train Decomposition*. SIAM J. Sci. Comput. 33(5).
549
+ - Heston, S.L. (1993). *A Closed-Form Solution for Options with Stochastic Volatility*. RFS 6(2).
550
+ - Andersen, L.B.G. (2008). *Efficient Simulation of the Heston Stochastic Volatility Model*. J. Comp. Fin.
551
+ - Longstaff, F.A. & Schwartz, E.S. (2001). *Valuing American Options by Simulation*. RFS.
552
+ - Hagan, P.S. et al. (2002). *Managing Smile Risk*. Wilmott Magazine. (SABR model)
553
+ - Gatheral, J. (2004). *A Parsimonious Arbitrage-Free Implied Volatility Parameterization*. (SVI)
554
+ - Vasicek, O.A. (1977). *An Equilibrium Characterization of the Term Structure*. J. Fin. Econ.
555
+ - Cox, J.C., Ingersoll, J.E. & Ross, S.A. (1985). *A Theory of the Term Structure of Interest Rates*. Econometrica.
556
+ - Merton, R.C. (1974). *On the Pricing of Corporate Debt*. J. Finance.
557
+ - Garman, M.B. & Kohlhagen, S.W. (1983). *Foreign Currency Option Values*. J. Int. Money & Finance.
558
+ - Black, F. (1976). *The Pricing of Commodity Contracts*. J. Fin. Econ.
559
+ - Black, F. & Scholes, M. (1973). *The Pricing of Options and Corporate Liabilities*. J. Pol. Econ.
560
+ - Glasserman, P. (2003). *Monte Carlo Methods in Financial Engineering*. Springer.
561
+
562
+ ---
563
+
564
+ ## Contributing
565
+
566
+ See [`CONTRIBUTING.md`](CONTRIBUTING.md) for development setup, coding standards, and guidelines.
567
+
568
+ ---
569
+
570
+ ## License
571
+
572
+ MIT — see [`LICENSE`](LICENSE).
573
+
574
+ ---
575
+
576
+ ## Roadmap
577
+
578
+ - [x] Custom autograd engine (23+ differentiable ops)
579
+ - [x] Second-order autodiff (Hessian, HVP, Gamma/Vanna/Volga)
580
+ - [x] Black-Scholes pricing + full Greeks
581
+ - [x] TT-SVD compression + surrogate pricing
582
+ - [x] Heston stochastic volatility (analytic + MC + calibration)
583
+ - [x] American options (Longstaff-Schwartz LSM)
584
+ - [x] Exotic options (Asian, Digital, Barrier, Lookback, Cliquet, Rainbow)
585
+ - [x] Variance reduction techniques (5 methods + comparison)
586
+ - [x] Risk metrics (VaR, CVaR, scenario analysis)
587
+ - [x] Volatility surface models (SABR, SVI + calibration)
588
+ - [x] Interest rate models (Vasicek, CIR, Nelson-Siegel)
589
+ - [x] FX options (Garman-Kohlhagen, forwards, quanto)
590
+ - [x] Credit risk (Merton structural, CDS pricing)
591
+ - [x] Jump-diffusion models (Merton, Kou)
592
+ - [x] Local volatility (Dupire, MC)
593
+ - [x] IR derivatives (Black-76 caps/floors, swaptions)
594
+ - [x] Market data integration (Yahoo Finance)
595
+ - [x] Backtesting framework (engine, strategies, metrics)
596
+ - [x] CLI interface
597
+ - [ ] PyPI release
598
+ - [ ] GPU acceleration via CuPy
599
+
600
+ ---
601
+
602
+ *Built from scratch — no ML framework dependencies. Custom autograd + custom TT-SVD + custom stochastic models.*