The following notes cover the topics discussed at the Seminar of Computational Finance held at ETH Zurich, DMAT by Josef Teichmann.
Important remark: I do not take any credit for the content of the notes; all credit goes to the professor, the reference papers and so on.
Feel free to reach out to me with any comments, clarifications, or corrections.
Lastly, note that the following page reflects my learning journey and not the proper way the seminar was conducted or how people were supposed to follow it: you'll therefore find my deep dives, my interests and how I preferred to study the topic. Let's go!
Index
- 1. Introduction: Transportation Marketplace Rate Forecast Using Signature Transform
- 2. Technical Background
- 2.1. Tensors
- 2.2. Signatures of a Continuous Path
- 2.3. Key Properties of Signature
- 2.4. Theorem 1: Uniqueness
- 2.5. Theorem 2: Universal nonlinearity
- 2.6. Theorem 3: Factorial Decay
- 2.7. Theorem 4: Invariance to Time Reparametrization
- 2.8. Computation of Signature Transform
- 2.9. Chen's Identity
- 2.10. Improving computational efficiency
- 3. A Generic Framework for Linear Statistical Models with Signature Transform
- 4. Signature Based Deep Hedging
Introduction: Transportation Marketplace Rate Forecast Using Signature Transform
We begin by approaching the paper Transportation Marketplace Rate Forecast Using Signature Transform, written by Haotian Gu, Xin Guo, Timothy L. Jacobs, Philip Kaminsky, and Xinyu Li in December 2024.
In the following section, I try to provide a better understanding and summary of the paper, while still reviewing theoretical foundations.
Introduction: overview of freight marketplace rates and challenges in forecastingThe starting point of the paper is Amazon's key problem in forecasting transportation freight marketplace rates, driven by a lot of factors (networks of thousands of drivers, shippers of all sizes, seasonal and regular demands, traditional and digital exchanges, local, regional, and national economic factors, etc.) and often going through fundamental shifts (because of wars, pandemics, fuel prices, or shifts in international patterns).
In this context, traditional time-series techniques may fail to predict transportation freight rates.
Autoregressive Integrated Moving Average (ARIMA) and Exponential Smoothing assume that time series are stationary, but this is not the case. Furthermore, long-term trends and seasonality are not well captured by ARIMA. Lastly, these methods rely only on historical data from the time series and are not able to capture the causal relationship between economic factors and the target prediction variable (i.e., the transportation freight rates).
Indeed, a big challenge in analyzing time-series data is their changing statistical properties caused by changes in the business and economic cycle, shifts in policy, or changes in market conditions, for example, as we have recently seen in terms of volatility, demand, and supply during COVID-19 or the war in Ukraine.
To address these problems, we can approach statistical learning, which relies on finding a feature map that maps the input data (in our case: samples of time series) into a multidimensional feature space, with the following two important requirements:
- universality: nonlinear functions of the input data are approximated by linear functionals in the feature space, so the forecasting problem is translated into a linear regression;
- characteristicness: the expected value of the feature map characterizes the law of the random variable.
Therefore, the signature transform satisfies these two properties in duality.
Furthermore, the signature kernel allows for computationally efficient comparison of similarities between time-series data, which is particularly useful for identifying different "signature feature maps" (i.e., the statistical counterpart of identifying different distributions for time-series data in the linearized feature space of the signature transform).
We recall that the signature transform (path signature, signature) was introduced and initially studied in algebraic topology by Kuo-Tsai Chen in Iterated Integrals and Exponential Homomorphisms (Proceedings of the London Mathematical Society) and Integration of Paths, Geometric Invariants and a Generalization of the Baker–Hausdorff Formula (Annals of Mathematics), and then applied to the financial markets and machine learning.
Generally speaking, given any continuous or discrete time series, its signature transform produces a vector of real-valued features that extract information such as order and area, and then explicitly considers combinations of different channels to characterize the time series in a computationally efficient way.
Furthermore, every continuous function of a time series can be asymptotically approximated by a linear functional of its signature, so, in other words, the signature transform linearizes the complicated feature space and can be used as a powerful tool for pattern identification and forecasting in machine learning.
Intuition: consider each market period as a path with rates, supply and demand, etc. The signature turns the path into a "fingerprint" that captures the values and how they changed. Then the signature kernel compares fingerprints by to understand how similar they are. During forecasting, historical periods more similar to the current one get more weight in the regression and vice versa, helping the model to adapt to seasonality and market regimes.
Methodology
The proposed approach starts by collecting data (market supply and demand factors) and running correlation tests between the marketplace rate and the factors in order to remove nonsignificant factors and identify factors that are collinear.
Then, the authors use the universal nonlinearity property of the signature transform to build signature features as candidates for the "internal features" using a feature map that transforms time-series inputs into a vector of features. Note that the map does not capture only the values, but also their order and interactions.
Recall that collinearity means that predictors overlap, and, in regression, this makes it hard to tell which predictor matters and can make the coefficient estimates unstable.
Furthermore, to avoid overfitting and collinearity between signature features and external factors, they adopted the two-step LASSO for the regression (helping to shrink coefficients and select a small set of features), enhanced with adaptive weights using a signature kernel that allows it to capture changes in regimes or seasonality.
Technical Background
TensorsA tensor is a mathematical object that generalizes vectors and matrices.
Formally, let be a vector space over a field . A tensor of type on is an element of , where is the dual space.
Equivalently, it can be seen as a multilinear map:
As we said, tensors can be seen as a generalization of lower-dimensional data structures:
- rank-0 tensor: scalar
- rank-1 tensor: vector (requires 1 index)
- rank-2 tensor: matrix (requires 2 indices)
- rank-3 or higher tensor: higher-dimensional "cubes" or "hypercubes" of data (example: a batch of color images in DL is a 4D structure with shape
[Batch Size, Channels, Height, Width])
Furthermore, we recall that the outer product for and is the tensor , with components .
This translates to the following matrix, which has all the pairwise component combinations:
Signatures of a Continuous Path
Let denote the space of all real tensors with shape .
We define a binary operation called tensor product, denoted by , that maps a tensor of shape and a tensor of shape to a tensor of shape via
When applied to two vectors, this is the outer product.
Let and for , in each case with tensor product symbols.
Intuition: the tensor product combines two tensors by multiplying their elements without summing. Example: multiplying a 2-vector by a 3-vector produces a matrix. If we repeat the operation, we have , where each entry is a product of components, .
Definition: signature of as a collection of iterated integralsLet and let be a continuous, piecewise-smooth path.
The signature of is then defined as the collection of iterated integrals:
Here, is the tensor product, , and the term is taken to be .
Then, the truncated signature of depth of is defined as:
The idea is that we have a continuous, piecewise-smooth path ( denotes its position at time ); the signature records a sequence of features called levels, i.e., level collects all the -fold iterated integrals of the path:
Specifically, for path , its level is:
Similarly, a 2-fold iterated integral is:
The inner integral collects changes in coordinate up to time ; the outer integral then pairs those with later changes in coordinate (intuition: this measures how much change in coordinate is followed by change in coordinate , and higher levels represent increasingly detailed ordered combinations of changes).
Example: linear interpolation
We now provide an illustrative example. Suppose is the linear interpolation between two points (i.e., the straight line from to as time goes from to ), so that:
Then its signature is the collection of tensor powers of its total increment :
To show this, let and . Then,
Substituting this into the signature levels gives:
In general, the ordered region has volume , so we have:
So the signature is:
Example: one-dimensional smooth path
Suppose is a one-dimensional smooth path. Its signature is the collection of powers of its total increment. We can proceed as follows:
Let . The integral over the full cube factors into a product of integrals:
The cube divides into regions according to the possible orderings of the times. Since the one-dimensional integrand is symmetric in those times, each region contributes equally. Therefore,
This gives:
We immediately notice that this is independent of for . Furthermore, if is a random process, its expected signature is:
If these moments exist, they are the moments of . For a high-dimensional stochastic process , the expected signature is the generalization of the moments of the process (in other words, for a stochastic process, its expected signature characterizes the law of ).
Also, this second example shows that the signature of a one-dimensional path depends only on its increment. This implies that the signature of a path itself may not contain sufficient information to fully characterize the path, but this problem can be solved by considering time-augmented versions of the original path.
Indeed, given a path , we can define the corresponding time-augmented path by , which is a path in .
Signature of Discrete Data
If we want to compute the signature of discrete data streams, we can simply use linear interpolation and then apply the signature transform.
We can indeed define the space of streams of data as:
Given , the integer is called the length of .
Furthermore, for such that , we can fix:
Let be continuous such that for all and linear on the intervals in between. Then is called the linear interpolation of .
Given that is a linear interpolation of , the signature of (the initial stream of data) is defined as , and the same applies to the truncated signatures, i.e., .
Key Properties of Signature Theorem 1: Uniqueness
Let be a continuous piecewise-smooth path. Then uniquely determines up to translation.
Intuition: the signature collects all iterated integrals, and these integrals are like the moments of a distribution. "Up to translation" means that two paths are considered the same if one is just the other shifted by a constant vector.
Theorem 2: Universal nonlinearity (Weierstrass Theorem)
Let be a real-valued continuous function on continuous piecewise-smooth paths in and let be a compact set of such paths. Also assume that for all .
Consider now . Then there exists a linear functional such that
Intuition: any continuous function of a path, even if not linear, can be approximated as closely as we want by a linear combination of signatures.
We can think of this theorem by analogy. The Weierstrass theorem says that any continuous function on an interval can be approximated by a polynomial, i.e.
that is linear in the coefficients , and the "features" are the monomials . Well, theorem 2 is the same: the features are the iterated integrals (signatures), and the polynomial is .
This works firstly because products of signature terms are again signatures (\implies we can write the product of two iterated integrals as a linear combination of higher-level ones) and because the signature separates paths (i.e. it is unique up to translation, but in the theorem we assume to avoid this).
This universal nonlinearity is the key property of the signature transform, and it is necessary for the model and its applications. Note also that the signature, by definition, is an infinitely-dimensional tensor; however, we often deal with the truncated signature up to some depth .
Theorem 3: Factorial Decay
Let be a continuous piecewise-smooth path, and let be a tensor norm on .
where is a constant depending on .
Intuition: the "size" of a level- signature is at most , so higher levels of the signature "shrink" faster than the exponential (the norm of the level- term gets smaller as grows), so a few levels can capture almost everything and this makes truncation justified.
Theorem 4: Invariance to Time Reparametrization
Let be a continuous piecewise-smooth path. Let be a continuously differentiable, increasing and surjective function. Then .
ProofFirst of all, we set .
Since is continuous, increasing, and surjective, we have and . Since and is piecewise smooth, is also continuous and piecewise smooth.
Furthermore, by the chain rule, we have
We now prove the following:
We can then proceed by induction on , first proving that it holds for . Indeed, we have:
We now do the inductive step, i.e. we assume that it also holds for . So we have:
If we now take and , we have:
Intuition: represents the time change, so the path is the exact same curve as but at a different speed. The theorem says that speeding up or slowing down doesn't change the signature. This is an important feature because it implies that the signature encodes data by its arrival order and independently of its arrival time.
From this theorem, note that the signature of a (discrete) stream of data is not dependent on the choice of interpolation times .
Furthermore, if we consider as a data stream of length in , then has components, with
The idea is that, since the truncated signature is a long vector of numbers, each number is one iterated integral of the path, where each level has components (note also that this is independent of the length of the data stream).
Computation of Signature Transform
The signature transform of a data stream can be computed in an efficient way with the help of Chen's identity.
The main idea is that the signature of a path is a list of numbers that represent the path through iterated integrals (level 1: displacement, level 2: areas between coordinates, etc.).
Chen's identity states that the signature of a path made of two consecutive pieces is the product of the signatures of the pieces.
That means that we do NOT have to process the whole path at once, but we can instead compute the signature of each small piece and then multiply them with . This can be done incrementally and far more cheaply, so, when a new data point arrives, we can update the signature with one operation instead of recomputing everything.
Formally speaking, we first have to introduce the operator.
Set and define by:
This can be interpreted as multiplication of signatures, i.e.
Note that is the space of tensors obtained via the tensor product ( is a matrix with entries ), and represents a list, not a product of numbers. Thus, each element of is a tuple where lives at level .
Furthermore, represents the two signatures being multiplied. Each is a list with one entry per level, and the indices and sum to .
Then, Chen's identity states that the image of the signature transform forms a group structure with respect to .
Chen's Identity
Formally, this means that, given a sequence of data and , we have that
Proof of Chen's IdentityWe start with the following definition:
This can be split into disjoint pieces by cutting the interval at , so we have on and on :
Note that the pieces are disjoint and the equality holds up to a null set: together they miss only the points where some , which have measure zero, so they do not change the integral.
Since is piecewise smooth, the integral with is a traditional Lebesgue integral with a bounded integrand.
So, on each piece the integrand is, by construction, a product of a function of and a function of , and Fubini's (Tonelli's) theorem lets the integral factor.
Recall that Fubini's theorem says that, when the integration region is and the integrand is a product , the integral is:
In our case, this translates to:
And note that the product of the two factors is the tensor product , so, if we sum over , we get:
This is the -component of as previously mentioned. If we set and apply it for , we have:
Furthermore, the signature of a sequence of length 2 can be computed explicitly from the definition. Consider the following.
so we have that
That is a nice way to compute the signature of a single line segment, where in the previous formula is the displacement of the segment () and is tensored with itself times (an order- array with entries ).
But, according to Chen's identity, the signature transform can be computed as
This implies that computing the signature of an incoming data stream is doable, efficient and, most importantly, scalable!
Indeed, if we have some data and receive another data point, we do NOT need to recompute the signature of the entire signal. We can just compute the signature of the new piece of information and then combine it with the previously computed signature using the tensor product.
Improving computational efficiency
The key component of the signature computation is to evaluate the following:
That means that for each data point we need to compute , and so we have to compute each level from scratch. However, this is not efficient since many terms may overlap (the th power of is just the th power times again), so we can reuse the previous result and multiply it by a small factor.
However, instead of computing conventionally with the composition of and , we can speed up the computation using Horner's method.
Intuition: Horner's method rewrites a polynomial as , which uses far fewer multiplications.
In our case, this means expanding as:
so that the -th term can be computed by
The cost of level is the sum of the step sizes:
because this is a geometric series dominated by its last term (for ). Summing over levels gives
Note that this method has fewer scalar multiplications than the conventional approach and reduces the asymptotic complexity from (where comes from adding up k +1 tensors at each level) to .
This rate is asymptotically optimal since the size of the result is itself of size .
A Generic Framework for Linear Statistical Models with Signature Transform
The core idea of this section is to use the universal nonlinearity of the signature transform to capture complex nonlinear relationships and translate them into linear models.
Forecasting ProblemWe can start by considering a time-series forecasting problem with two time series, and , where is a -dimensional vector representing the factor values at time .
The target takes values in (in our case: the freight rate). The goal is to predict the value of for a given time interval , that means finding a (possibly nonlinear) model such that, as closely as possible,
where is the class of all possible models. Note that here is written as a function of the current factor values for simplicity; in the next section it will depend on the recent window through its signature, which is what lets the model use the history of the factors.
Specifically, given data up to time , the standard approach is to solve the following optimization problem:
where is the loss function.
Linear Statistical Models with Signature Transforms
For any time step and a time window of size , we can denote the slice of the time series from to as
Let be the depth of the truncated signature, and let be the corresponding signature for the truncated path from to .
We now consider as the class of linear models that map to .
Given the training data set , the optimal predictor is obtained by minimizing the empirical loss, i.e. by computing:
where has one component per signature feature, i.e. of them (or if the window is time-augmented).
where is the loss function. For example, in the case of ordinary least squares (OLS), is defined as the squared error, i.e.
Furthermore, for Lasso regression, the loss function is augmented with an -regularization term to promote sparsity in the parameters, i.e.
where is the regularization parameter.
Similarly, Ridge regression adds an -regularization term to penalize large parameters, i.e.
Adaptive weight via Signature Kernel
In the classical approach to linear statistical modelling, each historical sample has equal weight in the optimization problem. However, this equal weighting may fail to account for changes in regime or seasonality.
To address this, we can adopt a more effective approach to assign weights based on their similarity to the current period.
To do so, we first recall the signature feature map as:
To avoid computations over a large space of functions, we can define the signature kernel for any discrete time series (where is the inner product on the linear space of signatures) as
Next, we want to measure the similarity between two discrete time series by considering the squared distance induced by the signature kernel, defined as
Note that this is a squared distance, so it is not a metric (the triangle inequality can fail), and with truncation depth it is only a pseudometric (two different series can have distance ).
The idea is that a small implies a higher similarity between patterns (time series) in come from the same regime and share the same seasonality.
Finally, we can adapt the weights in the linear models according to the signature kernel (and this is called 'AdaWeight.Sig').
More precisely, as before, we can consider a forecast horizon , a window size , signature depth , kernel distance , and temperature parameter .
Then, we can define, for all with :
and then denote by the slice of the time series from to .
At each time , 'AdaWeight.Sig' takes the historical samples as inputs and calculates the adaptive weight vector as follows.
such that
Intuition: 'AdaWeight.Sig' assigns a higher weight to the sample if its seasonality pattern near is similar to the current pattern. Furthermore, whenever each new sample arrives, the weight vector is recomputed to adapt to recent changes.
Algorithm 1: Adaptive Weight via Signature Kernel ('AdaWeight.Sig')
-
Input: forecast horizon , window size , depth , temperature , kernel distance , dataset .
-
For :
- compute the distance between the truncated signatures of and :
-
For :
- compute the weights as
-
Output the weight vector . We can now spend some time defining the algorithm.
Algorithm 2: Adaptive Linear Models with Signature Kernel
Once we have defined the adaptive weight algorithm as above, we can proceed with the forecasting algorithm.
-
Input: forecast horizon , regularization parameter , window size , depth , temperature parameter , kernel distance , and dataset .
-
Run 'AdaWeight.Sig' (Algorithm 1, as defined above) once, at the current time , with , , , , , and to identify the regime and obtain .
-
Fit the linear model on the dataset with the adaptive weights and regularization parameter , i.e. solve the weighted problem (the sum already runs over all ):
-
Predict:
To sum up, we can say that measuring similarity via the signature kernel leads to a new linear modelling approach, where we adapt weights according to similarities between time series to capture seasonality and regime.
Note that this is equivalent to identifying different distributions for a given set, but in a linearized feature space from the signature transform.
Signature-Based Deep Hedging
We now present an example of application of the signature transform. In particular, we will consider a self-financing strategy that replicates a path-dependent terminal payoff.
We will simulate asset prices, encode the asset price's path using a truncated time-augmented signature, then fit a linear signature strategy by regression and finally train a nonlinear neural strategy on 256 newly simulated paths.
Before starting, we define the requirements.
import copy
import math
import numpy as np
import torch
from torch import nn
import matplotlib.pyplot as plt
# Dependencies: numpy, torch, matplotlib
torch.set_num_threads(2)
torch.manual_seed(7)
plt.rcParams.update({'figure.figsize': (10, 4), 'axes.grid': True})
Asset Prices
We can model asset prices using a discretized geometric Brownian motion given by
with and . Solving the GBM stochastic differential equation gives this expression, so there is no Euler error in the prices.
Furthermore, note that the term is the Itô correction (convexity correction) applied because, without it, the expected growth would be larger than .
n_calibration, n_val, n_test = 2048, 2048, 4096
paths_per_epoch, epochs = 256, 2000
n_pricing = 100_000
n_steps, n_windows, d = 40, 10, 1
T, sigma, rho, strike = 1.0, 0.25, 0.3, 1.0
mu, r = 0.08, 0.03
depth = 3
claim_type = 'geometric_put' # Alternative: 'asian_call'
weights = torch.full((d,), 1.0 / d)
assert n_steps % n_windows == 0, 'Each window must contain an integer number of steps.'
assert d == 1 or -1 / (d - 1) < rho < 1
feature_dim = sum((d + 1)**k for k in range(1, depth + 1))
memory_gb = (n_calibration + paths_per_epoch + n_val + n_test) * n_steps * feature_dim * 4 / 1e9
print(f'{feature_dim} features; approximately {memory_gb:.2f} GB for feature arrays.')
# 14 features; approximately 0.02 GB for feature arrays.
def simulate_paths(n_paths, seed, drift):
"""Return prices [path, time, asset], including time zero."""
generator = torch.Generator().manual_seed(seed)
# Correlation matrix between assets.
corr = (1 - rho) * torch.eye(d) + rho * torch.ones(d, d)
# Compute the lower-triangular L, with LL^T = corr.
chol = torch.linalg.cholesky(corr)
# Draw independent N(0,1) shocks and multiply by L^T.
z = torch.randn(n_paths, n_steps, d, generator=generator) @ chol.T
dt = T / n_steps
# Log return at each step (Gaussian with mean (drift − ½σ²)Δt
# and standard deviation σ√Δt).
log_returns = (drift - 0.5 * sigma**2) * dt + sigma * math.sqrt(dt) * z
log_prices = torch.cat([torch.zeros(n_paths, 1, d), log_returns.cumsum(1)], dim=1)
return log_prices.exp()
S_calibration = simulate_paths(n_calibration, 10, drift=mu)
S_val = simulate_paths(n_val, 20, drift=mu)
S_test = simulate_paths(n_test, 30, drift=mu)
times = torch.linspace(0, T, n_steps + 1)
Consider that in the previous code we assumed n_steps = 40 and year, so we have ( rebalanced hedging every six trading days).

