**Welcome to THETAWIKI**. If you like to create or edit a page please make sure to login or register an account. All registered users please make sure to provide a valid email address.

# Hedging in ThetaML

## Contents

## Introduction

This tutorial introduces a variety of hedging techniques in ThetaML. As a byproduct, it also illustrates the simplicity and flexibility of using ThetaML for fast and accurate simulations.

To start with, we compute in ThetaML the very familiar Black-Scholes delta, then use this Black-Scholes delta to simulate hedge European put option - stepping both forward and backward in time. In the end, we compare the hedged portfolio value with the exact European put price. Our first results produce the same European put price for forward and backward hedges, with a standard error of `0.84` in both cases.

Next, we present our unique `Beta` function and illustrate by examples its wide applicablity and flexibility in more advanced hedge settings. We start with the more familiar variance-minimization hedge - for single and multiple underlyings and for single- and multi-dimensional stochastic processes. We then proceed to apply our `Beta` function to static and dynamic portfolio hedging. Finally, our `Beta` function is applied in the real-world hedging with transaction costs, demonstrated by code example for portfolio rebalancing when a barrier is imposed on the positions in the hedge instruments.

To proceed with presenting various hedging methods, we set up a hedge portfolio `Pi` as

- $ Pi = V + d * S $,

with option `V` and a position of `d` in the hedge instrument `S`. The task of the hedging procedure is to choose `d` such that the portfolio `Pi` does not change much even if the underlying `S` changes.

Throughout this tutorial, we use the stock price process `S` and the discount numeraire `EUR` simulated respectively in the model `S_Process` and `EUR_Process`. The stock prices `S` follows a Geometric Brownian motion process, and the discount numeraire `EUR` are computed with a constant interest rate curve. Their ThetaML code implementations can be found in the tutorial From European to American.

## Delta Hedging

We start with a simple example that uses the Black-Scholes-Merton equation to obtain a representation for `d`. The choice and use of `d` to hedge portfolio risk is generally called Delta-Hedging (see Black-Scholes Option Pricing for details).

The delta-hedge pricing method offsets the portfolio risk in `Pi` such that it can be made completely risk free in the idealized Black-Scholes world. This is unrealistic in the real world, mainly because the hedge must be rebalanced continuously in time wheras a real trader can only buy and sell at discrete times. In this section, we will compute and analyze the errors that occur when using discrete instead of continuous hedges.

We use European put option as an example. The formula for European put option delta `d` is known as

$ d = \frac{\partial V}{\partial S} = \mathbb{N} \left( \frac{ \log\left(\frac{S}{K}\right) + (r + \frac{\sigma^2}{2} ) \cdot T }{\sigma \cdot \sqrt{T}} \right) -1 $,

where $ \mathbb{N}() $ is the cummulative standard normal distribution, and the term $ \frac{\partial V}{\partial S}\, $ refers to the partial derivative of `V` with respect to `S`.

With this formula and the convenience that ThetaML can call any regular Matlab functions, it is very easy to obtain the delta of a European put option in ThetaML as follows.

For consistency, all subsequent code examples use the following assumptions and parameter values:

- Stochastic Model: Geometric Brownian Motion
- Volatility
`sigma`: 0.4 (40% p.a.) - Risk-free rate
`r`: 0.05 (5% p.a.) - Current Stock price
`S`: 100 - Numeraire value
`EUR`: 1 - Structural Model
- Strike
`K`: 100 - Maturity time
`T`: 1

The following code example is a ThetaML model for computing Black-Scholes delta for European put.

### ThetaML Model for Computing Black-Scholes Delta

%% This model returns the Black-Scholes hedge ratio "delta" for %% European put options. model OptionDelta import S "Current stock price" import K "Option strike price" import sigma "Volatility of the underlying" import r "Risk-free interest rate" import T "Maturity time of the option" export delta "Black-Scholes put delta" if T<= 0 delta = S < K; else d1 = ( log(S/K) + (r + (sigma^2)/2)*T ) / (sigma * sqrt(T)); delta = normcdf(d1,0,1) - 1; end end

Having computed the Black-Scholes delta in the model `OptionDelta`, we proceed to use this analytic delta to simulate hedging portfolio values and compare the hedge errors between the hedging portfolio and the option value. This is illustrated by the following code examples and hedge error histograms.

