{"id":21042592,"url":"https://github.com/jialuechen/torchquant","last_synced_at":"2025-12-14T04:25:14.301Z","repository":{"id":49848629,"uuid":"445039511","full_name":"jialuechen/torchquant","owner":"jialuechen","description":"PyTorch Extension Library for Quantitative Finance","archived":false,"fork":false,"pushed_at":"2025-01-26T04:13:50.000Z","size":2786,"stargazers_count":155,"open_issues_count":6,"forks_count":22,"subscribers_count":8,"default_branch":"main","last_synced_at":"2025-03-29T05:03:12.577Z","etag":null,"topics":["automatic-differentiation","deep-learning","derivatives-pricing","malliavin-calculus","numerical-methods","optimal-transport","pytorch","quantitative-finance","quantlib","risk-management"],"latest_commit_sha":null,"homepage":"https://jialuechen.github.io/torchquant/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jialuechen.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-01-06T04:26:18.000Z","updated_at":"2025-03-25T14:22:35.000Z","dependencies_parsed_at":"2023-11-15T21:29:31.884Z","dependency_job_id":"6f40b8d7-135e-46aa-89e1-e8751c3440b0","html_url":"https://github.com/jialuechen/torchquant","commit_stats":{"total_commits":36,"total_committers":2,"mean_commits":18.0,"dds":0.02777777777777779,"last_synced_commit":"6d61afa061f10a08f62a275055b3c3c565643dec"},"previous_names":["jialuechen/torchquant","jialuechen/quantorch"],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jialuechen%2Ftorchquant","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jialuechen%2Ftorchquant/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jialuechen%2Ftorchquant/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jialuechen%2Ftorchquant/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jialuechen","download_url":"https://codeload.github.com/jialuechen/torchquant/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247294537,"owners_count":20915340,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["automatic-differentiation","deep-learning","derivatives-pricing","malliavin-calculus","numerical-methods","optimal-transport","pytorch","quantitative-finance","quantlib","risk-management"],"created_at":"2024-11-19T14:08:03.993Z","updated_at":"2025-12-14T04:25:14.217Z","avatar_url":"https://github.com/jialuechen.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=center\u003e\n\u003cimg src=\"assets/torchquant.png\" width=\"40%\" loc\u003e\n\n[![PyPI version](https://badge.fury.io/py/torchquantlib.svg)](https://badge.fury.io/py/torchquantlib)\n[![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)\n![Python versions](https://img.shields.io/badge/python-3.7%2B-green)\n![PyTorch version](https://img.shields.io/badge/pytorch-2.4.0%2B-green)\n![Downloads](https://img.shields.io/pypi/dm/torchquantlib)\n[![Documentation Status](https://readthedocs.org/projects/torchquant/badge/?version=stable)](https://torchquant.readthedocs.io/en/stable/?badge=stable)\n\n\u003c/div\u003e\n\n**TorchQuant** is a comprehensive high-performance quantitative finance library built on top of PyTorch's automatic differentiation and GPU acceleration. It is a differentiable pricing framework with high-accuracy numerical methods. It provides comprehensive tools for derivatives pricing, risk management, and stochastic model calibration.\n\n## Features\n\n- **Asset Pricing**:\n  - Option pricing models including BSM, Heston, binomial tree, and Monte Carlo simulations.\n  - Bond pricing models including callable, putable, and convertible bonds.\n  - Advanced options support for American, Bermudan, Asian, barrier and look-back options.\n  - Implied volatility calculation using \"Let's be rational\" algorithm.\n  - Futures and currency pricing.\n\n- **Risk Management**:\n  - Greeks calculation utilizing Malliavin calculus.\n  - Scenario analysis and stress testing.\n  - Market risk measures such as VaR and Expected Shortfall.\n  - Credit risk models including structural and reduced form models.\n  - Valuation adjustments (CVA, DVA, MVA, FVA).\n\n- **Neural Network-based Model Calibration**:\n  - Calibration for stochastic models like Heston, Vasicek, SABR, and more.\n  - Local volatility models including Dupire.\n  - Optimal Transport for model calibration\n \n- **Sequence Methods**:\n  - Seq2Seq PDE solvers\n\n## Installation\n\nYou can install torchquant via pip:\n\n```bash\npip install --upgrade torchquantlib\n```\n\n## Usage (check out the examples folder for more information)\n\n### Exotic Options\n\n#### American Option\n\n```python\nimport torch\nfrom torchquantlib.core.asset_pricing.option.american_option import american_option  # 修正路径\n\nspot = torch.tensor(100.0)\nstrike = torch.tensor(105.0)\nexpiry = torch.tensor(1.0)\nvolatility = torch.tensor(0.2)\nrate = torch.tensor(0.05)\nsteps = 100\n\nprice = american_option('call', spot, strike, expiry, volatility, rate, steps)\nprint(f'American Option Price: {price.item()}')\n```\n\n#### Bermudan Option\n\n```python\nimport torch\nfrom torchquantlib.core.asset_pricing.option.bermudan_option import bermudan_option  # 修正路径\n\nspot = torch.tensor(100.0)\nstrike = torch.tensor(105.0)\nexpiry = torch.tensor(1.0)\nvolatility = torch.tensor(0.2)\nrate = torch.tensor(0.05)\nsteps = 100\nexercise_dates = torch.tensor([30, 60, 90])\n\nprice = bermudan_option('call', spot, strike, expiry, volatility, rate, steps, exercise_dates)\nprint(f'Bermudan Option Price: {price.item()}')\n```\n\n#### Asian Option\n\n```python\nimport torch\nfrom torchquantlib.core.asset_pricing.option.asian_option import asian_option  # 修正路径\n\nspot = torch.tensor(100.0)\nstrike = torch.tensor(105.0)\nexpiry = torch.tensor(1.0)\nvolatility = torch.tensor(0.2)\nrate = torch.tensor(0.05)\nsteps = 100\n\nprice = asian_option('call', spot, strike, expiry, volatility, rate, steps)\nprint(f'Asian Option Price: {price.item()}')\n```\n\n### Greeks Calculation using Malliavin Calculus\n\n```python\nimport torch\nfrom torchquantlib.core.risk.greeks.malliavin import malliavin_greek\n\noption_price = torch.tensor(10.0)\nunderlying_price = torch.tensor(100.0)\nvolatility = torch.tensor(0.2)\nexpiry = torch.tensor(1.0)\n\ngreek = malliavin_greek(option_price, underlying_price, volatility, expiry)\nprint(f'Malliavin Greek: {greek.item()}')\n```\n\n### Model Calibration by Optimal Transport\n\n#### Heston Model Calibration\n\n```python\n# calibrate_heston.py\n\nimport numpy as np\nimport torch\nfrom torchquantlib.calibration import model_calibrator\nfrom torchquantlib.models.stochastic_volatility.heston import Heston\n\n# Generate synthetic observed data using true Heston parameters\nN_observed = 1000\nS0 = 100.0\nT = 1.0\ntrue_params = {\n    'kappa': 2.0,\n    'theta': 0.04,\n    'sigma_v': 0.3,\n    'rho': -0.7,\n    'v0': 0.04,\n    'mu': 0.05\n}\n\nnp.random.seed(42)\ntorch.manual_seed(42)\nheston_true = Heston(**true_params)\nS_observed = heston_true.simulate(S0=S0, T=T, N=N_observed)\n\n# Initialize the Heston model with initial guesses\nheston_model = Heston(\n    kappa_init=1.0,\n    theta_init=0.02,\n    sigma_v_init=0.2,\n    rho_init=-0.5,\n    v0_init=0.02,\n    mu_init=0.0\n)\n\n# Set up the calibrator\ncalibrator = model_calibrator(\n    model=heston_model,\n    observed_data=S_observed.detach().cpu().numpy(),  # Convert tensor to numpy array\n    S0=S0,\n    T=T,\n    lr=0.01\n)\n\n# Calibrate the model\ncalibrator.calibrate(num_epochs=1000, steps=100, verbose=True)\n\n# Get the calibrated parameters\ncalibrated_params = calibrator.get_calibrated_params()\nprint(\"Calibrated Parameters:\")\nfor name, value in calibrated_params.items():\n    print(f\"{name}: {value:.6f}\")\n```\n\n## Seq2Seq PDE Solver\n```python\nfrom torchquantlib.utils import Seq2SeqPDESolver\n# Define model parameters\ninput_dim = 1      # Adjust based on your input features\nhidden_dim = 64    # Number of features in the hidden state\noutput_dim = 1     # Adjust based on your output features\nnum_layers = 2     # Number of stacked LSTM layers\n\n# Initialize the model, loss function, and optimizer\nmodel = Seq2SeqPDESolver(input_dim, hidden_dim, output_dim, num_layers)\ncriterion = nn.MSELoss()\noptimizer = optim.Adam(model.parameters(), lr=0.001)\n\n# Training loop (simplified)\nnum_epochs = 100\nfor epoch in range(num_epochs):\n    model.train()\n    optimizer.zero_grad()\n    output = model(src, trg)\n    loss = criterion(output, trg)\n    loss.backward()\n    optimizer.step()\n    \n    print(f'Epoch {epoch+1}/{num_epochs}, Loss: {loss.item():.4f}')\n```\n\n## Credit Risk Measurement\n```python\nimport torch\nfrom torchquantlib.core.risk.credit_risk.structural_model import merton_model\nfrom torchquantlib.core.risk.credit_risk.reduced_form_model import reduced_form_model\n\nasset_value = torch.tensor(100.0)\ndebt = torch.tensor(80.0)\nvolatility = torch.tensor(0.2)\nrate = torch.tensor(0.05)\nexpiry = torch.tensor(1.0)\n\n# Merton Model\nequity_value = merton_model(asset_value, debt, volatility, rate, expiry)\nprint(f'Equity Value (Merton Model): {equity_value.item()}')\n\nlambda_0 = torch.tensor(0.02)\ndefault_intensity = torch.tensor(0.05)\nrecovery_rate = torch.tensor(0.4)\ntime = torch.tensor(1.0)\n\n# Reduced Form Model\nexpected_loss = reduced_form_model(lambda_0, default_intensity, recovery_rate, time)\nprint(f'Expected Loss (Reduced Form Model): {expected_loss.item()}')\n```\n\n## Roadmap\n\n\n### Q2 2025\n- Add support for more asset classes such as commodities and real estate.\n- Enhance the calibration module to support a broader range of models and optimization techniques.\n\n## Development\n\nTo contribute to TorchQuant, clone the repository and install the required dependencies:\n\n```bash\ngit clone https://github.com/jialuechen/torchquant.git\ncd torchquant\npip install -r requirements.txt\n```\n\nRun the tests to ensure everything is working:\n\n```bash\npytest\n```\n\n## License\n\nThis project is licensed under the Apache License 2.0. See the [LICENSE](LICENSE) file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjialuechen%2Ftorchquant","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjialuechen%2Ftorchquant","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjialuechen%2Ftorchquant/lists"}