選項

如何獲得二叉樹的所有路徑

  • April 24, 2020

我正在嘗試為基於二叉樹的奇異期權實施定價方法。我遇到的問題是我無法生成樹的所有路徑。我在 python 中有以下程式碼生成樹,但無法從中提取所有路徑。

import numpy as np
risk_free = 0.1
spot = 50
volatility = 0.4
T = 3/12
steps = 3
dt = T/steps
Up = np.exp(volatility*np.sqrt(dt))
Down = 1 / Up
p = (np.exp(risk_free*dt)-Down)/(Up-Down)
q = 1-p

dpowers = Down ** np.arange(steps,-1,-1)
upowers = Up ** np.arange(0,steps+1)
# steps + 1 because at the end we have steps + 1 prices
W = spot*dpowers*upowers

# backward valuation
for i in np.arange(steps, 0,-1):
   Si = spot*dpowers[(steps-i+1):steps+1]*upowers[0:i]
   W = np.vstack((np.append(np.repeat(0,steps-i+1),Si),W))
Tree = W.T

您可以使用以下程式碼(取自 StackOverflow)創建您想要的所有動作:

import itertools
import numpy as np
risk_free = 0.1
spot = 50
volatility = 0.4
T = 3/12
steps = 3
dt = T/steps
Up = np.exp(volatility*np.sqrt(dt))
Down = 1 / Up

paths = itertools.product([Up, Down], repeat=steps)

您可以遍歷此列表並乘以目前價格以獲得下一個價格。

引用自:https://quant.stackexchange.com/questions/53573