luphord / longstaff_schwartz Goto Github PK
View Code? Open in Web Editor NEWA Python implementation of the Longstaff-Schwartz linear regression algorithm for the evaluation of call rights an American options.
License: MIT License
A Python implementation of the Longstaff-Schwartz linear regression algorithm for the evaluation of call rights an American options.
License: MIT License
I tried to compute the American call price of an option on real data. The value of the stock price was not 1, so I tried to change the formula of the geometric Brownian motion. The simulated price(s) look nice and plausible. The problem arises when I try to use the "longstaff_schwartz_iter" & the "longstaff_schwartz" functions.
I ran the function "longstaff_schwartz" with the edited geometric Brownian motion as input. The code rises an error at the line
"continuation = fitted(x)" - TypeError: 'numpy.ndarray' object is not callable
I tried to fix this issue for several hours without success. Is there another way to compute the price of an American option with a value <> 1 with these functions? All support would be highly appreciated!
I am trying to calibrate to a volatility (ATM) curve for your Longstaff python code. Before setting it up, I was testing a variety of the base parameters, and I kept noticing this : when risk-free-rate <= 0.0, the American (call) option is always lower in price than European.
That does not make sense to me (or am I missing some fundamental theory here)?
I copied the main example and it did not run. I get an error that polynomial is not properly conditioned
can you please fix
Paste the command(s) you ran and the output.
If there was a crash, please include the traceback here.
I was interested in computing the exercise barrier for calls, after observing that the binomial module did not have such functions, so I modified the existing put
functions with the necessary call_payoff_func
and I am getting errors where all exercises are null. Any insight would be much appreciated, please see code and error below.
from longstaff_schwartz.binomial import create_binomial_model
from longstaff_schwartz.stochastic_process import GeometricBrownianMotion
from longstaff_schwartz.algorithm import longstaff_schwartz
from numpy.polynomial import Polynomial
import numpy as np
def call_payoff(spot):
return np.maximum(spot - strike, 0.0)
# Discount factor function
def constant_rate_df(t_from, t_to):
return np.exp(-riskless_rate * (t_to - t_from))
# Approximation of continuation value
def fit_quadratic(x, y):
return np.polynomial.Polynomial.fit(x, y, 2, rcond=None)
# Selection of paths to consider for exercise
# (and continuation value approxmation)
def itm(payoff, spot):
return payoff > 0
# Model parameters
timegrid = np.linspace(0, 5, 100) # timegrid for simulation
riskless_rate = 0.01 # riskless rate
sigma = 0.15 # annual volatility of underlying
simnum = 100 # number of simulated paths
# Simulate the underlying
gbm = GeometricBrownianMotion(mu=riskless_rate, sigma=sigma)
rnd = np.random.RandomState(1234)
underlying = gbm.simulate(timegrid, simnum, rnd) # x.shape == (t.size, n)
# Payoff (exercise) function
strike = 0.95
def call_payoff_func(strike):
return lambda S: np.maximum(S - strike, 0)
def american_call_exercise_barrier(mdl, strike):
exercises = []
payoff = call_payoff_func(strike)
for cnt, s, ex, opt in mdl.evaluate_american_exercisable_iter(payoff):
ex_idx = (ex >= cnt) & (ex > 0)
ex_spots = s[ex_idx]
exercises.append(ex_spots.max() if ex_idx.any() else np.nan)
exercises.reverse()
return np.array(exercises)
def american_call_exercise_barrier_fitted(mdl, strike, degree=4):
barrier = american_call_exercise_barrier(mdl, strike)
t = np.linspace(0, mdl.T, mdl.n)
ex_exists = ~np.isnan(barrier)
return Polynomial.fit(t[ex_exists], barrier[ex_exists], degree)
npv_american = longstaff_schwartz(underlying, timegrid, constant_rate_df,
fit_quadratic, call_payoff, itm)
npv_european = constant_rate_df(timegrid[0], timegrid[-1]) * call_payoff(underlying[-1]).mean()
# Exercise Boundary
mdl = create_binomial_model(sigma=sigma, r=riskless_rate, S0=strike, T=timegrid[-1], n=len(timegrid))
exercise_barrier = american_call_exercise_barrier_fitted(mdl, strike, 3)
Which gives the error:
Traceback (most recent call last):
File "c.py", line 63, in <module>
exercise_barrier = american_call_exercise_barrier_fitted(mdl, strike, 3)
File "c.py", line 55, in american_call_exercise_barrier_fitted
return Polynomial.fit(t[ex_exists], barrier[ex_exists], degree)
File "/home/user/miniconda3/lib/python3.8/site-packages/numpy/polynomial/_polybase.py", line 975, in fit
domain = pu.getdomain(x)
File "/home/user/miniconda3/lib/python3.8/site-packages/numpy/polynomial/polyutils.py", line 294, in getdomain
[x] = as_series([x], trim=False)
File "/home/user/miniconda3/lib/python3.8/site-packages/numpy/polynomial/polyutils.py", line 178, in as_series
raise ValueError("Coefficient array is empty")
ValueError: Coefficient array is empty
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.