This code example is a ThetaML model for simulating hedge portfolio values forward in time, using Black-Scholes delta as the hedge strategy for the underlying hedge instrument $ S $. It also computes the hedging error based on the analytic Black-Scholes option delta.

### ThetaML Model for Black-Scholes Hedge Simulation (Forward)

%%The model European_hedged_BS_forwards simulates the "delta" %%hedge of a European put option. Note that the Black-Scholes %%delta is optimal for the risk-neutral Geometric Brownian motion; %%The stock prices 'S' and the discount numeraire 'EUR' are simulated %%respectively in the model 'S_Process' and 'EUR_Process' model European_hedged_BS_forwards import S "Stock prices" import EUR "Discount numeraire" import sigma "Volatility of stock prices" import r "Risk-free interest rate" import K "Option strike price" export Pi "Portfolio Value" export delta "Hedge ratios (Black-Scholes)" export error "Hedging error" T = 1 %time to maturity of the option n = 250*T %loop length %at current time, set the portfolio value to have the same expected discounted %value as the variable 'V'; the ThetaML future operator '!' accompanying the %variable 'V' allows the values of 'V' to be determined at a later instance %when 'V' is assigned some values Pi = E(V!) %loop n times loop n %call the model 'OptionDelta' call OptionDelta %export the local parameter values 'K', 'sigma', 'r' and 'S' to the parameters %'K', 'sigma', 'r' and 'S' in 'OptionDelta' export K, sigma, r, S %export the time-to-maturity 'T - @time' at current model time to the parameter %'T' in 'OptionDelta'; the ThetaML parameter '@time' extracts the time that has %passed so far export T - @time to T %import in the local variable 'delta' the computed values of 'delta' in 'OptionDelta' import delta %update the previous stock prices 'S_old' to the stock prices 'S' at this model time S_old = S %update the previous numeraire 'EUR_old' to the numeraire values 'EUR' at this model time EUR_old = EUR %the ThetaML command 'theta' advances time by 'T/n' years theta T/n %update portfolio value at the next time-step Pi = Pi + delta * (S * EUR - S_old * EUR_old) end %at option maturity time T (=n*(T/n)), set the European put option payoffs; %the option payoffs are discounted to time 0 by the discount numeraire 'EUR'; %here the values of the stock prices 'S' and the discount numeraire 'EUR' are %evaluated at the option's maturity time T V = max(K - S,0) * EUR %compute the hedging error error = Pi - V end

The model `European_hedged_BS_forwards` uses the Black-Scholes delta computed in the model `OptionDelta` to provide a simple delta hedge for the European put option. The values of the hedging portfolio `Pi` are updated at each model time. The model time steps `T/n` are advanced by the ThetaML command `theta`. After `n` loops with each loop step forward by `T/n` years, at the option's maturity time `T`, we compute the hedging error between the hedging portfolio and the put option.

The ThetaML future operator `!` allows us to use the variable `V` at time 0 even if its values are not pre-assigned `Pi = E(V!)`. The values of `V` are determined at a later instance when `V` is assigned some values. This happens at the option's maturity time, when `V` is assigned the option payoff values.

The ThetaML `E` function computes the conditional expected values of its arguments. In the statement `Pi = E(V!)`, since the conditioning state variables at time 0 have deterministic values, the `E` function simply returns an average value of `V!`.

The ThetaML `call` command calls the submodel `OptionDelta`, exports the values of local parameters to the corresponding parameters defined in the submodel `OptionDelta`, and imports in the local variable `delta` the computed delta values from the submodel `OptionDelta`.

The ThetaML `theta` command advances time to the next model time point. In the model `European_hedged_BS_forwards`, the time grids are a set of times {0, T/n, 2*(T/n), …, T}. The `theta T/n` command in the loop thus passes time from 0 to T/n, from T/n to 2*(T/n), and so on, up to time T.
At the option maturity time `T`, the variable `V` is assigned the payoff values discounted by the numeraire `EUR` maturing at time `T`. At the intermediate model times, the stock prices `S` and `S_old` are discounted by the numeraire `EUR` maturing at these intermediate times.

The following graph is the histogram of the hedge error distribution. The exact value of the European put `E(V)` is 13.15 with a standard deviation of 0.84 for the `error` .

This code example is a ThetaML model for simulating hedge portfolio values backward in time, using Black-Scholes delta as the hedge strategy for the underlying hedge instrument $ S $.

### ThetaML Model for Black-Scholes Hedge Simulation (Backward)