In the notebook, we use the (physical) measure, with drift and volatility , for training, validation, testing, and feature calibration. We use the (risk-neutral) measure, with drift and the same volatility, for pricing only.
Intuition: we need for pricing because it gives the initial required capital , which represents "the fair cost of hedging". However, we need for training and testing because we are interested in how the strategy performs in the real world.
Note that moving from P to Q changes only the drift through the Girsanov change of measure.
Indeed, under P, the price solves , where is a P-Brownian motion. Let be the market price of risk (the excess return per unit of volatility).
Girsanov's theorem (constant-drift case) states that, if is a martingale (which is true here because is constant, e.g. by Novikov's condition), then the measure defined by is equivalent to and is a -Brownian motion.
Substituting in the dynamics of :
Intuition: the change of measure removes the risk premium from the drift and replaces it with the risk-free rate, while the randomness stays the same.
, on the other hand is unchanged since it is linked to the path's quadratic variation: . Furthermore, note that under the discounted price is a martingale, which formally means:
To see this, solve the SDE under :
The increment is independent of and , and , so the factors cancel and we get . On the grid the same computation gives .
Under instead, the same computation gives : the discounted price drifts upward at the risk premium, so it is NOT a martingale.
This also implies that, for any holding , the discounted gains have mean zero under . Indeed, since is -measurable, by the tower property
(assuming enough integrability, e.g. bounded or square-integrable ). Hence .
To sum up... if a strategy replicated the claim exactly, , then . This is why the Q-expectation is the no-arbitrage price, which is why we use it as initial capital.
Under the gains have mean (they earn the risk premium), which is why the hedging error under can show a bias.
Path-dependent claim
We now split into equal windows and, for each simulated asset, compute the arithmetic average in each window and then the geometric mean across windows.
We then build the terminal claim as
We immediately notice that depends on the whole trajectory, not only on the price at expiry, so the value at time is NOT a function of alone.
Therefore, we cannot use Black–Scholes; we can use the signature for hedging because it represents how the path has evolved so far.
Note that the payoff can be defined as an Asian-style put with a variant. Indeed, an Asian put value depends on the average (arithmetic or geometric average across the windows) of the underlying price over time, not on alone.
Formally, this means:
Our payoff sits between the last two: if , then is the arithmetic average over ; if each window shrinks to a single observation date, is the geometric average of the prices.
In our case, we are dealing with a particular case: in each window the average is not lognormal, so there's no exact closed form for the full payoff (only the pure geometric Asian put has one, since the geometric average of a lognormal process is lognormal).
def terminal_claim(S, kind=claim_type):
"""Return one terminal payoff per path."""
midpoint_prices = 0.5 * (S[:, :-1] + S[:, 1:])
if kind == 'geometric_put':
steps_per_window = n_steps // n_windows
window_means = midpoint_prices.reshape(-1, n_windows, steps_per_window, d).mean(2)
geometric_means = window_means.log().mean(1).exp()
return (strike - geometric_means @ weights).clamp_min(0)
if kind == 'asian_call':
arithmetic_means = midpoint_prices.mean(1)
return (arithmetic_means @ weights - strike).clamp_min(0)
raise ValueError('Unknown claim type')
Furthermore, for this case, we can estimate the risk-neutral value of the discretized claim using 100,000 independent pricing paths with drift and discounting the payoff to time zero. Formally, we have:
def estimate_price(n_paths, batch_size=4096):
"""Estimate the claim price and its Monte Carlo standard error."""
payoffs = []
# Walk through 100,000 paths in chunks of 4,096 (25 batches)
# to keep memory small.
for batch, start in enumerate(range(0, n_paths, batch_size)):
size = min(batch_size, n_paths - start)
# simulation under Q
S = simulate_paths(size, seed=1_000_000 + batch, drift=r)
payoffs.append(terminal_claim(S))
# Discounting.
H = math.exp(-r * T) * torch.cat(payoffs).double()
# return price p = mean(H) and standard error: std(H̃)/√N
return H.mean().item(), (H.std() / math.sqrt(n_paths)).item()
initial_capital, price_se = estimate_price(n_pricing)
H_val = terminal_claim(S_val)
H_test = terminal_claim(S_test)
print(f'Fixed initial capital (risk-neutral price): {initial_capital:.5f}')
print(f'Pricing Monte Carlo SE: {price_se:.5f}')
print(f'Approximate 95% pricing CI: [{initial_capital - 1.96*price_se:.5f}, '
f'{initial_capital + 1.96*price_se:.5f}]')
# 14 features; approximately 0.02 GB for feature arrays.
# Fixed initial capital (risk-neutral price): 0.05119
# Pricing Monte Carlo SE: 0.00023
# Approximate 95% pricing CI: [0.05074, 0.05164]
Time-augmented Signature
The idea is that the hedging strategy at time t only depends on the path of the asset price up to t. We can then compress this information into the signature.
To do so, we firstly consider the following time-augmented path for the generic case with d assets:
where the time channel is added since the plain signature ignores the "timing" dynamics of the path (i.e. it ignores how fast the path moves).
We then normalize prices to start at 0 and consider the case with asset, so the path has a total of 2 channels.
The path is linearly interpolated between two observations, so if we consider the segment , the signature has the following closed form:
We can now apply Chen's identity to update the signature only when a new segment is added (i.e. when a new data point is received):
Then, we apply truncation so that only levels are kept (in this case, ). The number of features is therefore (it grows exponentially with depth and asset count).
In the code, tensor_product computes the flattened outer product. Then prefix_signatures loops over time steps, appends the current signature, adds a new segment, and builds the segment's levels recursively using and Chen's identity.
def tensor_product(a, b):
"""Flattened tensor product for each path."""
return (a.unsqueeze(-1) * b.unsqueeze(-2)).flatten(1)
def prefix_signatures(Z, depth):
"""Prefix signatures before each price increment: [batch, steps, features]."""
batch, nodes, channels = Z.shape
levels = [torch.ones(batch, 1, dtype=Z.dtype)]
levels += [torch.zeros(batch, channels**k, dtype=Z.dtype) for k in range(1, depth + 1)]
prefixes = []
for n in range(nodes - 1):
# Record the prefix at n before adding the segment n -> n+1.
prefixes.append(torch.cat(levels[1:], dim=1))
increment = Z[:, n + 1] - Z[:, n]
segment = [torch.ones(batch, 1, dtype=Z.dtype)]
for k in range(1, depth + 1):
segment.append(tensor_product(segment[-1], increment) / k)
old = levels
levels = [sum(tensor_product(old[j], segment[k-j]) for j in range(k+1))
for k in range(depth + 1)]
return torch.stack(prefixes, dim=1)
def make_features(S):
time_channel = times.reshape(1, -1, 1).expand(S.shape[0], -1, -1) / T
relative_prices = S / S[:, :1] - 1
augmented_path = torch.cat([time_channel, relative_prices], dim=-1)
return prefix_signatures(augmented_path, depth)
We then standardize each feature into so every feature (every iterated integral) has a comparable scale.
# Fit scaling once on an independent calibration sample.
F_calibration = make_features(S_calibration)
feature_mean = F_calibration.mean(dim=(0, 1), keepdim=True)
feature_scale = F_calibration.std(dim=(0, 1), keepdim=True).clamp_min(1e-6)
def scaled_features(S):
return (make_features(S) - feature_mean) / feature_scale
F_val = scaled_features(S_val)
F_test = scaled_features(S_test)
print('Validation feature shape:', tuple(F_val.shape))
Self-financing Portfolio and Objective
At each date , suppose we choose to hold shares of the asset using only information up to , with initial fixed capital .
The cash balance is then b_n = V_n - h_n S_n, subject to interest rate r, so the total wealth is:
where the first term represents the share's new value and the second the cash left in the bank at interest rate . Note that nothing is added or withdrawn, so the strategy is self-financing.
We now define the discounted asset price as . If we divide the recursion by , we reach the following closed form for the total wealth:
Intuition: the discounted wealth equals the initial capital plus the accumulated and discounted trading gains.
We now want to minimize the mean squared hedging error at maturity under the physical measure ; that means that we want to minimize the following loss function:
Since and the rest is fixed, this implies minimizing:
So the target is , the discounted claim minus the initial capital, and the model tries to reproduce it with trading gains.
Note that this is not a regression of the claim on the signature of the whole path. The model is fitted through the trading gains; hence, the signature only appears as the input for the holdings .
def wealth_from_holdings(h, S, capital):
"""Self-financing wealth, including interest on the cash balance."""
bank_account = torch.exp(r * times).reshape(1, -1)
discounted_S = S / bank_account.unsqueeze(-1)
gains = (h * (discounted_S[:, 1:] - discounted_S[:, :-1])).sum(dim=-1)
initial = torch.as_tensor(capital, dtype=S.dtype).expand(S.shape[0], 1)
discounted_V = torch.cat([initial, initial + gains.cumsum(dim=1)], dim=1)
return bank_account * discounted_V
Linear Signature Hedging by Least Squares
The starting point of the hedging problem is that, for one path, the trading gain is a sum over 40 dates:
where each term is the profit or loss of that interval. We then want to be as close as possible to , the discounted payoff minus the Asian put we owe and the initial capital (which implies that the trading gains have to cover that difference).
We now consider , the standardized signature up to degree , and include a constant coordinate by defining:
def add_constant(features): return torch.cat([torch.ones_like(features[..., :1]), features], dim=-1)
We then define the holdings as a linear combination of :
Intuition: we want to find the weights at every date, and the time dependence comes from the feature because the signature contains . The strategy is therefore a linear combination of the path's iterated integrals.
We can now substitute in the gains formula and change the order of summation since does not depend on :
We recall that is the gain we would make following the "elementary strategy" (hold shares at date , with weight 1; this is a number you can compute for each path before fitting anything.)
def regression_batch(S):
phi = add_constant(scaled_features(S)).double()
discounted_S = S.double() * torch.exp(-r * times.double()).reshape(1, -1, 1)
increments = discounted_S[:, 1:] - discounted_S[:, :-1]
# build A with path b, date n, feature q, asset i
A = torch.einsum('bnq,bni->bqi', phi, increments).flatten(1)
y = math.exp(-r * T) * terminal_claim(S).double() - initial_capital
return A, y
Again, we want to match (), so we can find that minimizes the squared loss:
where indexes the paths, and each is the discounted hedging error on path (note that this is the "Monte Carlo version" of )
If we set the gradient to zero, we obtain and, if is invertible, we get .
However, note that many columns are nearly or exactly linearly dependent, so inverting the matrix gives unstable coefficients.
Therefore, we can use an SVD-based solver that handles dependencies without inverting .
def fit_linear_signature(n_batches=epochs, batch_size=paths_per_epoch):
"""Fit empirical L2 hedging on the same simulated paths as the NN."""
rows, targets = [], []
# Generate 2,000 batches of 256 paths under the physical measure P.
for batch in range(n_batches):
S = simulate_paths(batch_size, seed=10_000 + batch, drift=mu)
A, y = regression_batch(S)
rows.append(A)
targets.append(y)
A, y = torch.cat(rows), torch.cat(targets)
# lstsq with gelsd solves min|AC-y|^2 with an SVD
# solution: vector of 15 numbers
fit = torch.linalg.lstsq(A, y, driver='gelsd', rcond=1e-10)
coefficients = fit.solution.reshape(feature_dim + 1, d).float()
print(f'Least squares: {len(y):,} paths, {A.shape[1]} coefficients, rank {fit.rank.item()}')
return coefficients
def linear_portfolio(coefficients, features, S):
h = add_constant(features) @ coefficients
return wealth_from_holdings(h, S, initial_capital), h
Once we have fitted the model and found , we can apply at every date and then compute the wealth, starting from .
linear_coefficients = fit_linear_signature()
with torch.no_grad():
V_linear_val, _ = linear_portfolio(linear_coefficients, F_val, S_val)
print(f'Linear validation MSE: {(V_linear_val[:, -1] - H_val).square().mean():.6f}')
# The regression prediction must equal the discounted trading gain.
A_check, _ = regression_batch(S_val[:4])
V_check, _ = linear_portfolio(linear_coefficients, F_val[:4], S_val[:4])
expected_gain = A_check @ linear_coefficients.double().flatten()
actual_gain = math.exp(-r * T) * V_check[:, -1].double() - initial_capital
torch.testing.assert_close(actual_gain, expected_gain, rtol=1e-4, atol=1e-6)
Neural Signature Hedging
We now apply the same procedure, but replace the linear map with a nonlinear neural network of the following form:
Note that the network has two hidden layers of 32 units with Tanh activation and a linear output. Consider also that holdings can be negative.
def portfolio(model, features, S):
"""V includes V_0; h[:, n] is held over the interval n -> n+1."""
h = model(features)
V = wealth_from_holdings(h, S, model.capital)
return V, h
def hedging_loss(model, features, S, H):
V, _ = portfolio(model, features, S)
return (V[:, -1] - H).square().mean()
model = HedgeNet(feature_dim, d, initial_capital)
assert "capital" not in dict(model.named_parameters())
Then, the initial capital, features, simulated paths, and objective are the same as in the previous linear regression case.
Note also that in this case the capital is not a parameter: the model stores it but never updates it. Otherwise, if capital were trainable, the model could lower the loss by increasing the starting wealth, breaking the setup.
We can then proceed with the training on new simulations: each epoch generates 256 new paths under the physical measure, computes their payoffs and signature features, and performs one gradient update.
Then, every 50 epochs the model is evaluated on the fixed validation set and, if the validation improves, the weights are stored. Only at the end, the best weights are loaded (however, note that the loss is not convex no global optimum is guaranteed).
def train_model(model, epochs=epochs, batch_size=paths_per_epoch, learning_rate=0.002):
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
history = {'train': [], 'validation': [], 'validation_epoch': []}
best_loss, best_state = float('inf'), None
for epoch in range(epochs):
# One new Monte Carlo batch and one optimizer step per epoch.
S = simulate_paths(batch_size, seed=10_000 + epoch, drift=mu)
H = terminal_claim(S)
F = scaled_features(S)
model.train()
optimizer.zero_grad()
loss = hedging_loss(model, F, S, H)
loss.backward()
optimizer.step()
history['train'].append(loss.item())
if (epoch + 1) % 50 == 0 or epoch + 1 == epochs:
model.eval()
with torch.no_grad():
val_loss = hedging_loss(model, F_val, S_val, H_val).item()
history['validation'].append(val_loss)
history['validation_epoch'].append(epoch + 1)
if val_loss < best_loss:
best_loss = val_loss
# copy weights if loss is improved
best_state = copy.deepcopy(model.state_dict())
if (epoch + 1) % 250 == 0 or epoch + 1 == epochs:
print(f'Epoch {epoch+1:4d} | fresh-batch MSE {loss.item():.6f} | validation {val_loss:.6f}')
model.load_state_dict(best_state)
model.eval()
return history
capital_before_training = model.capital.clone()
history = train_model(model)

Out-of-Sample Results
We now present the linear and neural strategies on independent paths under the physical measure, starting from the fixed Monte Carlo price estimate.
| Strategy | MSE | RMSE | MAE | Bias | 95th pct. of |error| |
|---|---|---|---|---|---|
| Linear signature | 0.00024 | 0.01554 | 0.01238 | -0.00023 | 0.0295 |
| Signature + NN | 0.00009 | 0.00991 | 0.00777 | -0.00003 | 0.0194 |
Fixed initial capital (Q price): 0.05119.
Physical-measure test mean payoff (not a price): 0.04162 ± 0.00207
(approx. 95% MC CI).
