• Stars
    star
    249
  • Rank 162,987 (Top 4 %)
  • Language
    Python
  • License
    MIT License
  • Created over 3 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PyTorch-based framework for Deep Hedging

PFHedge: Deep Hedging in PyTorch

python pypi CI codecov downloads code style: black pytorch

PFHedge is a PyTorch-based framework for Deep Hedging.

What is Deep Hedging?

Deep Hedging is a deep learning-based framework to hedge financial derivatives.

Hedging financial derivatives in the presence of market frictions (e.g., transaction cost) is a challenging task. In the absence of market frictions, the perfect hedge is accessible based on the Black-Scholes model. The real market, in contrast, always involves frictions and thereby makes hedging optimization much more challenging. Since the analytic formulas (such as the Black-Scholes formula) are no longer available in such a market, it may be necessary to adjust model-based Greeks to hedge and price derivatives based on experiences.

Deep Hedging is a ground-breaking framework to optimize such hedging operations. In this framework, a neural network is trained to hedge derivatives so that it minimizes a proper risk measure. By virtue of the high representability of a neural network and modern optimization algorithms, one can expect to achieve the optimal hedge by training a neural network. Indeed, the experiments in BΓΌhler et al. 18 and Imaki et al. 21 show high feasibility and scalability of Deep Hedging algorithms for options under transaction costs.

Global investment banks are looking to rethink the Greeks-based hedging with Deep Hedging and slash considerable amount of hedging costs. This could be the "game-changer" in the trillion-dollar industry of derivatives.

PFHedge enables you to experience this revolutionary framework on your own. You can try, tweak, and delve into Deep Hedging algorithms using PyTorch. We hope PFHedge accelerates the research and development of Deep Hedging.

Features

Imperative Experiences

  • PFHedge is designed to be intuitive and imperative to streamline your research on Deep Hedging.
  • You can quickly build a Hedger and then fit and price derivatives right away.
  • You can easily tweak your model, risk measure, derivative, optimizer, and other setups on the fly.

Seamless Integration with PyTorch

  • PFHedge is built to be deeply integrated into PyTorch.
  • Your Deep-Hedger can be built as a Module and trained by any Optimizer.
  • You can use GPUs to boost your hedging optimization (See below).

Effortless Extensions

  • You can build new hedging models, derivatives, and features with little glue code.
  • You can build new hedging models by just subclassing Module.
  • You can quickly try out your own stochastic processes, derivatives, and input features.

Batteries Included

Install

pip install pfhedge

How to Use

Open In Colab

Prepare a Derivative to Hedge

Financial instruments are provided in pfhedge.instruments and classified into two types:

  • Primary instruments: A primary instrument is a basic financial instrument that is traded on a market, and therefore their prices are accessible as the market prices. Examples include stocks, bonds, commodities, and currencies.
  • Derivative instruments: A derivative is a financial instrument whose payoff is contingent on a primary instrument. An (over-the-counter) derivative is not traded on the market, and therefore the price is not directly accessible. Examples include EuropeanOption, LookbackOption, VarianceSwap, and so forth.

We consider a BrownianStock, which is a stock following the geometric Brownian motion, and a EuropeanOption which is contingent on it. We assume that the stock has a transaction cost of 1 basis point.

from pfhedge.instruments import BrownianStock
from pfhedge.instruments import EuropeanOption

stock = BrownianStock(cost=1e-4)
derivative = EuropeanOption(stock)

derivative
# EuropeanOption(
#   strike=1., maturity=0.0800
#   (underlier): BrownianStock(sigma=0.2000, cost=1.0000e-04, dt=0.0040)
# )

Create Your Hedger

A Hedger in Deep Hedging is basically characterized by three elements:

We here use a multi-layer perceptron as our model.

from pfhedge.nn import Hedger
from pfhedge.nn import MultiLayerPerceptron

model = MultiLayerPerceptron()
hedger = Hedger(model, inputs=["log_moneyness", "expiry_time", "volatility", "prev_hedge"])

The hedger is also a Module.

hedger
# Hedger(
#   inputs=['log_moneyness', 'expiry_time', 'volatility', 'prev_hedge']
#   (model): MultiLayerPerceptron(
#     (0): LazyLinear(in_features=0, out_features=32, bias=True)
#     (1): ReLU()
#     (2): Linear(in_features=32, out_features=32, bias=True)
#     (3): ReLU()
#     (4): Linear(in_features=32, out_features=32, bias=True)
#     (5): ReLU()
#     (6): Linear(in_features=32, out_features=32, bias=True)
#     (7): ReLU()
#     (8): Linear(in_features=32, out_features=1, bias=True)
#     (9): Identity()
#   )
#   (criterion): EntropicRiskMeasure()
# )