%The model European_hedged_BS simulates the "delta" hedge of %a European put option; the stock prices 'S' and the discount numeraire 'EUR' %are simulated respectively in the model 'S_Process' and 'EUR_Process' model European_hedged_BS import S "Stock prices" import EUR "Discount numeraire" import sigma "Volatility of stock prices" import r "Risk-free interest rate" import K "Option strike price" export Pi "Portfolio Value" export error "Hedging error" T = 1 %time to maturity of the option n = 250*T %loop length error = Pi! - E(V!) %compute the hedging error loop n %loop n times call OptionDelta export K, sigma, r, S export T - @time to T import delta %update current portfolio value ‘Pi’; %‘Pi!’,’ S!’ and ‘EUR!’ represents respectively the %variables ‘Pi’,’ S’ and ‘EUR’ evaluated at the next %model time; the future operator '!' allows the possibility to use the %variables ‘Pi’,’ S’ and ‘EUR’ at the model time when their values %are not known Pi = Pi! – delta * (S! * EUR! – S * EUR) %the ThetaML command 'theta' advances time by 'T/n' years theta T/n end %at the option maturity time, the hedging portfolio ‘Pi’ %has the same value distribution as the European put ‘V’ %’V!’ is simply ‘V’ evaluated in the immediate next statement Pi = V! %at option maturity time T, set the European put option payoffs; %the option payoffs are discounted to time 0 by the numeraire 'EUR' V = max(K - S, 0) * EUR end

The above ThetaML model also computes the hedging error based on the analytic solution of the option's delta. The error is computed in a backward fashion, such that `Pi` always contains exactly the same amount of money required for a perfect replication. It is important to note that this amount `Pi` is not deterministic and thus has a probability distribution at time 0. This distribution minus the option value `E(V!)` is the hedging error.

The ThetaML future operator `!` occurs a couple of times in our hedging model: at the initial time, when computing the hedging error ` Pi! - E(V!)` ; at the intermediate model times, when updating the hedging portfolio values ` Pi! – delta * (S! * EUR! – S * EUR)`. The ThetaML future operator `!` allows the possibility to use the variables `Pi` , `V`, `S` and `EUR` at the model time when their values are not pre-assigned. The finally compiled codes, however, will record the commands into a computational order. This forces the final assignment of `V` to be evaluated first. The result is then overwritten by updated values when stepping backwards in time.

The variables `Pi` , `V`, `S` and `EUR` are process variables with implicit scenario and time indexes, i.e. their values change across different Monte Carlo scenario and at different model times. The use of the future operator `!` allows stepping the processes `Pi` , `V`, `S` and `EUR` forward in time like what they would have behaved in real life financial markets. As such, we are able to update the portfolio values of `Pi` at each model time, while holding the European put option `V` throughout the process up till the maturity time `T`.

The distribution for the hedging error is shown in the graph below.

As in the case of forward hedging, the value of the European put `E(V)` is 13.15 with a standard deviation of 0.84 for the hedging error.

## Variance Minimization by Hedging

Even though theory dictates that financial markets do not allow arbitrage and that markets are complete, even though this no-arbitrage-and-complete-market theory has led to various breakthroughs in the previous decades, there is in ThetaML a unique technology that lies at the frontline of this derivatives research, by simply assuming that a real-world model for the underlying hedge instrument exists. Even though this view appears unconventional, we can obtain optimal hedging strategies for incomplete markets and in the presence of transaction costs.

Our optimal hedging strategies are computed by the function `Beta`. The `Beta(S,V)` function computes a variance minimal hedge based on the statistical properties of the underlying `S` and the instrument to be hedged `V` (more details for the `Beta` command can be found in ThetaML).

Our unique `Beta` function allows using Monte Carlo pricing for many more realistic market scenarios other than the basic ones assumed in the Black-Scholes economy. Moreover, even in a Black-Scholes economy, our `Beta` function gives the same results as the Black-Scholes delta. This is illustrated by the following ThetaML code examples where the hedge instruments can be single- or multi-dimensional stochastic processes, or single or multiple underlyings.

### Single Dimensional Stochastics

#### Single Underlying

%The model American_hedged simulates the optimal hedge of an %American put option; the ‘Beta’ hedge is variance optimal for any %underlying process S; the stock prices 'S' and the discount numeraire % 'EUR' are simulated respectively in the model 'S_Process' and 'EUR_Process' model American_hedged import S "Stock prices" import EUR "Discount numeraire" import sigma "Volatility of stock prices" import r "Risk-free interest rate" import K "Option strike price" export Pi "Portfolio Value" T = 1 %time to maturity of the option n = 252*T %loop length loop n %loop ‘n’ times % update the discounted portfolio value at current time step; %the ThetaML ‘Beta’ function computes a variance-optimal %hedge ratio between its two arguments Pi = Pi! - Beta(S! * EUR!, Pi!) * (S! * EUR! – S * EUR) %early exercise evaluation; the ThetaML function 'E' approximates the conditional %expected discounted portfolio value, computed using the Least Squares Monte Carlo %method combined with the sparse grid basis functions if E(Pi!) < (K – S) *EUR Pi = (K – S) *EUR end %the ThetaML command 'theta' advances time by 'T/n' years theta T/n end %at the option maturity time, the hedging portfolio ‘Pi’ %has the same value distribution as the European put ‘V’; %’V!’ is simply ‘V’ evaluated in the immediate next statement Pi = V! %at option maturity time T, set the European put option payoffs; %the option payoffs are discounted to time 0 by the numeraire 'EUR' V = max(K - S, 0) * EUR end

The hedging model `American_hedged` uses the ThetaML `Beta` function to hedge simulate the American put option value. The `Beta` function returns a variance optimal hedge ratio between its two arguments, conditional on the current information available. The first argument is the explanatory variable, and the second argument is the dependent variable.

The ThetaML future operator `!` appears inside both functions `E` and `Beta` for conditional regressions. Since when stepping forward in time, both `E` and `Beta` have as arguments with values evaluated at the next model time conditional on current model time. The ThetaML future operator `!` allows the possibility to use the variables at the model time when their values are not pre-assigned.

The `E` function uses the least squares Monte Carlo method combined with sparse grid type basis function to compute the conditional expected option value. The ThetaML compiler filters out the conditioning state variables measurable at current model time and takes care of the numerical details in implementing the `E` function.
The cash flows are discounted with the numeraire `EUR`: at the option maturity `T`, the option payoff values are discounted by `EUR` maturing at `T`; at the intermediate model times, the discounted hedge portfolio values `Pi` are discounted by `EUR` maturing at these intermediate model times.

The imported processes `S` and `EUR` step forward in model time along with the process `Pi`, such that at a given model time their values are evaluated at that same specific model time.

#### Multiple Underlyings

%The model American_hedged_nd simulates the optimal hedge of an %American basket put option. ; the ‘Beta’ hedge is variance optimal for any %underlying process S; the stock prices 'S' and the discount numeraire % 'EUR' are simulated externally; note that ‘S’ is now an array of stocks while % 'EUR' is the same numeraire simulated in the model ‘EUR_Process’ model American_hedged_nd import S "An array of stock price process" import K "An array of option strike prices" import EUR "Discount numeraire" export delta "An array of hedge positions" export Pi_obs "Portfolio values" export P "Option price" %at current time, set the option value to have the same %expected discounted value as the variable 'Pi' P = E(Pi!) %loop ‘252’ times loop 252 %we store the values of ‘Pi’ at each time step %in the variable ‘Pi_obs’ for examinations Pi_obs = Pi! %array loop, loop through the elements of the arrays %’S’ and ‘delta!’, and update the discounted hedging portfolio %value ‘Pi’; ‘delta!’ is defined next in the statement %after the array loop loop s, d : S, delta! Pi = Pi! - d * (s! *EUR! - s*EUR) end %computes an array of beta factors at this model time delta = Beta(S! *EUR!, Pi!) %the ThetaML command 'theta' advances time by '1/252' years theta 1/252 end %at the option maturity time 1, the hedging portfolio value ‘Pi’ %has the same value distribution as the European basket put ‘V’ %’V!’ is the ‘V’ evaluated in the immediate next statement Pi = V! %loop through the arrays of stocks ‘S’ and strikes ‘K’, and %assign the discounted payoffs to V loop s, k : S, K V = max(V!, k - s) * EUR end %cut-off value of option payoffs V = 0 %liquidate the stock positions at option maturity delta = 0 end

The hedging model `American_hedged_nd` uses array loops in two occasions: `loop s, d : S, delta!` in updating the hedging portfolio `Pi`, and `loop s, k : S, K` in assigning the option payoffs `V`.
In the array loop `loop s, d : S, delta!`, the variables `s` and `d` serve as array iterators and take the corresponding pointed array values. The loop