Fit and Price

Now we train our hedger so that it minimizes the risk measure through hedging.

The hedger is trained as follows. In each epoch, we generate Monte Carlo paths of the asset prices and let the hedger hedge the derivative by trading the stock. The hedger's risk measure (EntropicRiskMeasure() in our case) is computed from the resulting profit and loss distribution, and the parameters in the model are updated.

hedger.fit(derivative, n_epochs=200)

Once we have trained the hedger, we can evaluate the derivative price as utility indifference price (For details, see Deep Hedging and references therein).

price = hedger.price(derivative)

More Examples

Use GPU

To employ the desired device and/or dtype in fitting and pricing, use to method.

dtype = torch.float64
device = torch.device("cuda:0")

derivative = EuropeanOption(BrownianStock()).to(dtype, device)
hedger = Hedger(...).to(dtype, device)

Black-Scholes' Delta-Hedging Strategy

In this strategy, a hedger incessantly rebalances their portfolio and keeps it delta-neutral. The hedge-ratio at each time step is given by the Black-Scholes' delta.

This strategy is the optimal one in the absence of cost. On the other hand, this strategy transacts too frequently and consumes too much transaction cost.

from pfhedge.nn import BlackScholes
from pfhedge.nn import Hedger

derivative = EuropeanOption(BrownianStock(cost=1e-4))

model = BlackScholes(derivative)
hedger = Hedger(model, inputs=model.inputs())

Whalley-Wilmott's Asymptotically Optimal Strategy for Small Costs

This strategy is proposed by Whalley et al. 1997 and is proved to be optimal for asymptotically small transaction costs.

In this strategy, a hedger always maintains their hedge ratio in the range (called no-transaction band) while they never transact inside this range. This strategy is supposed to be optimal in the limit of small transaction costs, while suboptimal for large transaction costs.

from pfhedge.nn import Hedger
from pfhedge.nn import WhalleyWilmott

derivative = EuropeanOption(BrownianStock(cost=1e-3))

model = WhalleyWilmott(derivative)
hedger = Hedger(model, inputs=model.inputs())

Your Own Module

You can employ any Module you build as a hedging model. The input/output shapes is (N, H_in) -> (N, 1), where N is the number of Monte Carlo paths of assets and H_in is the number of input features.

Here we show an example of No-Transaction Band Network, which is proposed in Imaki et al. 21.

import torch
import torch.nn.functional as fn
from torch import Tensor
from torch.nn import Module

from pfhedge.nn import BlackScholes
from pfhedge.nn import Clamp
from pfhedge.nn import Hedger
from pfhedge.nn import MultiLayerPerceptron


class NoTransactionBandNet(Module):
    def __init__(self, derivative):
        super().__init__()

        self.delta = BlackScholes(derivative)
        self.mlp = MultiLayerPerceptron(out_features=2)
        self.clamp = Clamp()

    def inputs(self):
        return self.delta.inputs() + ["prev_hedge"]

    def forward(self, input: Tensor) -> Tensor:
        prev_hedge = input[..., [-1]]

        delta = self.delta(input[..., :-1])
        width = self.mlp(input[..., :-1])

        min = delta - fn.leaky_relu(width[..., [0]])
        max = delta + fn.leaky_relu(width[..., [1]])

        return self.clamp(prev_hedge, min=min, max=max)


model = NoTransactionBandNet(derivative)
hedger = Hedger(model, inputs=model.inputs())

Autogreek

A module pfhedge.autogreek provides functions implementing automatic evaluation of greeks using automatic differentiation.

import pfhedge.autogreek as autogreek
from pfhedge.instruments import BrownianStock
from pfhedge.instruments import EuropeanOption
from pfhedge.nn import Hedger
from pfhedge.nn import WhalleyWilmott

derivative = EuropeanOption(BrownianStock(cost=1e-4))

model = WhalleyWilmott(derivative)
hedger = Hedger(model, inputs=model.inputs())

def pricer(spot):
    return hedger.price(derivative, init_state=(spot,), enable_grad=True)

delta = autogreek.delta(pricer, spot=torch.tensor(1.0))
# tensor(0.5092)
gamma = autogreek.gamma(pricer, spot=torch.tensor(1.0))
# tensor(0.0885)

Contribution

Any contributions to PFHedge are more than welcome!

  • GitHub Issues: Bug reports, feature requests, and questions.
  • Pull Requests: Bug-fixes, feature implementations, and documentation updates.

Please take a look at CONTRIBUTING.md before creating a pull request.

This project is owned by Preferred Networks and maintained by Shota Imaki and Masanori Hirano.

References

More Repositories

1

sngan_projection

GANs with spectral normalization and projection discriminator
Python
1,079
star
2

chainer-gan-lib

Chainer implementation of recent GAN variants
Python
407
star
3

xfeat

Flexible Feature Engineering & Exploration Library using GPUs and Optuna.
Python
369
star
4

chainer-gogh

Python
302
star
5

menoh

Menoh: fast DNN inference library with multiple programming language support
C++
279
star
6

contextual_augmentation

Contextual augmentation, a text data augmentation using a bidirectional language model.
Python
193
star
7

distilled-feature-fields

Python
178
star
8

nips17-adversarial-attack

Submission to Kaggle NIPS'17 competition on adversarial examples (non-targeted adversarial attack track)
Python
146
star
9

meta-tasnet

A PyTorch implementation of Meta-TasNet from "Meta-learning Extractors for Music Source Separation
Python
135
star
10

FSCS

Fast Soft Color Segmentation
Python
134
star
11

chainer-pix2pix

chainer implementation of pix2pix
Python
131
star
12

k8s-cluster-simulator

Kubernetes cluster simulator for evaluating schedulers.
Go
124
star
13

chainer-compiler

Experimental toolchain to compile and run Chainer models
Python
112
star
14

graph-nvp

GraphNVP: An Invertible Flow Model for Generating Molecular Graphs
Python
91
star
15

autogbt-alt

An experimental Python package that reimplements AutoGBT using LightGBM and Optuna.
Python
82
star
16

chainer-stylegan

Chainer implementation of Style-based Generator
Python
79
star
17

tgan

The implementation of Temporal Generative Adversarial Nets with Singular Value Clipping
Python
78
star
18

tgan2

The official implementation of "Train Sparsely, Generate Densely: Memory-efficient Unsupervised Training of High-resolution Temporal GAN"
Python
76
star
19

deep-table

Python
76
star
20

git-ghost

Synchronize your working directory efficiently to a remote place without committing the changes.
Go
73
star
21

chainer-graph-cnn