loop s, d : S, delta! Pi = Pi! – d * (s! *EUR! - s*EUR) end

can be expanded as follows:

`Pi = Pi! - delta[1]*(S[1]!*EUR! – S[1]*EUR)`

`Pi = Pi! - delta[2]*(S[2]!*EUR! – S[2]*EUR)`

`…`

`Pi = Pi! - delta[length(S)] * (S[length(S)]!*EUR! – S[length(S)]*EUR) `

`Pi = Pi_next`

where we have used the square bracket to mark the array indexes, `delta [1]` denotes the first array element of `delta `, and `delta [length(S)]` denotes the last array element of `delta `, and so on.
Define `m = length(S)`, denote the portfolio value at the k-th loop as `Pi[k]` , the above set is put together as follows

`Pi = ( … ((Pi_next - delta[m]*(S[m]!*EUR! – S[m]*EUR)) `

` - delta[m-1]*(S[m-1]!*EUR! – S[m-1]*EUR)) … ) `

` - delta[1]*(S[1]!*EUR! – S[1]*EUR)`

Similarly the array loop

loop s, k : S, K V = max(V!, k - s) * EUR end V = 0

can be expanded as follows

`V = max(V!, (K[1] – S[1]) * EUR)`

`V = max(V!, (K[2] – S[2]) * EUR)`

` … `

`V = max(V!, (K[length(K)] – S[length(S)]) * EUR)`

`V = 0`

where again we have used the square bracket to differentiate the array indexes, and `length(K)= length(S)` per the array definition in ThetaML.

The above array loop expansion can be combined to have the following single statement

`V = max(max( … max(0, (K[length(K)]– S[length(S)])*EUR) … , (K[2] – S[2])* EUR), (K[1] – S[1])*EUR)`

for the payoff of our exotic European basket put option.

The `Beta(S! *EUR!, Pi!) ` function computes an array of beta factors for the array of stocks.

### Multi-Dimensional Stochastics

The exact same ThetaML hedging model is applicable to stock prices that follow higher dimensional stochastic processes, only that the imported stock price process `S` is a multi-dimensional process simulated externally in a process model.

## Static vs. Dynamic Hedging

To further illustrate the applicability of our unique `Beta` command, we provide, among others, the following code examples for static and dynamic portfolio hedging.

### Static Hedging

%The model ‘Static_hedging’ statically hedges a Barrier option using a set of %call and put options as the hedging instruments; the stock prices 'S' and the numeraire %'EUR' are simulated respectively in the model 'S_Process' and 'EUR_Process' model Static_hedging import S "Stock prices" import EUR "Discount numeraire" export delta "Hedge positions" export P_obs "Hedged Barrier option price" %declare 'delta' as a float array of length 20 %declare 'V_t' as a float array of length 20 type delta float[20] type V_t float[20] %at current time, set the ‘P_obs’ to have the same distribution %as the variable 'P!' P_obs = P! %compute the hedge ratios between the hedging instruments ‘V_t!’ %and the Barrier option ‘V!’ at time 0; the value processes for %the Barrier option ‘V!’ and the hedging instruments ‘V_t!’ %are modeled later in the code delta = Beta(V_t!, V!) %array loop; loop through the arrays of hedge ratios ‘delta!’ and ‘V_t!’, %and update the hedged option values ‘P’ loop d, v : delta, V_t P = P! - d * ( v! - E(v) ) end % ‘P’ has the same value distribution as ‘V!’ at time 0 P = V! %a ThetaML ‘fork…end’ statement that virtually parallels the %value process of the Barrier option ‘V’ and the value process %of the hedging instruments ‘V_t’ fork %check ’52’ times whether the Barrier is violated or not loop 52 %the ThetaML command 'theta' advances time by '1/52' years theta 1/52 %at this model time, if these paths where the stock prices ‘S’ is %larger than ‘120, set the values of the Barrier option ‘V’ to 0 if S > 120 V = 0 end end %at 1 year maturity, the discounted option payoff values V = max(100 - S, 0) * EUR end % build up the hedge instruments index = 1 loop 5 %time passing of 1/5 years theta 1/5 %the following set of hedging instruments mature at this time V_t[index] = max(100 - S, 0) * EUR V_t[index + 1] = max(120 - S, 0) * EUR V_t[index + 2] = max(S - 100, 0) * EUR V_t[index + 3] = max(S - 120, 0) * EUR %update the array index index = index + 4 end end