Chainer implementation of 'Convolutional Neural Networks on Graphs with Fast Localized Spectral Filtering' (https://arxiv.org/abs/1606.09375)
Python
67
star
22

meta-fuse-csi-plugin

A CSI plugin for All FUSE implementations
Go
67
star
23

surface-aligned-nerf

Python
65
star
24

bayesgrad

BayesGrad: Explaining Predictions of Graph Convolutional Networks
Jupyter Notebook
62
star
25

japanese-lm-fin-harness

Japanese Language Model Financial Evaluation Harness
Shell
62
star
26

torch-dftd

pytorch implementation of dftd2 & dftd3
Python
60
star
27

alertmanager-to-github

This receives webhook requests from Alertmanager and creates GitHub issues.
Go
50
star
28

kaggle-lyft-motion-prediction-4th-place-solution

Kaggle Lyft Motion Prediction for Autonomous Vehicles 4th place solution
Python
48
star
29

einconv

Python
46
star
30

chainer-segnet

SegNet implementation & experiments in Chainer
Python
42
star
31

TabCSDI

A code for the NeurIPS 2022 Table Representation Learning Workshop paper: "Diffusion models for missing value imputation in tabular data"
Python
41
star
32

gcp-workload-identity-federation-webhook

This webhook is for mutating pods that will require GCP Workload Identity Federation access from Kubernetes Cluster.
Go
39
star
33

chainer-trt

Chainer x TensorRT
C++
34
star
34

hyperbolic_wrapped_distribution

Python
32
star
35

picking-instruction

PFN Picking Instructions for Commodities Dataset (PFN-PIC) including images, bounding boxes and text instructions.
31
star
36

pftaskqueue

pftaskqueue: Lightweight task queue tool
Go
30
star
37

multi-stage-blended-diffusion

Python
30
star
38

NoTransactionBandNetwork

Minimal implementation and experiments of "No-Transaction Band Network: A Neural Network Architecture for Efficient Deep Hedging".
Jupyter Notebook
30
star
39

capg

Implementation of clipped action policy gradient (CAPG) with PPO and TRPO
Python
29
star
40

charge_transfer_nnp

Graph neural network potential with charge transfer
Python
28
star
41

node-operation-controller

Kubernetes controller for automated Node operations
Go
26
star
42

menoh-ruby

Ruby binding for Menoh DNN inference library
C
26
star
43

optuna-book

Jupyter Notebook
26
star
44

chainer-ADDA

Adversarial Discriminative Domain Adaptation in Chainer
Python
24
star
45

RJT-RL

RJT-RL: De novo molecular design using a Reversible Junction Tree and Reinforcement Learning
Python
23
star
46

superpixel-align

Official implementation of "Minimizing Supervision for Free-space Segmentation" paper
Jupyter Notebook
23
star
47

label-efficient-brain-tumor-segmentation

Python
21
star
48

chainer-disentanglement-lib

Unsupervised Disentanglement Representation Learning in Chainer
Python
21
star
49

vat_nmt

Implementation of "Effective Adversarial Regularization for Neural Machine Translation", ACL 2019
Python
21
star
50

allreduce-proto

A prototype implementation of AllReduce collective communication routine.
C++
20
star
51

Chainer-DeepFill

Python
19
star
52

pfneumonia

Repo for RSNA pneumonia open-source
Python
18
star
53

chainer-LSGAN

Least Squares Generative Adversarial Network implemented in Chainer
Python
18
star
54

KDD-Cup-AutoML-5

KDD Cup 2019 AutoML Track 5th solution
Python
18
star
55

step-wise-chemical-synthesis-prediction

A GGNN-GWM based step-wise framework for Chemical Synthesis Prediction
Python
17
star
56

ATPG4SV

A prototype of Concolic Testing engine for SystemVerilog, developed as part of PFN summer internship 2018.
OCaml
16
star
57

menoh-sharp

C# binding for Menoh DNN inference library
C#
15
star
58

BMI219-2017-ProteinFolding

UCSF BMI219 Deep Learning (2017), Coding example (Prediction of protein folding with RNN and CNN)
Python
15
star
59

go-menoh

Golang binding for Menoh DNN inference library
Go
14
star
60

hierarchical-molecular-learning

Implementation of "Semi-supervised learning of hierarchical representations of molecules using neural message passing" (arXiv:1711.10168)
Python
14
star
61

kaggle-alaska2-3rd-place-solution

3rd place solution for ALASKA2 Image Steganalysis on Kaggle
Python
13
star
62

menoh-rs

Rust binding for Menoh
Rust
13
star
63

menoh-haskell

Haskell binding for Menoh DNN inference library
Jupyter Notebook
12
star
64

chainer-differentiable-mpc

Differentiable MPC in Chainer, developed as part of PFN summer internship 2019.
Python
12
star
65

asdf-clusterctl

clusterctl plugin for the asdf version manager
Shell
12
star
66

GenerRNA

Python
11
star
67

Deep_visuo-tactile_learning_ICRA2019

11
star
68

menoh-java

Building a Deep Neural Network (DNN) application in Java
Java
11
star
69

treewidth-prediction

Prediction of Treewidth using Graph Neural Network, developed as part of PFN summer internship 2019.
Jupyter Notebook
10
star
70

pml

A ML-like programming language with type-based probabilistic behavior specification, developed as part of PFN summer internship 2018.
C++
10
star
71

optuna-hands-on

Jupyter Notebook
10
star
72

kaggle-hpa-2021-7th-place-solution

7th place solution of Human Protein Atlas - Single Cell Classification on Kaggle
Python
9
star
73

chainer-ev3

Jupyter Notebook
9
star
74

chainer-robotcar-text

8
star
75

tabret

Python
8
star
76

pfmt-bench-fin-ja

pfmt-bench-fin-ja: Preferred Multi-turn Benchmark for Finance in Japanese
Python
8
star
77

batch-metaheuristics

Python
7
star
78

rp-safe-rl

Python
7
star
79

limited-gp

C++
6
star
80

recompute

Python
6
star
81

piekd

This is the official implementation of Periodic Intra-Ensemble Knowledge Distillation (PIEKD).
Python
6
star
82

differentiable-ray-sampling

Jupyter Notebook
6
star
83

BMI219-2017-DeepQSAR

UCSF BMI219 Deep Learning (2017), Coding example (QSAR with Deep multitask learning)
Python
5
star
84

chainer-capsnet

CapsNet implemented in Chainer
Python
5
star
85

node-menoh

NodeJS binding for Menoh DNN inference library
JavaScript
5
star
86

chainer-formulanet

Chainer implementation of FormulaNet
Python
5
star
87

plamo-examples

5
star
88

pocket_detection

Pocket detection
Python
5
star
89

ssdrl

Python
4
star
90

cg-transfer

Python
4
star
91

head_model

Python
4
star
92

Finance_data_augmentation_ICAIF2022

Jupyter Notebook
3
star
93

echainer

Elastic Chainer prototype
Python
3
star
94

robust_estimation

repository for robust estimation research
Python
3
star
95

Invisible_marker_IROS2020

3
star
96

ex_matgl

MatGL-based neural network potential that computes excited state energies and forces
Python
3
star
97

timesfm_fin

Python
3
star
98

nms-comp

Neural Multi-scale Compression
Python
2
star
99

transport-control-socket

C++
2
star
100

unsupervised_segmental_empirical_ODM

Python
2
star