The hedging model `Static_hedging` returns a value distribution for the hedged Barrier option using 20 vanilla call and put options as the hedging instruments. The hedge ratios are computed at time 0 using the ThetaML `Beta` function.

The value processes for the Barrier option `V` and the hedging instruments `V_t` run parallel in model time via the ThetaML `fork … end` statement. As such, both `V` and `V_t` step forward in time as what they would have behaved in real life financial markets.

The model times in the value processes for the Barrier option `V` are a set of time in years {0, 1/52, 2/52, …, 1}, and the model times in the value processes for the hedging instruments `V_t` are a set of time in years {0, 1/5, 2/5, …, 1}. Altogether the model times for the hedging model `Static_hedge` combines these two time sets to have {0, 1/52, …, 10/52, 1/5, 11/52, …, 41/52, 4/5, 42/52, 43/52, …, 1}.

The arrays `delta` and `V_t` are declared as `float` type after the model import and export statements. In most cases, the ThetaML compiler automatically detects the data types without having to explicitly using the `type` keyword to declare the data type.

### Dynamic Hedging

%This model applies our Beta function to provide a dynamic %hedge for a Barrier option model Dynamic_hedging import S "Stock prices" import EUR "Discount numeraire" export Pi_obs "Dynamically hedged option values" export V_obs "Unhedged Barrier option values" %store the present values of the Barrier option in %V_obs, and store the hedged values of the Barrier %option in the variable Pi_obs V_obs = V! Pi_obs = Pi! %a ThetaML ‘fork … end’ statement; it virtually parallels %the process ‘Pi’ defined within the statement with the %process ‘V’ defined in the next ‘fork … end’ statement fork %dynamically hedge the Barrier option loop 252 %dynamically hedge the Barrier option with hedge ratios %computed by the ThetaML ‘Beta’ function Pi = Pi! - Beta(S!*EUR!, Pi!) * (S!*EUR! - S*EUR) %the ThetaML command ‘theta’ advances time by ‘1/252’ years theta 1/252 end end fork %Barrier option value process loop 52 %the ThetaML command ‘theta’ advances time by ‘1/52’ years theta 1/52 %check if the stock prices ‘S’ violates the barrier ‘120’ if S > 120 %if the barrier is violated, the discounted barrier %option ‘V’ and the hedged value ‘Pi’ are knocked out; %this is so for all the violated paths V = 0 Pi = 0 end end %the hedged value process ‘Pi’ has the same distribution %as the discounted barrier option ‘V’ at the option maturity %time 1; ‘V!’ is defined in the immediate next code statement Pi = V! V = max(100 - S,0) * EUR end end

In the hedging model `Dynamic_hedging `, the ThetaML keyword `fork` allows the Barrier option process `V` and its hedged value process `Pi` to step forward in model time in parallel. As such, during the evolving model times, we are able to dynamically hedge the Barrier option `V` using the hedge ratios computed with `Beta(S!*EUR!, Pi!)`, and dynamically update the value process `Pi`. Note that the `S` process, the `EUR` process, and the `Pi` process all evolving at the same pace, meaning that at a given model time, their values are evaluated at the same model time.

The ThetaML future operator `!` appears several times in the code. Its appearance suggests that the values of the variable are defined later in the code. We can therefore look in the subsequent code statements for the instance where the variable is assigned some values to check its whereabouts.

## Transaction Costs

Our `Beta` function also computes optimal hedging strategies in the presence of transaction costs. We show below one such code example for portfolio rebalancing only when the underlying position changes are above a certain barrier.

The case of portfolio rebalancing only when changes in the underlying positions are above a certain barrier:

model BetaHedge_TCost_PositionBarrier % This model applies our ‘Beta’ function to hedge a European % put option in the presence of transaction costs, the % portfolio is rebalanced only when the positions in % underlying hedge instruments change more than some level % the stock prices 'S' and the discount numeraire 'EUR' are % simulated respectively in the model ‘S_Process’ and ‘EUR_Process’ import S "Stock prices" import EUR "Discount numeraire" import K "Option strike price " import T "Option time to maturity" export Pi "Backward hedging portfolio value" export Pi_f "Forward hedging portfolio value" export Error "Hedging error" export delta "Hedge position" n = 252 % loop length kappa = 0.01 % percentage level of transaction cost % the forward hedging portfolio ‘Pi_f’ initially has the % same expected value as the discounted backward hedging % portfolio ‘Pi’ Pi_f = E(Pi!) % ‘delta_old’ is the backward hedging ratio, computed in % the next model time delta_old = 0 % ‘delta_old_f’ is the forward hedging ratio, computed in % the previous model time delta_old_f = 0 % initialize the discounted old stock values ‘S_old’ to % the discounted current stock values ‘S * EUR’ S_old = S * EUR % loop ‘n’ times loop n % optimally update the discounted backward-hedging portfolio % ‘Pi’ considering transaction costs; ‘delta!’ and ‘delta_old!’ % are respectively defined in the immediate next assignment Pi = Pi! - delta!*(S!*EUR! - S*EUR) + kappa * abs( (delta_old! - delta!)*S*EUR) % limit the position in stock ‘S’ to [-1, 0] since the % hedged option is a put option delta = min(0, max(-1, Beta(S!*EUR!, Pi!))) % update the backward hedge ratio ‘delta_old’ with ‘delta!’ % computed in the next model time; note that the use of the % future operator ‘!’ means that this ‘delta!’ is defined at % a later model time delta_old = delta! % ‘theta’ advances time at ‘T/n’ time interval theta T/n % if the absolute position taken in the stock ‘S’ has changed % from the previous one above or at 0.05, rebalance the forward % hedging portfolio ‘Pi_f’; ‘delta’ is the hedge ratio at % this model time; ‘delta_old_f’ is the hedge ratio computed % at the immediate previous model time; ‘@time’ sums up the % time that has passed so far by the ‘theta’ command if (abs(delta - delta_old_f) >= 0.05) & @time < T Pi_f = Pi_f + delta * (S * EUR – S_old) – kappa * abs( (delta_old_f - delta) * S * EUR) % update the previous discounted stock price for the forward % hedging process S_old = S * EUR % update the previous hedge ratio for the forward hedging process delta_old_f = delta end end % at option maturity T, for forwardly hedged portfolio: unwind % the position in stocks, considering transaction costs Pi_f = Pi_f - kappa * abs( (delta_old_f - 0)*S*EUR) % liquidate stock positions at option maturity delta = 0 % at option maturity T, set the backward hedging portfolio ‘Pi’ % to the values of discounted option payoffs ‘V!’; ‘V!’ is % defined in the immediate next code statement Pi = V! % discounted option maturity payoffs V = max(K - S, 0) * EUR % hedging error at maturity time between the option payoff values % ‘V’ and the forward hedging portfolio ‘Pi_f’ Error = V – Pi_f end

In the model `BetaHedge_TCost_PositionBarrier`, the ThetaML future operator `!` allows the possibility to use the variable `Pi` at the initial model time when its values are not pre-assigned. The appearance of `!` suggests that the values of the variable `Pi` are defined later in the code. We look in the subsequent code statements for the instance where the variable `Pi` is assigned some values. This occurs at the option’s maturity time `T` where `Pi` is assigned the discounted option payoff values `V!` (the variable `V!` is defined in the immediate next code statement `V = max(K - S, 0) * EUR`). This way of coding is possible because during the compilation process the compiled codes record the commands into a computational order, i.e. the compiler forces the final assignment of `Pi` to be evaluated first. This result is then overwritten by updated values when stepping backwards in time.

The advantage of using the future operator `!` here is that we can first build a backward-in-time hedging portfolio `Pi` to have the same payoff values as the European put option `V` at the option maturity time, then step backwards in time to compute a series of hedge ratios `delta` in the presence of transaction costs. Next, we set up a forward-in-time hedging portfolio `Pi_f` to have initially the same expected discounted value as `Pi`, then step forward in time and update values of the portfolio `Pi_f` using the computed hedge ratios `delta`. When reaching the option maturity time `T`, we compute the hedging errors of the forward hedging portfolio `Pi_f` (considering transaction costs) with the option payoff values `V`.

This completes our tutorial 'Hedging in ThetaML'. Further references for methods of hedging financial derivatives and hedging in incomplete markets can be found at Grau (2008)^{[1]}.

## References

- ↑ Grau, A. J., 2008, Applications of Least-Squares Regressions to Pricing and Hedging of Financial Derivatives, Dissertation, Technische Universität München. Source: http://nbnresolving.de/urn/resolver.pl?urn:nbn:de:bvb:91-diss-20071212-635889-1-9