diff --git a/QID-1143-SFEgamma/Metainfo.txt b/QID-1143-SFEgamma/Metainfo.txt index 67e88e7..ac8a28d 100644 --- a/QID-1143-SFEgamma/Metainfo.txt +++ b/QID-1143-SFEgamma/Metainfo.txt @@ -10,6 +10,8 @@ See also: SFEvanna, SFEvolga, SFEdelta, SFEvega, SFEtheta, SFEspeed, SFEcharmcal Author: Wolfgang K. Haerdle +Author[Python]: David Schulte + Submitted: Mon, November 24 2014 by Awdesch Melzer Example: 'For given [lower, upper] bound of Asset price S like [50,150] and [lower, upper] bound of time to maturity tau like [0.01, 1] a plot of the Gamma of a call option is produced.' \ No newline at end of file diff --git a/QID-1143-SFEgamma/README.md b/QID-1143-SFEgamma/README.md deleted file mode 100644 index cae231b..0000000 --- a/QID-1143-SFEgamma/README.md +++ /dev/null @@ -1,78 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFEgamma** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFEgamma - -Published in : Statistics of Financial Markets - -Description : 'Plots the Gamma of a call option as a function of the time to maturity and the asset -price.' - -Keywords : 'asset, black-scholes, call, european-option, financial, graphical representation, -greeks, option, option-price, plot' - -See also : 'SFEvanna, SFEvolga, SFEdelta, SFEvega, SFEtheta, SFEspeed, SFEcharmcall, SFEcolor, -SFEultima, SFEvomma, SFEzomma, SFEdvegadtime' - -Author : Wolfgang K. Haerdle - -Submitted : Mon, November 24 2014 by Awdesch Melzer - -Example : 'For given [lower, upper] bound of Asset price S like [50,150] and [lower, upper] bound -of time to maturity tau like [0.01, 1] a plot of the Gamma of a call option is produced.' - -``` - -![Picture1](SFEgamma-1.png) - - -### R Code: -```r - -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# install and load packages -libraries = c("lattice") -lapply(libraries, function(x) if (!(x %in% installed.packages())) { -install.packages(x) -}) -lapply(libraries, library, quietly = TRUE, character.only = TRUE) - -# parameter settings -S_min = 50 # lower bound of Asset Price -S_max = 150 # upper bound of Asset Price -tau_min = 0.01 # lower bound of Time to Maturity -tau_max = 1 # upper bound of Time to Maturity -K = 100 # exercise price -r = 0 # riskfree interest rate -sig = 0.25 # volatility -d = 0 # dividend rate -b = r - d # cost of carry -steps = 60 # steps - -tau = seq(tau_min, tau_max, by = (tau_max - tau_min)/(steps - 1)) -S = seq(S_max, S_min, by = -(S_max - S_min)/(steps - 1)) - -gamma = function(tau, S, K, r, d, sig) { - d1 = (log(S/K) + (r - d + sig^2/2) * tau)/(sig * sqrt(tau)) - return(dnorm(d1)/(S * (sig * sqrt(tau)))) -} - -mesh = outer(tau, sort(S), gamma, K = K, r = r, d = d, sig = sig) - -# Plot -wireframe(mesh, drape = T, main = expression(paste("Gamma as function of the time to maturity ", - tau, " and the asset price S")), aspect = c(1, 0.75), sub = "Strike price is 100, no interests or dividends, annual volatility is 0.25", - scales = list(arrows = FALSE, col = "black", distance = 1, tick.number = 8, - cex = 0.7, x = list(labels = round(seq(tau_min, tau_max, length = 7), 1)), - y = list(labels = round(seq(S_min, S_max, length = 7), 1))), xlab = list(expression(paste("Time to Maturity ", - tau)), rot = 30, cex = 1.2), ylab = list("Asset Price S", rot = -30, cex = 1.2), - zlab = list("Gamma", rot = 90, cex = 1.2), screen = list(z = 45, x = -70)) - -``` diff --git a/QID-1143-SFEgamma/SFEgamma.png b/QID-1143-SFEgamma/SFEgamma.png new file mode 100644 index 0000000..7ba1dfe Binary files /dev/null and b/QID-1143-SFEgamma/SFEgamma.png differ diff --git a/QID-1143-SFEgamma/SFEgamma.py b/QID-1143-SFEgamma/SFEgamma.py new file mode 100644 index 0000000..8352c98 --- /dev/null +++ b/QID-1143-SFEgamma/SFEgamma.py @@ -0,0 +1,38 @@ +import numpy as np +from scipy.stats import norm +from matplotlib import pyplot as plt +from matplotlib import cm + +# parameter settings +save_figure = True +S_min = 50 # lower bound of Asset Price +S_max = 150 # upper bound of Asset Price +tau_min = 0.05 # lower bound of Time to Maturity +tau_max = 1 # upper bound of Time to Maturity +K = 100 # exercise price +r = 0.1 # riskfree interest rate +sig = 0.25 # volatility +d = 0.2 # dividend rate +steps = 60 # steps + +tau = np.linspace(tau_min, tau_max, steps) +S = np.linspace(S_max, S_min, steps) + + +def get_gamma(tau, S, K, r, d, sig): + y = (np.log(S/K) + (r - d - sig**2/2) * tau)/(sig * np.sqrt(tau)) + + return np.exp(-d*tau)*norm.pdf(y+sig*np.sqrt(tau))/(S * sig * np.sqrt(tau)) + + +X, Y = np.meshgrid(tau, S) +fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) +ax.plot_surface(X, Y, get_gamma(X, Y, K, r, d, sig), cmap=cm.viridis) +ax.set_title('Dependence of Gamma on Stock Price and Time to Maturity') +ax.set_xlabel('Time to Maturity') +ax.set_ylabel('Stock Price') +ax.set_zlabel('Gamma') +plt.show() + +if save_figure: + fig.savefig('SFEgamma.png', transparent=True) diff --git a/QID-1389-SFEBSCopt2/SFEBSCopt2.py b/QID-1389-SFEBSCopt2/SFEBSCopt2.py new file mode 100644 index 0000000..7ea041a --- /dev/null +++ b/QID-1389-SFEBSCopt2/SFEBSCopt2.py @@ -0,0 +1,17 @@ +import numpy as np +from scipy.stats import norm + +# input variables +K = 100 +S = 98 +r = 1/20 +b = 1/20 +tau = 20/52 +sig = 1/5 + +# main computation +y = (np.log(S/K) + (b - (sig**2)/2) * tau)/(sig * np.sqrt(tau)) +c = np.exp(-(r - b) * tau) * S * norm.cdf(y + sig * np.sqrt(tau)) - np.exp(-r * tau) * K * norm.cdf(y) + +# output +print("The call price is {}".format(c)) \ No newline at end of file diff --git a/QID-1414-SFEtheta/Metainfo.txt b/QID-1414-SFEtheta/Metainfo.txt index 693b30e..23af864 100644 --- a/QID-1414-SFEtheta/Metainfo.txt +++ b/QID-1414-SFEtheta/Metainfo.txt @@ -10,6 +10,8 @@ See also: SFEvanna, SFEvolga, SFEdelta, SFEgamma, SFEvega, SFEspeed, SFEcharmcal Author: Ekaterina Ignatieva, Ying Chen, Christian M. Hafner +Author[Python]: David Schulte + Submitted: Sun, December 04 2011 by Dedy Dwi Prastyo Example: 'For given [lower, upper] bound of Asset price S like [50,150] and [lower, upper] bound of time to maturity tau like [0.05, 1] a plot of the Theta of a call option is produced.' \ No newline at end of file diff --git a/QID-1414-SFEtheta/README.md b/QID-1414-SFEtheta/README.md deleted file mode 100644 index 85d98f0..0000000 --- a/QID-1414-SFEtheta/README.md +++ /dev/null @@ -1,90 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFEtheta** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFEtheta - -Published in : Statistics of Financial Markets - -Description : 'Plots the Theta of a call option as a function of the time to maturity and the asset -price.' - -Keywords : 'asset, black-scholes, call, european-option, financial, graphical representation, -greeks, option, option-price, plot' - -See also : 'SFEvanna, SFEvolga, SFEdelta, SFEgamma, SFEvega, SFEspeed, SFEcharmcall, SFEcolor, -SFEultima, SFEvomma, SFEzomma, SFEdvegadtime' - -Author : Ekaterina Ignatieva, Ying Chen, Christian M. Hafner - -Submitted : Sun, December 04 2011 by Dedy Dwi Prastyo - -Example : 'For given [lower, upper] bound of Asset price S like [50,150] and [lower, upper] bound -of time to maturity tau like [0.05, 1] a plot of the Theta of a call option is produced.' - -``` - -![Picture1](SFEtheta-1.png) - - -### R Code: -```r - -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# install and load packages -libraries = c("lattice") -lapply(libraries, function(x) if (!(x %in% installed.packages())) { -install.packages(x) -}) -lapply(libraries, library, quietly = TRUE, character.only = TRUE) - -# parameter settings -S_min = 50 # lower bound of Asset Price -S_max = 150 # upper bound of Asset Price -tau_min = 0.05 # lower bound of Time to Maturity -tau_max = 1 # upper bound of Time to Maturity -K = 100 # exercise price -r = 0 # interest rate -sig = 0.25 # volatility -d = 0 # dividend rate -b = r - d # cost of carry -steps = 60 # steps - -meshgrid = function(a, b) { - list(x = outer(b * 0, a, FUN = "+"), y = outer(b, a * 0, FUN = "+")) -} -first = meshgrid(seq(tau_min, tau_max, (tau_max - tau_min)/(steps - 1)), seq(tau_min, - tau_max, (tau_max - tau_min)/(steps - 1))) - -tau = first$x -dump = first$y -second = meshgrid(seq(S_max, S_min, -(S_max - S_min)/(steps - 1)), seq(S_max, S_min, - -(S_max - S_min)/(steps - 1))) - -dump2 = second$x -S = second$y - - -d1 = (log(S/K) + (r - d + sig^2/2) * tau)/(sig * sqrt(tau)) -y = (log(S/K) + (r - d - sig^2/2) * tau)/(sig * sqrt(tau)) -theta = -((exp(-d * tau) * dnorm(d1) * S * sig)/(2 * sqrt(tau))) - (r * K * exp(-r * - tau) * pnorm(y)) - -# Plot -title = bquote(expression(paste("Strike price is ", .(K), ", interest rate is ", - .(r), ", dividend rate is ", .(d), ", annual volatility is ", .(sig)))) -wireframe(theta ~ tau * S, drape = T, ticktype = "detailed", main = expression(paste("Theta as function of the time to maturity ", - tau, " and the asset price S")), sub = title, scales = list(arrows = FALSE, - col = "black", distance = 1, tick.number = 8, cex = 0.7, x = list(labels = round(seq(tau_min, - tau_max, length = 11), 1)), y = list(labels = round(seq(S_min, S_max, length = 11), - 1))), xlab = list(expression(paste("Time to Maturity ", tau)), rot = 30, - cex = 1.2), ylab = list("Asset Price S", rot = -40, cex = 1.2), zlab = list("Theta", - cex = 1.1)) - -``` diff --git a/QID-1414-SFEtheta/SFEtheta.png b/QID-1414-SFEtheta/SFEtheta.png new file mode 100644 index 0000000..6fecd3d Binary files /dev/null and b/QID-1414-SFEtheta/SFEtheta.png differ diff --git a/QID-1414-SFEtheta/SFEtheta.py b/QID-1414-SFEtheta/SFEtheta.py new file mode 100644 index 0000000..51b1bca --- /dev/null +++ b/QID-1414-SFEtheta/SFEtheta.py @@ -0,0 +1,38 @@ +import numpy as np +from scipy.stats import norm +from matplotlib import pyplot as plt +from matplotlib import cm + +# parameter settings +save_figure = True +S_min = 50 # lower bound of Asset Price +S_max = 150 # upper bound of Asset Price +tau_min = 0.05 # lower bound of Time to Maturity +tau_max = 1 # upper bound of Time to Maturity +K = 100 # exercise price +r = 0.1 # riskfree interest rate +sig = 0.25 # volatility +d = 0.2 # dividend rate +steps = 60 # steps + +tau = np.linspace(tau_min, tau_max, steps) +S = np.linspace(S_max, S_min, steps) + + +def get_theta(tau, S, K, r, d, sig): + y = (np.log(S/K) + (r - d - sig**2/2) * tau)/(sig * np.sqrt(tau)) + + return -np.exp(-d*tau)*sig*S/(2*np.sqrt(tau))*norm.pdf(y+sig*np.sqrt(tau)) - r*K*np.exp(-r*tau)*norm.cdf(y) + + +X, Y = np.meshgrid(tau, S) +fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) +ax.plot_surface(X, Y, get_theta(X, Y, K, r, d, sig), cmap=cm.viridis) +ax.set_title('Dependence of Theta on Stock Price and Time to Maturity') +ax.set_xlabel('Time to Maturity') +ax.set_ylabel('Stock Price') +ax.set_zlabel('Theta') +plt.show() + +if save_figure: + fig.savefig('SFEtheta.png', transparent=True) diff --git a/QID-1428-SFEvega/Metainfo.txt b/QID-1428-SFEvega/Metainfo.txt index a39b513..4873bdb 100644 --- a/QID-1428-SFEvega/Metainfo.txt +++ b/QID-1428-SFEvega/Metainfo.txt @@ -10,6 +10,8 @@ See also: SFEvanna, SFEvolga, SFEdelta, SFEgamma, SFEtheta, SFEspeed, SFEcharmca Author: Ying Chen, Christian M. Hafner +Author[Python]: David Schulte + Submitted: Tue, July 01 2014 by Petra Burdejova Example: 'For given [lower, upper] bound of Asset price S like [50,150] and [lower, upper] bound of time to maturity tau like [0.01, 1] a plot of the Vega of a call option is produced.' \ No newline at end of file diff --git a/QID-1428-SFEvega/README.md b/QID-1428-SFEvega/README.md deleted file mode 100644 index f9e6631..0000000 --- a/QID-1428-SFEvega/README.md +++ /dev/null @@ -1,87 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFEvega** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFEvega - -Published in : Statistics of Financial Markets - -Description : 'Plots the Vega of a call option as a function of the time to maturity and the asset -price.' - -Keywords : 'asset, black-scholes, call, european-option, financial, graphical representation, -greeks, option, option-price, plot' - -See also : 'SFEvanna, SFEvolga, SFEdelta, SFEgamma, SFEtheta, SFEspeed, SFEcharmcall, SFEcolor, -SFEultima, SFEvomma, SFEzomma, SFEdvegadtime' - -Author : Ying Chen, Christian M. Hafner - -Submitted : Tue, July 01 2014 by Petra Burdejova - -Example : 'For given [lower, upper] bound of Asset price S like [50,150] and [lower, upper] bound -of time to maturity tau like [0.01, 1] a plot of the Vega of a call option is produced.' - -``` - -![Picture1](SFEvega-1.png) - - -### R Code: -```r - -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# install and load packages -libraries = c("lattice") -lapply(libraries, function(x) if (!(x %in% installed.packages())) { -install.packages(x) -}) -lapply(libraries, library, quietly = TRUE, character.only = TRUE) - -# parameter settings -S_min = 50 # lower bound of Asset Price -S_max = 150 # upper bound of Asset Price -tau_min = 0.01 # lower bound of Time to Maturity -tau_max = 1 # upper bound of Time to Maturity -K = 100 # exercise price -r = 0 # interest rate -sig = 0.25 # volatility -d = 0 # dividend rate -b = r - d # cost of carry -steps = 60 # steps - -meshgrid = function(a, b) { - list(x = outer(b * 0, a, FUN = "+"), y = outer(b, a * 0, FUN = "+")) -} -first = meshgrid(seq(tau_min, tau_max, (tau_max - tau_min)/(steps - 1)), seq(tau_min, - tau_max, (tau_max - tau_min)/(steps - 1))) - -tau = first$x -dump = first$y -second = meshgrid(seq(S_max, S_min, -(S_max - S_min)/(steps - 1)), seq(S_max, S_min, - -(S_max - S_min)/(steps - 1))) - -dump2 = second$x -S = second$y - -d1 = (log(S/K) + (r - d - sig^2/2) * tau)/(sig * sqrt(tau)) -Vega = S * exp(-d * tau) * dnorm(d1) * sqrt(tau) - -# Plot -title = bquote(expression(paste("Strike price is ", .(K), ", interest rate is ", - .(r), ", dividend rate is ", .(d), ", annual volatility is ", .(sig)))) -wireframe(Vega ~ tau * S, drape = T, ticktype = "detailed", main = expression(paste("Vega as function of the time to maturity ", - tau, " and the asset price S")), sub = title, scales = list(arrows = FALSE, - col = "black", distance = 1, tick.number = 8, cex = 0.7, x = list(labels = round(seq(tau_min, - tau_max, length = 11), 1)), y = list(labels = round(seq(S_min, S_max, length = 11), - 1))), xlab = list(expression(paste("Time to Maturity ", tau)), rot = 30, - cex = 1.2), ylab = list("Asset Price S", rot = -40, cex = 1.2), zlab = list("Vega", - cex = 1.1)) - -``` diff --git a/QID-1428-SFEvega/SFEvega.png b/QID-1428-SFEvega/SFEvega.png new file mode 100644 index 0000000..08cafc3 Binary files /dev/null and b/QID-1428-SFEvega/SFEvega.png differ diff --git a/QID-1428-SFEvega/SFEvega.py b/QID-1428-SFEvega/SFEvega.py new file mode 100644 index 0000000..10ac3d3 --- /dev/null +++ b/QID-1428-SFEvega/SFEvega.py @@ -0,0 +1,38 @@ +import numpy as np +from scipy.stats import norm +from matplotlib import pyplot as plt +from matplotlib import cm + +# parameter settings +save_figure = True +S_min = 50 # lower bound of Asset Price +S_max = 150 # upper bound of Asset Price +tau_min = 0.05 # lower bound of Time to Maturity +tau_max = 1 # upper bound of Time to Maturity +K = 100 # exercise price +r = 0.1 # riskfree interest rate +sig = 0.25 # volatility +d = 0.2 # dividend rate +steps = 60 # steps + +tau = np.linspace(tau_min, tau_max, steps) +S = np.linspace(S_max, S_min, steps) + + +def get_vega(tau, S, K, r, d, sig): + y = (np.log(S/K) + (r - d - sig**2/2) * tau)/(sig * np.sqrt(tau)) + + return np.exp(-d*tau)*S*np.sqrt(tau)*norm.pdf(y+sig*np.sqrt(tau)) + + +X, Y = np.meshgrid(tau, S) +fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) +ax.plot_surface(X, Y, get_vega(X, Y, K, r, d, sig), cmap=cm.viridis) +ax.set_title('Dependence of Vega on Stock Price and Time to Maturity') +ax.set_xlabel('Time to Maturity') +ax.set_ylabel('Stock Price') +ax.set_zlabel('Vega') +plt.show() + +if save_figure: + fig.savefig('SFEvega.png', transparent=True) diff --git a/QID-1971-SFEvanna/Metainfo.txt b/QID-1971-SFEvanna/Metainfo.txt index baa789e..c6afb69 100644 --- a/QID-1971-SFEvanna/Metainfo.txt +++ b/QID-1971-SFEvanna/Metainfo.txt @@ -10,6 +10,8 @@ See also: SFEvolga, SFEdelta, SFEgamma, SFEvega, SFEtheta, SFEspeed, SFEcharmcal Author: Andreas Golle, Awdesch Melzer +Author[Python]: David Schulte + Submitted: Tue, June 17 2014 by Franziska Schulz Example: 'For given [lower, upper] bound of Asset price S like [50,150] and [lower, upper] bound of time to maturity tau like [0.05, 1] a plot of the Theta of a call option is produced.' \ No newline at end of file diff --git a/QID-1971-SFEvanna/README.md b/QID-1971-SFEvanna/README.md deleted file mode 100644 index 5ea38b0..0000000 --- a/QID-1971-SFEvanna/README.md +++ /dev/null @@ -1,91 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFEvanna** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFEvanna - -Published in : Statistics of Financial Markets - -Description : 'Plots the Vanna of a call option as a function of the time to maturity and the asset -price.' - -Keywords : 'asset, black-scholes, call, european-option, financial, graphical representation, -greeks, option, option-price, plot' - -See also : 'SFEvolga, SFEdelta, SFEgamma, SFEvega, SFEtheta, SFEspeed, SFEcharmcall, SFEcolor, -SFEultima, SFEvomma, SFEzomma, SFEdvegadtime' - -Author : Andreas Golle, Awdesch Melzer - -Submitted : Tue, June 17 2014 by Franziska Schulz - -Example : 'For given [lower, upper] bound of Asset price S like [50,150] and [lower, upper] bound -of time to maturity tau like [0.05, 1] a plot of the Theta of a call option is produced.' - -``` - -![Picture1](SFEvanna-1.png) - - -### R Code: -```r - -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# install and load packages -libraries = c("lattice") -lapply(libraries, function(x) if (!(x %in% installed.packages())) { -install.packages(x) -}) -lapply(libraries, library, quietly = TRUE, character.only = TRUE) - -# parameter settings -# parameter settings -S_min = 50 # lower bound of Asset Price -S_max = 150 # upper bound of Asset Price -tau_min = 0.01 # lower bound of Time to Maturity -tau_max = 1 # upper bound of Time to Maturity -k = 100 # exercise price -r = 0 # interest rate -sig = 0.25 # volatility -tau = 0.5 # time to maturity -q = 0 # dividend rate -b = r - q # cost of carry -steps = 100 # steps - -meshgrid = function(a, b) { - list(x = outer(b * 0, a, FUN = "+"), y = outer(b, a * 0, FUN = "+")) -} - -first = meshgrid(seq(tau_min, tau_max, -(tau_min - tau_max)/(steps - 1)), seq(tau_min, tau_max, -(tau_min - tau_max)/(steps - - 1))) - -tau = first$x -dump = first$y - -second = meshgrid(seq(S_min, S_max, -(S_min - S_max)/(steps - 1)), seq(S_min, S_max, -(S_min - S_max)/(steps - 1))) - -dump2 = second$x -S = second$y - -d1 = (log(S/k) + (r - q - sig^2/2) * tau)/(sig * sqrt(tau)) -d2 = d1 - sig * sqrt(tau) -Vanna = -(exp((b - r) * tau) * d2)/sig * dnorm(d1) - -# Plot -title = bquote(expression(paste("Strike price is ", .(k), ", interest rate is ", - .(r), ", dividend rate is ", .(q), ", annual volatility is ", .(sig)))) -wireframe(Vanna ~ tau * S, drape = T, ticktype = "detailed", main = expression(paste("Vanna as function of the time to maturity ", - tau, " and the asset price S")), sub = title, scales = list(arrows = FALSE, - col = "black", distance = 1, tick.number = 8, cex = 0.7, x = list(labels = round(seq(tau_min, - tau_max, length = 11), 1)), y = list(labels = round(seq(S_min, S_max, length = 11), - 1))), xlab = list(expression(paste("Time to Maturity ", tau)), rot = 30, - cex = 1.2), ylab = list("Asset Price S", rot = -40, cex = 1.2), zlab = list("Vanna", - cex = 1.1)) - -``` diff --git a/QID-1971-SFEvanna/SFEvanna.png b/QID-1971-SFEvanna/SFEvanna.png new file mode 100644 index 0000000..7abd60b Binary files /dev/null and b/QID-1971-SFEvanna/SFEvanna.png differ diff --git a/QID-1971-SFEvanna/SFEvanna.py b/QID-1971-SFEvanna/SFEvanna.py new file mode 100644 index 0000000..0dae8f2 --- /dev/null +++ b/QID-1971-SFEvanna/SFEvanna.py @@ -0,0 +1,38 @@ +import numpy as np +from scipy.stats import norm +from matplotlib import pyplot as plt +from matplotlib import cm + +# parameter settings +save_figure = True +S_min = 50 # lower bound of Asset Price +S_max = 150 # upper bound of Asset Price +tau_min = 0.05 # lower bound of Time to Maturity +tau_max = 1 # upper bound of Time to Maturity +K = 100 # exercise price +r = 0.1 # riskfree interest rate +sig = 0.35 # volatility +d = 0.2 # dividend rate +steps = 60 # steps + +tau = np.linspace(tau_min, tau_max, steps) +S = np.linspace(S_max, S_min, steps) + + +def get_vanna(tau, S, K, r, d, sig): + y = (np.log(S/K) + (r - d - sig**2/2) * tau)/(sig * np.sqrt(tau)) + d1 = y+sig*np.sqrt(tau) + + return -np.exp(-d*tau)*y/sig*norm.pdf(d1) + +X, Y = np.meshgrid(tau, S) +fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) +ax.plot_surface(X, Y, get_vanna(X, Y, K, r, d, sig), cmap=cm.viridis) +ax.set_title('Dependence of Vanna on Stock Price and Time to Maturity') +ax.set_xlabel('Time to Maturity') +ax.set_ylabel('Stock Price') +ax.set_zlabel('Vanna') +plt.show() + +if save_figure: + fig.savefig('SFEvanna.png', transparent=True) diff --git a/QID-3144-SFEdvegadtime/Metainfo.txt b/QID-3144-SFEdvegadtime/Metainfo.txt index 3427e2b..9fbce05 100644 --- a/QID-3144-SFEdvegadtime/Metainfo.txt +++ b/QID-3144-SFEdvegadtime/Metainfo.txt @@ -19,5 +19,6 @@ Keywords: Author: - Andreas Golle - Awdesch Melzer +Author[Python]: David Schulte Submitted: Thu, June 04 2015 by Lukas Borke Example: 'User inputs [lower, upper] bound of Asset price S like [50,150], [lower, upper] bound of time to maturity tau like [0.01, 1], then plot of the Vega of a Call option is given.' \ No newline at end of file diff --git a/QID-3144-SFEdvegadtime/README.md b/QID-3144-SFEdvegadtime/README.md deleted file mode 100644 index 8daf20f..0000000 --- a/QID-3144-SFEdvegadtime/README.md +++ /dev/null @@ -1,87 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFEdvegadtime** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFEdvegadtime - -Published in : Statistics of Financial Markets - -Description : 'Plots the DvegaDtime of a call/put option (DvegaDtime or Vega bleed). DvegaDtime is -divided by 36500 to reflect a one-day move and a one-percentage point change in volatility.' - -Keywords : 'asset, black-scholes, call, financial, graphical representation, greeks, option, -option-price, plot, put, returns, stock-price, vega, volatility' - -Author : Andreas Golle, Awdesch Melzer - -Submitted : Thu, June 04 2015 by Lukas Borke - -Example : 'User inputs [lower, upper] bound of Asset price S like [50,150], [lower, upper] bound of -time to maturity tau like [0.01, 1], then plot of the Vega of a Call option is given.' - -``` - -![Picture1](SFEdvegadtime-1.png) - - -### R Code: -```r - -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# install and load packages -libraries = c("lattice") -lapply(libraries, function(x) if (!(x %in% installed.packages())) {install.packages(x)} ) -lapply(libraries, library, quietly = TRUE, character.only = TRUE) - -# parameter settings -s1 = 50 # lower bound of Asset Price -s2 = 150 # upper bound of Asset Price -t1 = 0.05 # lower bound of Time to Maturity -t2 = 1 # upper bound of Time to Maturity -K = 100 # exercise price -r = 0.01 # interest rate -sig = 0.35 # volatility -d = 0 # dividend rate -b = r - d # cost of carry -steps = 60 - -meshgrid = function(a, b) { - list(x = outer(b * 0, a, FUN = "+"), y = outer(b, a * 0, FUN = "+")) -} - -first = meshgrid(seq(t1, t2, -(t1 - t2)/(steps - 1)), seq(t1, t2, -(t1 - t2)/(steps - 1))) - -tau = first$x -dump = first$y - -second = meshgrid(seq(s1, s2, -(s1 - s2)/(steps - 1)), seq(s1, s2, -(s1 - s2)/(steps - 1))) - -dump2 = second$x -S = second$y - -# Black Scholes -d1 = (log(S/K) + (r - d - sig^2/2) * tau)/(sig * sqrt(tau)) -d2 = d1 - sig * sqrt(tau) -# Greeks -Vega = S * exp((b - r) * tau) * dnorm(d1) * sqrt(tau) -DvegaDtime = Vega * (r - b + b * d1/(sig * sqrt(tau)) - (1 + d1 * d2)/(2 * tau)) - -# plot -title = bquote(expression(paste("Strike price is ", .(K), ", interest rate is ", .(r), ", dividend rate is ", .(d), ", annual volatility is ", .(sig)))) - -wireframe((DvegaDtime/36500) ~ tau * S, drape = T, ticktype = "detailed", main = expression(paste("DvegaDtime as function of the time to maturity ", - tau, " and the asset price S")), sub = title, scales = list(arrows = FALSE, - col = "black", distance = 1, tick.number = 8, cex = 0.7, x = list(labels = round(seq(t1, - t2, length = 11), 1)), y = list(labels = round(seq(s1, s2, length = 11), - 1)), z = list(labels = round(seq(min(DvegaDtime/36500), max(DvegaDtime/36500), - length = 11), 4))), xlab = list(expression(paste("Time to Maturity ", - tau)), rot = 30, cex = 1.2), ylab = list("Asset Price S", rot = -40, cex = 1.2), - zlab = list("DvegaDtime", rot = 95, cex = 1.1)) - -``` diff --git a/QID-3144-SFEdvegadtime/SFEDvegaDtime.png b/QID-3144-SFEdvegadtime/SFEDvegaDtime.png new file mode 100644 index 0000000..d09cccd Binary files /dev/null and b/QID-3144-SFEdvegadtime/SFEDvegaDtime.png differ diff --git a/QID-3144-SFEdvegadtime/SFEDvegaDtime.py b/QID-3144-SFEdvegadtime/SFEDvegaDtime.py new file mode 100644 index 0000000..d6424f8 --- /dev/null +++ b/QID-3144-SFEdvegadtime/SFEDvegaDtime.py @@ -0,0 +1,41 @@ +import numpy as np +from scipy.stats import norm +from matplotlib import pyplot as plt +from matplotlib import cm + +# parameter settings +save_figure = True +S_min = 50 # lower bound of Asset Price +S_max = 150 # upper bound of Asset Price +tau_min = 0.05 # lower bound of Time to Maturity +tau_max = 1 # upper bound of Time to Maturity +K = 100 # exercise price +r = 0.1 # riskfree interest rate +sig = 0.35 # volatility +d = 0.2 # dividend rate +steps = 60 # steps + +tau = np.linspace(tau_min, tau_max, steps) +S = np.linspace(S_max, S_min, steps) + + +def get_dvega_dtime(tau, S, K, r, d, sig): + y = (np.log(S/K) + (r - d - sig**2/2) * tau)/(sig * np.sqrt(tau)) + d1 = y+sig*np.sqrt(tau) + vega = np.exp(-d * tau) * S * np.sqrt(tau) * norm.pdf(d1) + b = r - d + + return vega*(d+b*d1/(sig*np.sqrt(tau))-(1+d1*y)/(2*tau)) + + +X, Y = np.meshgrid(tau, S) +fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) +ax.plot_surface(X, Y, get_dvega_dtime(X, Y, K, r, d, sig), cmap=cm.viridis) +ax.set_title('Dependence of Color on Stock Price and Time to Maturity') +ax.set_xlabel('Time to Maturity') +ax.set_ylabel('Stock Price') +ax.set_zlabel('DvegaDtime') +plt.show() + +if save_figure: + fig.savefig('SFEDvegaDtime.png', transparent=True) diff --git a/QID-3166-SFEspeed/Metainfo.txt b/QID-3166-SFEspeed/Metainfo.txt index d7aefb2..12d6590 100644 --- a/QID-3166-SFEspeed/Metainfo.txt +++ b/QID-3166-SFEspeed/Metainfo.txt @@ -3,5 +3,6 @@ Published in: Statistics of Financial Markets Description: 'Plots the speed of a call option as a function of the time to maturity and the asset price.' Keywords: asset, black-scholes, call, european-option, financial, graphical representation, greeks, option, option-price, plot Author: Andreas Golle, Awdesch Melzer +Author[Python]: David Schulte Submitted: Mon, June 08 2015 by Lukas Borke Example: 'User inputs [lower, upper] bound of asset price S like [50,150], [lower, upper] bound of time to maturity tau like [0.05, 1], then the plot of the speed of a call option is given.' \ No newline at end of file diff --git a/QID-3166-SFEspeed/README.md b/QID-3166-SFEspeed/README.md deleted file mode 100644 index e261e08..0000000 --- a/QID-3166-SFEspeed/README.md +++ /dev/null @@ -1,86 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFEspeed** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFEspeed - -Published in : Statistics of Financial Markets - -Description : 'Plots the speed of a call option as a function of the time to maturity and the asset -price.' - -Keywords : 'asset, black-scholes, call, european-option, financial, graphical representation, -greeks, option, option-price, plot' - -Author : Andreas Golle, Awdesch Melzer - -Submitted : Mon, June 08 2015 by Lukas Borke - -Example : 'User inputs [lower, upper] bound of asset price S like [50,150], [lower, upper] bound of -time to maturity tau like [0.05, 1], then the plot of the speed of a call option is given.' - -``` - -![Picture1](SFEspeed-1.png) - - -### R Code: -```r - -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# install and load packages -libraries = c("lattice") -lapply(libraries, function(x) if (!(x %in% installed.packages())) { - install.packages(x) -}) -lapply(libraries, library, quietly = TRUE, character.only = TRUE) - -# parameter settings -s1 = 50 # lower bound of Asset Price -s2 = 150 # upper bound of Asset Price -t1 = 0.05 # lower bound of Time to Maturity -t2 = 1 # upper bound of Time to Maturity -K = 100 # exercise price -r = 0.01 # interest rate -sig = 0.35 # volatility -d = 0 # dividend rate -b = r - d # cost of carry -steps = 60 - -meshgrid = function(a, b) { - list(x = outer(b * 0, a, FUN = "+"), y = outer(b, a * 0, FUN = "+")) -} - -first = meshgrid(seq(t1, t2, -(t1 - t2)/(steps - 1)), seq(t1, t2, -(t1 - t2)/(steps - 1))) -tau = first$x -dump = first$y - -second = meshgrid(seq(s1, s2, -(s1 - s2)/(steps - 1)), seq(s1, s2, -(s1 - s2)/(steps - 1))) -dump2 = second$x -S = second$y - -# Black-Scholes formula for the option price and the speed -d1 = (log(S/K) + (r - d + sig^2/2) * tau)/(sig * sqrt(tau)) -gamma = dnorm(d1)/(S * (sig * sqrt(tau))) -speed = -gamma/S * (1 + d1/sig * sqrt(tau)) - -# plot -title = bquote(expression(paste("Strike price is ", .(K), ", interest rate is ", - .(r), ", dividend rate is ", .(d), ", annual volatility is ", .(sig)))) - -wireframe(speed ~ tau * S, drape = T, ticktype = "detailed", main = expression(paste("Speed as function of the time to maturity ", - tau, " and the asset price S")), sub = title, scales = list(arrows = FALSE, - col = "black", distance = 1, tick.number = 8, cex = 0.7, x = list(labels = round(seq(t1, - t2, length = 11), 1)), y = list(labels = round(seq(s1, s2, length = 11), - 1)), z = list(labels = round(seq(min(speed), max(speed), length = 11), - 4))), xlab = list(expression(paste("Time to Maturity ", tau)), rot = 30, - cex = 1.2), ylab = list("Asset Price S", rot = -40, cex = 1.2), zlab = list("Speed", - rot = 95, cex = 1.1)) - -``` diff --git a/QID-3166-SFEspeed/SFEspeed.png b/QID-3166-SFEspeed/SFEspeed.png new file mode 100644 index 0000000..a170550 Binary files /dev/null and b/QID-3166-SFEspeed/SFEspeed.png differ diff --git a/QID-3166-SFEspeed/SFEspeed.py b/QID-3166-SFEspeed/SFEspeed.py new file mode 100644 index 0000000..217de6f --- /dev/null +++ b/QID-3166-SFEspeed/SFEspeed.py @@ -0,0 +1,39 @@ +import numpy as np +from scipy.stats import norm +from matplotlib import pyplot as plt +from matplotlib import cm + +# parameter settings +save_figure = True +S_min = 50 # lower bound of Asset Price +S_max = 150 # upper bound of Asset Price +tau_min = 0.05 # lower bound of Time to Maturity +tau_max = 1 # upper bound of Time to Maturity +K = 100 # exercise price +r = 0.1 # riskfree interest rate +sig = 0.35 # volatility +d = 0.2 # dividend rate +steps = 60 # steps + +tau = np.linspace(tau_min, tau_max, steps) +S = np.linspace(S_max, S_min, steps) + + +def get_speed(tau, S, K, r, d, sig): + y = (np.log(S/K) + (r - d - sig**2/2) * tau)/(sig * np.sqrt(tau)) + d1 = y+sig*np.sqrt(tau) + gamma = np.exp(-d*tau)*norm.pdf(d1)/(S * sig * np.sqrt(tau)) + + return -gamma/S*(1+d1/(sig*np.sqrt(tau))) + +X, Y = np.meshgrid(tau, S) +fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) +ax.plot_surface(X, Y, get_speed(X, Y, K, r, d, sig), cmap=cm.viridis) +ax.set_title('Dependence of Speed on Stock Price and Time to Maturity') +ax.set_xlabel('Time to Maturity') +ax.set_ylabel('Stock Price') +ax.set_zlabel('Speed') +plt.show() + +if save_figure: + fig.savefig('SFEspeed.png', transparent=True) diff --git a/QID-3205-SFEcharmcall/Metainfo.txt b/QID-3205-SFEcharmcall/Metainfo.txt index 7694b75..ffd60df 100644 --- a/QID-3205-SFEcharmcall/Metainfo.txt +++ b/QID-3205-SFEcharmcall/Metainfo.txt @@ -10,6 +10,8 @@ Author: Andreas Golle, Awdesch Melzer Author[Matlab]: Andreas Golle +Author[Python]: David Schulte + Submitted: Wed, June 10 2015 by Lukas Borke Input[Matlab]: 'S_min: Lower Bound of Asset Price S, tau_min: Lower Bound of Time to Maturity tau, S_max: Upper Bound of Asset Price S, tau_max: Upper Bound of Time to Maturity tau' diff --git a/QID-3205-SFEcharmcall/README.md b/QID-3205-SFEcharmcall/README.md deleted file mode 100644 index 76094ae..0000000 --- a/QID-3205-SFEcharmcall/README.md +++ /dev/null @@ -1,144 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFEcharmcall** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFEcharmcall - -Published in : Statistics of Financial Markets - -Description : 'Plots the Charm of a call option (Charm or Delta bleed). Charm is divided by 365 to -reflect the effect of a single day passing by.' - -Keywords : 'asset, black-scholes, call, delta, european-option, financial, graphical -representation, greeks, maturity, option, option-price, plot, price' - -Author : Andreas Golle, Awdesch Melzer - -Author[Matlab] : Andreas Golle - -Submitted : Wed, June 10 2015 by Lukas Borke - -Input[Matlab] : 'S_min: Lower Bound of Asset Price S, tau_min: Lower Bound of Time to Maturity tau, -S_max: Upper Bound of Asset Price S, tau_max: Upper Bound of Time to Maturity tau' - -Output[Matlab] : plot of the Charm of a call option - -Example : 'User inputs [lower, upper] bound of asset price S like [50,150], [lower, upper] bound of -time to maturity tau like [0.01, 1], then the plot of the Delta of a call option is given.' - -``` - -![Picture1](SFEcharmcall-1.png) - -![Picture2](SFEcharmcall_m.png) - - -### R Code: -```r - -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# install and load packages -libraries = c("lattice") -lapply(libraries, function(x) if (!(x %in% installed.packages())) {install.packages(x)} ) -lapply(libraries, library, quietly = TRUE, character.only = TRUE) - -# parameter settings -s1 = 50 # lower bound of Asset Price -s2 = 150 # upper bound of Asset Price -t1 = 0.05 # lower bound of Time to Maturity -t2 = 1 # upper bound of Time to Maturity -K = 100 # exercise price -r = 0.01 # interest rate -sig = 0.35 # volatility -d = 0 # dividend rate -b = r - d # cost of carry -steps = 60 - -meshgrid = function(a, b) { - list(x = outer(b * 0, a, FUN = "+"), y = outer(b, a * 0, FUN = "+")) -} - -first = meshgrid(seq(t1, t2, -(t1 - t2)/(steps - 1)), seq(t1, t2, -(t1 - t2)/(steps - 1))) -tau = first$x -dump = first$y -second = meshgrid(seq(s1, s2, -(s1 - s2)/(steps - 1)), seq(s1, s2, -(s1 - s2)/(steps - 1))) - -dump2 = second$x -S = second$y - -# Black Scholes formula -d1 = (log(S/K) + (r - d + sig^2/2) * tau)/(sig * sqrt(tau)) -d2 = d1 - sig * sqrt(tau) - -delta = exp((b - r) * tau) * pnorm(d1) -charm = -exp((b - r) * tau) * c(dnorm(d1) * (b/(sig * sqrt(tau)) - d2/(2 * tau)) + (b - r) * pnorm(d1)) - -# plot -title = bquote(expression(paste("Strike price is ", .(K), ", interest rate is ", .(r), ", dividend rate is ", .(q), ", annual volatility is ", .(sig)))) - -wireframe(charm ~ tau * S, drape = T, ticktype = "detailed", - main = expression(paste("Charm as function of the time to maturity ", tau, " and the asset price S")), - sub = title, scales = list(arrows = FALSE, col = "black", distance = 1, tick.number = 8, cex = 0.7, x = list(labels = round(seq(t1, t2, length = 11), 1)), y = list(labels = round(seq(s1, s2, length = 11), 1))), - xlab = list(expression(paste("Time to Maturity ", tau)), rot = 30, cex = 1.2), - ylab = list("Asset Price S", rot = -40, cex = 1.2), zlab = list("Charm", cex = 1.1)) - -``` - -### MATLAB Code: -```matlab - -% user inputs parameters - -disp('Please input [lower, upper] bound of Asset price S as: [50,150]') ; -disp(' '); -para = input('[lower, upper] bound of S ='); -while length(para) < 2 - disp('Not enough input arguments. Please input in 1*2 vector form like [50,150] or [50 150]'); - para=input('[lower, upper] bound of S='); -end -S_min = para(1); -S_max = para(2); - -disp(' '); -disp('Please input [lower, upper] bound of time to maturity tau as: [0.01, 1]'); -disp(' '); -para2 = input('[lower, upper] bound of tau ='); -while length(para2) < 2 - disp('Not enough input arguments. Please input in 1*2 vector form like [0.01, 1] or [0.01 1]'); - para2=input('[lower, upper] bound of tau ='); -end -tau_min = para2(1); -tau_max = para2(2); - -% main computation - -K = 100; %exercise price -r = 0.01; % interest rate -sig = 0.35; % volatility -d = 0; % dividend rate -b = r-d; %cost of carry -steps = 60; - -[tau,dump] = meshgrid([tau_min:(tau_max-tau_min)/(steps-1):tau_max]); -[dump2,S] = meshgrid([S_max:-(S_max-S_min)/(steps-1):S_min]); - -d1 = (log(S/K)+(r-d+sig^2/2).*tau)./(sig.*sqrt(tau)); -d2 = d1 - sig.*sqrt(tau); -delta = exp((b-r).*tau).*normcdf(d1); -charm = -exp((b-r).*tau).*[normpdf(d1).*(b./(sig.*sqrt(tau)) - d2./(2.*tau) ) + (b - r).*normcdf(d1)]; - - -% plot - -mesh(tau,S,charm/365); -title('Charm call option') -ylabel('Asset Price S'); -xlabel('Time to Maturity tau'); - -``` diff --git a/QID-3205-SFEcharmcall/SFEcharmcall.png b/QID-3205-SFEcharmcall/SFEcharmcall.png new file mode 100644 index 0000000..1fb3bdb Binary files /dev/null and b/QID-3205-SFEcharmcall/SFEcharmcall.png differ diff --git a/QID-3205-SFEcharmcall/SFEcharmcall.py b/QID-3205-SFEcharmcall/SFEcharmcall.py new file mode 100644 index 0000000..c92e976 --- /dev/null +++ b/QID-3205-SFEcharmcall/SFEcharmcall.py @@ -0,0 +1,38 @@ +import numpy as np +from scipy.stats import norm +from matplotlib import pyplot as plt +from matplotlib import cm + +# parameter settings +save_figure = True +S_min = 50 # lower bound of Asset Price +S_max = 150 # upper bound of Asset Price +tau_min = 0.05 # lower bound of Time to Maturity +tau_max = 1 # upper bound of Time to Maturity +K = 100 # exercise price +r = 0.1 # riskfree interest rate +sig = 0.35 # volatility +d = 0.2 # dividend rate +steps = 60 # steps + +tau = np.linspace(tau_min, tau_max, steps) +S = np.linspace(S_max, S_min, steps) + + +def get_charmcall(tau, S, K, r, d, sig): + y = (np.log(S/K) + (r - d - sig**2/2) * tau)/(sig * np.sqrt(tau)) + d1 = y+sig*np.sqrt(tau) + + return -np.exp(-d*tau)*(norm.pdf(d1)*((r-d)/(sig*np.sqrt(tau))-y/(2*tau))-d*norm.cdf(d1)) + +X, Y = np.meshgrid(tau, S) +fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) +ax.plot_surface(X, Y, get_charmcall(X, Y, K, r, d, sig), cmap=cm.viridis) +ax.set_title('Dependence of Charm on Stock Price and Time to Maturity') +ax.set_xlabel('Time to Maturity') +ax.set_ylabel('Stock Price') +ax.set_zlabel('Charm') +plt.show() + +if save_figure: + fig.savefig('SFEcharmcall.png', transparent=True) diff --git a/QID-3223-SFEDeltahedgingLogic/Metainfo.txt b/QID-3223-SFEDeltahedgingLogic/Metainfo.txt index d80be58..1ddc941 100644 --- a/QID-3223-SFEDeltahedgingLogic/Metainfo.txt +++ b/QID-3223-SFEDeltahedgingLogic/Metainfo.txt @@ -4,5 +4,6 @@ Description: 'Simulates 2 stock price paths, including the Black-Scholes Delta d Keywords: black-scholes, brownian-motion, delta, dependence, financial, geometric-brownian-motion, graphical representation, hedging, plot, simulation, stock-price, wiener-process See also: SFEDeltaHedging, SFEDeltaHedging, SFEDeltahedgingdepend, SFSdeltahedging Author: Juliane Tomzik, Gagandeep Singh, Christoph Jährling +Author[Python]: David Schulte Submitted: Thu, June 11 2015 by Lukas Borke Example: Plots of 2 stock price paths and Delta dependencies on steps and stock prices. \ No newline at end of file diff --git a/QID-3223-SFEDeltahedgingLogic/README.md b/QID-3223-SFEDeltahedgingLogic/README.md deleted file mode 100644 index 1af387a..0000000 --- a/QID-3223-SFEDeltahedgingLogic/README.md +++ /dev/null @@ -1,88 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFEDeltahedgingLogic** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFEDeltahedgingLogic - -Published in : Statistics of Financial Markets - -Description : 'Simulates 2 stock price paths, including the Black-Scholes Delta depending on n=50 -time steps and the stock price S1/S2 for given exercise price K=100, initial stock price S0=98, -volatility sig=0.2, interest rate r=0.05, and the time interval (T-t0) = 20 weeks. In the second -part it plots delta dependencies on steps and stock prices.' - -Keywords : 'black-scholes, brownian-motion, delta, dependence, financial, -geometric-brownian-motion, graphical representation, hedging, plot, simulation, stock-price, -wiener-process' - -See also : SFEDeltaHedging, SFEDeltaHedging, SFEDeltahedgingdepend, SFSdeltahedging - -Author : Juliane Tomzik, Gagandeep Singh, Christoph Jährling - -Submitted : Thu, June 11 2015 by Lukas Borke - -Example : Plots of 2 stock price paths and Delta dependencies on steps and stock prices. - -``` - -![Picture1](SFEDeltahedgingLogic-1.png) - - -### R Code: -```r - -rm(list = ls(all = TRUE)) -graphics.off() - -# parameter settings -n = 50 # periods (steps) -K = 100 # exercise price -S0 = 98 # initial stock price -sig = 0.2 # volatility (uniform distributed on 0.1 to 0.5) -r = 0.05 # interest rate (uniform distributed on 0 to 0.1) -t0 = 6/52 # current time (1 week = 1/52) -T = 26/52 # maturity -dt = (T - t0)/n # period between steps n -t = seq(t0, T, l = n) # T-t0 divided in n intervals -tau = T - t # time to maturity - -# Standard Wiener Process for path of the stock price S -Wt1 = c(0, sqrt(dt) * cumsum(rnorm(n - 1, 0, 1))) -S1 = S0 * exp((r - 0.5 * sig^2) * t + sig * Wt1) - -# 1st path -y1 = (log(S1/K) + (r - sig^2/2) * tau)/(sig * sqrt(tau)) -delta1 = pnorm(y1 + sig * sqrt(tau)) - -# 2nd path -Wt2 = c(0, sqrt(dt) * cumsum(rnorm(n - 1, 0, 1))) -S2 = S0 * exp((r - 0.5 * sig^2) * t + sig * Wt2) -y2 = (log(S2/K) + (r - sig^2/2) * tau)/(sig * sqrt(tau)) -delta2 = pnorm(y2 + sig * sqrt(tau)) - -# 3 Plots -par(mfrow = c(3, 1)) - -# Plot S(t) vs. tau -plot(S1 ~ seq(1, n), main = "Stock Price Paths", xlab = "Steps", ylab = "Stock price", - ylim = c(min(S1, S2), max(S1, S2)), type = "l", col = "red") -lines(S2 ~ seq(1, n), col = "blue") -abline(h = K, col = 1) - -# Plot Delta vs. tau -plot(delta1 ~ seq(1, n), main = "Dependence of Delta on Steps", xlab = "Steps", - ylab = "Delta", ylim = c(0, 1), type = "o", col = "red") -lines(delta2 ~ seq(1, n), type = "o", col = "blue") - -# Plot Delta vs. S(t) -plot(delta1 ~ S1, main = "Dependence of Delta on Stock Price", xlab = "Stock price", - ylab = "Delta", xlim = c(min(S1, S2), max(S1, S2)), ylim = c(0, 1), type = "p", - col = "red") -points(delta2 ~ S2, col = "blue") -abline(lm(delta1 ~ S1), col = "red") -abline(lm(delta2 ~ S2), col = "blue") - -``` diff --git a/QID-3223-SFEDeltahedgingLogic/SFEDeltaHedgingLogic.png b/QID-3223-SFEDeltahedgingLogic/SFEDeltaHedgingLogic.png new file mode 100644 index 0000000..23e9b07 Binary files /dev/null and b/QID-3223-SFEDeltahedgingLogic/SFEDeltaHedgingLogic.png differ diff --git a/QID-3223-SFEDeltahedgingLogic/SFEDeltaHedgingLogic.py b/QID-3223-SFEDeltahedgingLogic/SFEDeltaHedgingLogic.py new file mode 100644 index 0000000..ef2711a --- /dev/null +++ b/QID-3223-SFEDeltahedgingLogic/SFEDeltaHedgingLogic.py @@ -0,0 +1,76 @@ +import numpy as np +from scipy.stats import norm +from matplotlib import pyplot as plt + +# parameter settings +save_figure = True +n = 50 # periods (steps) +K = 100 # exercise price +S0 = 98 # initial stock price +sig = 0.2 # volatility +r = 0.05 # interest rate +t0 = 6/52 # current time (1 week = 1/52) +T = 26/52 # maturity +dt = (T - t0)/n # period between steps n +t = np.linspace(t0, T, n) # T-t0 divided in n intervals +tau = T - t # time to maturity + +# Standard Wiener Process for path of the stock price S +Wt1 = np.concatenate((np.array([0]), np.sqrt(dt)*np.cumsum(np.random.normal(size=n-1)))) +S1 = S0 * np.exp((r - 0.5 * sig**2) * t + sig * Wt1) + +# 1st path +with np.errstate(divide='ignore'): + y1 = (np.log(S1/K) + (r - sig**2/2) * tau)/(sig * np.sqrt(tau)) +delta1 = norm.cdf(y1 + sig * np.sqrt(tau)) + +# 2nd path +Wt2 = np.concatenate((np.zeros(1), np.sqrt(dt)*np.cumsum(np.random.normal(size=n-1)))) +S2 = S0 * np.exp((r - 0.5 * sig**2) * t + sig * Wt2) +with np.errstate(divide='ignore'): + y1 = (np.log(S2/K) + (r - sig**2/2) * tau)/(sig * np.sqrt(tau)) +delta2 = norm.cdf(y1 + sig * np.sqrt(tau)) + +# 3 Plots +fig = plt.figure() + +# Plot S(t) vs. tau +ax = fig.add_subplot(3,1,1) +ax.plot(S1, c='r') +ax.plot(S2, c='b') +ax.axhline(K, c='black', linestyle='dashed') +ax.set_title('Stock Price Paths') +ax.set_xlabel('Steps') +ax.set_ylabel('Stock price') +ax.legend(('S1', 'S2', 'K')) + +# Plot Delta vs. tau +ax = fig.add_subplot(3,1,2) +ax.plot(delta1, c='r') +ax.plot(delta2, c='b') +ax.set_title('Dependence of Delta on Steps') +ax.set_xlabel('Steps') +ax.set_ylabel('Delta') +ax.legend(('Delta 1', 'Delta 2')) + +# Plot Delta vs. S(t) +ax = fig.add_subplot(3,1,3) +ax.scatter(S1, delta1, c='r', marker='x') +ax.scatter(S2, delta2, c='b', marker='x') + +# Linear regression +b, m = np.polynomial.polynomial.polyfit(S1, delta1, 1) +ax.plot(S1, b + m * S1, '-', c='r', linewidth=0.5) +b, m = np.polynomial.polynomial.polyfit(S2, delta2, 1) +ax.plot(S2, b + m * S2, '-', c='b', linewidth=0.5) + +ax.set_title('Dependence of Delta on Stock Price') +ax.set_xlabel('Stock Price') +ax.set_ylabel('Delta') +ax.legend(('Delta 1', 'Delta 2')) + +fig.tight_layout() +plt.show() + +if save_figure: + fig.savefig('SFEDeltaHedgingLogic.png', transparent=True) diff --git a/QID-3368-SFEcolor/Metainfo.txt b/QID-3368-SFEcolor/Metainfo.txt index ee1fb65..c3a5453 100644 --- a/QID-3368-SFEcolor/Metainfo.txt +++ b/QID-3368-SFEcolor/Metainfo.txt @@ -4,6 +4,7 @@ Description: 'Plots the Color of a call option (Color or Gamma bleed or DgammaDt Keywords: asset, black-scholes, call, european-option, financial, graphical representation, greeks, option, option-price, plot Author: Andreas Golle, Awdesch Melzer Author[Matlab]: Ying Chen, Christian M. Hafner, Andreas Golle +Author[Python]: David Schulte Submitted: Tue, July 14 2015 by quantomas Submitted[Matlab]: Tue, August 30 2016 by Xiu Xu Example: 'User inputs [lower, upper] bound of asset price S like [50,150], [lower, upper] bound of time to maturity tau like [0.05, 1], then the plot of the Color of a call option is given.' \ No newline at end of file diff --git a/QID-3368-SFEcolor/README.md b/QID-3368-SFEcolor/README.md deleted file mode 100644 index ed1dbce..0000000 --- a/QID-3368-SFEcolor/README.md +++ /dev/null @@ -1,85 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/index.php?p=info) - -## [Visit QuantNet](http://quantlet.de/) **SFEcolor** [Visit QuantNet 2.0](http://quantlet.de/d3/ia) - -```yaml - -Name of QuantLet : SFEcolor - -Published in : Statistics of Financial Markets - -Description : 'Plots the Color of a call option (Color or Gamma bleed or DgammaDtime) as a function -of the time to maturity and the asset price. Color is divided by 365 to reflect the effect of a -single day passing by.' - -Keywords : 'asset, black-scholes, call, european-option, financial, graphical representation, -greeks, option, option-price, plot' - -Author : Andreas Golle, Awdesch Melzer - -Submitted : Tue, July 14 2015 by quantomas - -Example : 'User inputs [lower, upper] bound of asset price S like [50,150], [lower, upper] bound of -time to maturity tau like [0.05, 1], then the plot of the Color of a call option is given.' - -``` - -![Picture1](SFEcolor-1.png) - - -```r -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# install and load packages -libraries = c("lattice") -lapply(libraries, function(x) if (!(x %in% installed.packages())) { - install.packages(x) -}) -lapply(libraries, library, quietly = TRUE, character.only = TRUE) - -# parameter settings -s1 = 50 # lower bound of Asset Price -s2 = 150 # upper bound of Asset Price -t1 = 0.05 # lower bound of Time to Maturity -t2 = 1 # upper bound of Time to Maturity -K = 100 # exercise price -r = 0.01 # interest rate -sig = 0.35 # volatility -d = 0 # dividend rate -b = r - d # cost of carry -steps = 60 - -meshgrid = function(a, b) { - list(x = outer(b * 0, a, FUN = "+"), y = outer(b, a * 0, FUN = "+")) -} - -first = meshgrid(seq(t1, t2, -(t1 - t2)/(steps - 1)), seq(t1, t2, -(t1 - t2)/(steps - 1))) -tau = first$x -dump = first$y - -second = meshgrid(seq(s1, s2, -(s1 - s2)/(steps - 1)), seq(s1, s2, -(s1 - s2)/(steps - 1))) -dump2 = second$x -S = second$y - -# Black-Scholes formula for the option price and the color -d1 = (log(S/K) + (r - d + sig^2/2) * tau)/(sig * sqrt(tau)) -d2 = d1 - sig * sqrt(tau) -gamma = dnorm(d1)/(S * (sig * sqrt(tau))) -color = gamma * (r - b + b * d1/(sig * sqrt(tau)) + (1 - d1 * d2)/(2 * tau)) - -# plot -title = bquote(expression(paste("Strike price is ", .(K), ", interest rate is ", - .(r), ", dividend rate is ", .(d), ", annual volatility is ", .(sig)))) - -wireframe((color/365) ~ tau * S, drape = T, ticktype = "detailed", main = expression(paste("Color as function of the time to maturity ", - tau, " and the asset price S")), sub = title, scales = list(arrows = FALSE, - col = "black", distance = 1, tick.number = 8, cex = 0.7, x = list(labels = round(seq(t1, - t2, length = 11), 1)), y = list(labels = round(seq(s1, s2, length = 11), - 1)), z = list(labels = round(seq(min(color/365), max(color/365), length = 11), - 4))), xlab = list(expression(paste("Time to Maturity ", tau)), rot = 30, - cex = 1.2), ylab = list("Asset Price S", rot = -40, cex = 1.2), zlab = list("Color", - cex = 1.1)) -``` diff --git a/QID-3368-SFEcolor/SFEcolor.png b/QID-3368-SFEcolor/SFEcolor.png new file mode 100644 index 0000000..7a90e88 Binary files /dev/null and b/QID-3368-SFEcolor/SFEcolor.png differ diff --git a/QID-3368-SFEcolor/SFEcolor.py b/QID-3368-SFEcolor/SFEcolor.py new file mode 100644 index 0000000..30b9cbf --- /dev/null +++ b/QID-3368-SFEcolor/SFEcolor.py @@ -0,0 +1,40 @@ +import numpy as np +from scipy.stats import norm +from matplotlib import pyplot as plt +from matplotlib import cm + +# parameter settings +save_figure = True +S_min = 50 # lower bound of Asset Price +S_max = 150 # upper bound of Asset Price +tau_min = 0.05 # lower bound of Time to Maturity +tau_max = 1 # upper bound of Time to Maturity +K = 100 # exercise price +r = 0.1 # riskfree interest rate +sig = 0.35 # volatility +d = 0.2 # dividend rate +steps = 60 # steps + +tau = np.linspace(tau_min, tau_max, steps) +S = np.linspace(S_max, S_min, steps) + + +def get_color(tau, S, K, r, d, sig): + y = (np.log(S/K) + (r - d - sig**2/2) * tau)/(sig * np.sqrt(tau)) + d1 = y+sig*np.sqrt(tau) + gamma = np.exp(-d * tau) * norm.pdf(d1) / (S * sig * np.sqrt(tau)) + b = r - d + + return gamma*(d+b*d1/(sig*np.sqrt(tau))+(1-d1*y)/(2*tau)) + +X, Y = np.meshgrid(tau, S) +fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) +ax.plot_surface(X, Y, get_color(X, Y, K, r, d, sig), cmap=cm.viridis) +ax.set_title('Dependence of Color on Stock Price and Time to Maturity') +ax.set_xlabel('Time to Maturity') +ax.set_ylabel('Stock Price') +ax.set_zlabel('Color') +plt.show() + +if save_figure: + fig.savefig('SFEcolor.png', transparent=True) diff --git a/QID-3369-SFEultima/Metainfo.txt b/QID-3369-SFEultima/Metainfo.txt index 770a6e6..da50c3e 100644 --- a/QID-3369-SFEultima/Metainfo.txt +++ b/QID-3369-SFEultima/Metainfo.txt @@ -3,5 +3,6 @@ Published in: Statistics of Financial Markets Description: 'Plots the Ultima of a call option (Ultima or DvommaDvol) as a function of the time to maturity and the asset price. Ultima is divided by 1,000,000 to reflect a one-percentage point change in volatility.' Keywords: asset, black-scholes, call, european-option, financial, graphical representation, greeks, option, option-price, plot Author: Andreas Golle, Awdesch Melzer +Author[Python]: David Schulte Submitted: Tue, July 14 2015 by quantomas Example: 'User inputs [lower, upper] bound of asset price S like [50,150], [lower, upper] bound of time to maturity tau like [0.05, 1], then the plot of the Ultima of a call option is given.' \ No newline at end of file diff --git a/QID-3369-SFEultima/README.md b/QID-3369-SFEultima/README.md deleted file mode 100644 index 50a4174..0000000 --- a/QID-3369-SFEultima/README.md +++ /dev/null @@ -1,88 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFEultima** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFEultima - -Published in : Statistics of Financial Markets - -Description : 'Plots the Ultima of a call option (Ultima or DvommaDvol) as a function of the time -to maturity and the asset price. Ultima is divided by 1,000,000 to reflect a one-percentage point -change in volatility.' - -Keywords : 'asset, black-scholes, call, european-option, financial, graphical representation, -greeks, option, option-price, plot' - -Author : Andreas Golle, Awdesch Melzer - -Submitted : Tue, July 14 2015 by quantomas - -Example : 'User inputs [lower, upper] bound of asset price S like [50,150], [lower, upper] bound of -time to maturity tau like [0.05, 1], then the plot of the Ultima of a call option is given.' - -``` - -![Picture1](SFEultima-1.png) - - -### R Code: -```r -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# install and load packages -libraries = c("lattice") -lapply(libraries, function(x) if (!(x %in% installed.packages())) { - install.packages(x) -}) -lapply(libraries, library, quietly = TRUE, character.only = TRUE) - -# parameter settings -s1 = 50 # lower bound of Asset Price -s2 = 150 # upper bound of Asset Price -t1 = 0.05 # lower bound of Time to Maturity -t2 = 1 # upper bound of Time to Maturity -K = 100 # exercise price -r = 0.01 # interest rate -sig = 0.35 # volatility -d = 0 # dividend rate -b = r - d # cost of carry -steps = 60 - -meshgrid = function(a, b) { - list(x = outer(b * 0, a, FUN = "+"), y = outer(b, a * 0, FUN = "+")) -} - -first = meshgrid(seq(t1, t2, -(t1 - t2)/(steps - 1)), seq(t1, t2, -(t1 - t2)/(steps - 1))) -tau = first$x -dump = first$y - -second = meshgrid(seq(s1, s2, -(s1 - s2)/(steps - 1)), seq(s1, s2, -(s1 - s2)/(steps - 1))) -dump2 = second$x -S = second$y - -# Black-Scholes formula for the option price and the ultima -d1 = (log(S/K) + (r - d - sig^2/2) * tau)/(sig * sqrt(tau)) -d2 = d1 - sig * sqrt(tau) -vega = S * exp(-d * tau) * dnorm(d1) * sqrt(tau) -vomma = vega * (d1 * d2/sig) -ultima = vomma * (1/sig) * (d1 * d2 - d1/d2 - d2/d1 - 1) - -# plot -title = bquote(expression(paste("Strike price is ", .(K), ", interest rate is ", - .(r), ", dividend rate is ", .(d), ", annual volatility is ", .(sig)))) - -wireframe((ultima/1e+06) ~ tau * S, drape = T, ticktype = "detailed", main = expression(paste("Ultima as function of the time to maturity ", - tau, " and the asset price S")), sub = title, scales = list(arrows = FALSE, - col = "black", distance = 1, tick.number = 8, cex = 0.7, x = list(labels = round(seq(t1, - t2, length = 11), 1)), y = list(labels = round(seq(s1, s2, length = 11), - 1)), z = list(labels = round(seq(min(ultima/1e+06), max(ultima/1e+06), - length = 11), 4))), xlab = list(expression(paste("Time to Maturity ", - tau)), rot = 30, cex = 1.2), ylab = list("Asset Price S", rot = -40, cex = 1.2), - zlab = list("Ultima", rot = 95, cex = 1.1)) - -``` diff --git a/QID-3369-SFEultima/SFEultima.png b/QID-3369-SFEultima/SFEultima.png new file mode 100644 index 0000000..322592e Binary files /dev/null and b/QID-3369-SFEultima/SFEultima.png differ diff --git a/QID-3369-SFEultima/SFEultima.py b/QID-3369-SFEultima/SFEultima.py new file mode 100644 index 0000000..11c780d --- /dev/null +++ b/QID-3369-SFEultima/SFEultima.py @@ -0,0 +1,40 @@ +import numpy as np +from scipy.stats import norm +from matplotlib import pyplot as plt +from matplotlib import cm + +# parameter settings +save_figure = True +S_min = 50 # lower bound of Asset Price +S_max = 150 # upper bound of Asset Price +tau_min = 0.05 # lower bound of Time to Maturity +tau_max = 1 # upper bound of Time to Maturity +K = 100 # exercise price +r = 0.1 # riskfree interest rate +sig = 0.35 # volatility +d = 0.2 # dividend rate +steps = 60 # steps + +tau = np.linspace(tau_min, tau_max, steps) +S = np.linspace(S_max, S_min, steps) + + +def get_ultima(tau, S, K, r, d, sig): + y = (np.log(S/K) + (r - d - sig**2/2) * tau)/(sig * np.sqrt(tau)) + d1 = y+sig*np.sqrt(tau) + vega = np.exp(-d*tau)*S*np.sqrt(tau)*norm.pdf(d1) + vomma = vega*y*d1/sig + + return vomma/sig*(y*d1-d1/y-y/d1-1) + +X, Y = np.meshgrid(tau, S) +fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) +ax.plot_surface(X, Y, get_ultima(X, Y, K, r, d, sig), cmap=cm.viridis) +ax.set_title('Dependence of Ultima on Stock Price and Time to Maturity') +ax.set_xlabel('Time to Maturity') +ax.set_ylabel('Stock Price') +ax.set_zlabel('Ultima') +plt.show() + +if save_figure: + fig.savefig('SFEultima.png', transparent=True) diff --git a/QID-3371-SFEvomma/Metainfo.txt b/QID-3371-SFEvomma/Metainfo.txt index e5be1ed..6a95eae 100644 --- a/QID-3371-SFEvomma/Metainfo.txt +++ b/QID-3371-SFEvomma/Metainfo.txt @@ -3,5 +3,6 @@ Published in: Statistics of Financial Markets Description: 'Plots the Vomma of a call option (Vomma or Volga or DvegaDvol) as a function of the time to maturity and the asset price. Vomma is divided by 10000 to reflect a one-percentage point move in volatility.' Keywords: asset, black-scholes, call, european-option, financial, graphical representation, greeks, option, option-price, plot Author: Andreas Golle, Awdesch Melzer +Author[Python]: David Schulte Submitted: Tue, July 14 2015 by quantomas Example: 'User inputs [lower, upper] bound of asset price S like [50,150], [lower, upper] bound of time to maturity tau like [0.05, 1], then the plot of the Vomma of a call option is given.' \ No newline at end of file diff --git a/QID-3371-SFEvomma/README.md b/QID-3371-SFEvomma/README.md deleted file mode 100644 index 5b4c21d..0000000 --- a/QID-3371-SFEvomma/README.md +++ /dev/null @@ -1,86 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFEvomma** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFEvomma - -Published in : Statistics of Financial Markets - -Description : 'Plots the Vomma of a call option (Vomma or Volga or DvegaDvol) as a function of the -time to maturity and the asset price. Vomma is divided by 10000 to reflect a one-percentage point -move in volatility.' - -Keywords : 'asset, black-scholes, call, european-option, financial, graphical representation, -greeks, option, option-price, plot' - -Author : Andreas Golle, Awdesch Melzer - -Submitted : Tue, July 14 2015 by quantomas - -Example : 'User inputs [lower, upper] bound of asset price S like [50,150], [lower, upper] bound of -time to maturity tau like [0.05, 1], then the plot of the Vomma of a call option is given.' - -``` - -![Picture1](SFEvomma-1.png) - - -### R Code: -```r -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# install and load packages -libraries = c("lattice") -lapply(libraries, function(x) if (!(x %in% installed.packages())) { - install.packages(x) -}) -lapply(libraries, library, quietly = TRUE, character.only = TRUE) - -# parameter settings -s1 = 50 # lower bound of Asset Price -s2 = 150 # upper bound of Asset Price -t1 = 0.05 # lower bound of Time to Maturity -t2 = 1 # upper bound of Time to Maturity -K = 100 # exercise price -r = 0.01 # interest rate -sig = 0.35 # volatility -d = 0 # dividend rate -b = r - d # cost of carry -steps = 60 - -meshgrid = function(a, b) { - list(x = outer(b * 0, a, FUN = "+"), y = outer(b, a * 0, FUN = "+")) -} - -first = meshgrid(seq(t1, t2, -(t1 - t2)/(steps - 1)), seq(t1, t2, -(t1 - t2)/(steps - 1))) -tau = first$x -dump = first$y - -second = meshgrid(seq(s1, s2, -(s1 - s2)/(steps - 1)), seq(s1, s2, -(s1 - s2)/(steps - 1))) -dump2 = second$x -S = second$y - -# Black-Scholes formula for the option price and the vomma -d1 = (log(S/K) + (r - d - sig^2/2) * tau)/(sig * sqrt(tau)) -d2 = d1 - sig * sqrt(tau) -vega = S * exp(-d * tau) * dnorm(d1) * sqrt(tau) -vomma = vega * (d1 * d2/sig) - -# plot -title = bquote(expression(paste("Strike price is ", .(K), ", interest rate is ", - .(r), ", dividend rate is ", .(d), ", annual volatility is ", .(sig)))) - -wireframe((vomma/10000) ~ tau * S, drape = T, ticktype = "detailed", main = expression(paste("Vomma as function of the time to maturity ", - tau, " and the asset price S")), sub = title, scales = list(arrows = FALSE, col = "black", - distance = 1, tick.number = 8, cex = 0.7, x = list(labels = round(seq(t1, t2, - length = 11), 1)), y = list(labels = round(seq(s1, s2, length = 11), 1)), - z = list(labels = round(seq(min(vomma/10000), max(vomma/10000), length = 11), - 4))), xlab = list(expression(paste("Time to Maturity ", tau)), rot = 30, - cex = 1.2), ylab = list("Asset Price S", rot = -40, cex = 1.2), zlab = list("Vomma", - rot = 95, cex = 1.1)) -``` diff --git a/QID-3371-SFEvomma/SFEvomma.png b/QID-3371-SFEvomma/SFEvomma.png new file mode 100644 index 0000000..2e9da85 Binary files /dev/null and b/QID-3371-SFEvomma/SFEvomma.png differ diff --git a/QID-3371-SFEvomma/SFEvomma.py b/QID-3371-SFEvomma/SFEvomma.py new file mode 100644 index 0000000..0db21f4 --- /dev/null +++ b/QID-3371-SFEvomma/SFEvomma.py @@ -0,0 +1,39 @@ +import numpy as np +from scipy.stats import norm +from matplotlib import pyplot as plt +from matplotlib import cm + +# parameter settings +save_figure = True +S_min = 50 # lower bound of Asset Price +S_max = 150 # upper bound of Asset Price +tau_min = 0.05 # lower bound of Time to Maturity +tau_max = 1 # upper bound of Time to Maturity +K = 100 # exercise price +r = 0.1 # riskfree interest rate +sig = 0.35 # volatility +d = 0.2 # dividend rate +steps = 60 # steps + +tau = np.linspace(tau_min, tau_max, steps) +S = np.linspace(S_max, S_min, steps) + + +def get_vomma(tau, S, K, r, d, sig): + y = (np.log(S/K) + (r - d - sig**2/2) * tau)/(sig * np.sqrt(tau)) + d1 = y+sig*np.sqrt(tau) + vega = np.exp(-d*tau)*S*np.sqrt(tau)*norm.pdf(d1) + + return vega*y*d1/sig + +X, Y = np.meshgrid(tau, S) +fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) +ax.plot_surface(X, Y, get_vomma(X, Y, K, r, d, sig), cmap=cm.viridis) +ax.set_title('Dependence of Vomma on Stock Price and Time to Maturity') +ax.set_xlabel('Time to Maturity') +ax.set_ylabel('Stock Price') +ax.set_zlabel('Vomma') +plt.show() + +if save_figure: + fig.savefig('SFEvomma.png', transparent=True) diff --git a/QID-3373-SFEBMuller/Metainfo.txt b/QID-3373-SFEBMuller/Metainfo.txt index ff8c29f..a42da62 100644 --- a/QID-3373-SFEBMuller/Metainfo.txt +++ b/QID-3373-SFEBMuller/Metainfo.txt @@ -8,6 +8,8 @@ Keywords: box-muller, distribution, graphical representation, normal-distributio Author: Brenda López Cabrera +Author[Python]: David Schulte + Submitted: Thu, July 16 2015 by quantomas Submitted[Matlab]: Tue, May 17 2016 by Christoph Schult diff --git a/QID-3373-SFEBMuller/SFEBMuller.py b/QID-3373-SFEBMuller/SFEBMuller.py new file mode 100644 index 0000000..0a8e61b --- /dev/null +++ b/QID-3373-SFEBMuller/SFEBMuller.py @@ -0,0 +1,34 @@ +import numpy as np +from matplotlib import pyplot as plt + +# main computation +save_figure = True +n = 10000 +u1 = np.random.uniform(size=n) +u2 = np.random.uniform(size=n) +theta = 2 * np.pi * u2 +rho = np.sqrt(-2 * np.log(u1)) +zeta1 = rho * np.cos(theta) +zeta2 = rho * np.sin(theta) + +#First Moments of the generated distributions +v1 = np.var(zeta1) +v2 = np.var(zeta2) +m1 = np.mean(zeta1) +m2 = np.mean(zeta1) +print("Normal distribution 1:") +print("Mean: {} \tVariance {}".format(m1,v1)) +print("Normal distribution 2:") +print("Mean: {} \tVariance {}".format(m2,v2)) + +# output +fig = plt.figure() +ax = fig.add_subplot() +ax.scatter(zeta1, zeta2, s=3) +ax.set_title('Numbers generated using Box-Muller Algorithm') +ax.set_xlabel('$Z_1$') +ax.set_ylabel('$Z_2$') +plt.show() + +if save_figure: + fig.savefig('SFEBMuller.png', transparent=True) diff --git a/QID-3373-SFEBMuller/SFEBMuller0.png b/QID-3373-SFEBMuller/SFEBMuller0.png new file mode 100644 index 0000000..1bb1442 Binary files /dev/null and b/QID-3373-SFEBMuller/SFEBMuller0.png differ diff --git a/QID-3375-SFErandu/Metainfo.txt b/QID-3375-SFErandu/Metainfo.txt index 2ded6e5..46f29ed 100644 --- a/QID-3375-SFErandu/Metainfo.txt +++ b/QID-3375-SFErandu/Metainfo.txt @@ -4,5 +4,6 @@ Description: 'Generates uniform random numbers using RANDU generator and produce Keywords: graphical representation, hyperplain, plot, random, random-number-generation, randu, scatterplot, simulation, uniform See also: SFEfibonacci, SFErangen1, SFErangen1, SFErangen2, SFErangen2 Author: Awdesch Melzer +Author[Python]: David Schulte Submitted: Thu, July 16 2015 by quantomas Example: 'A plot is provided for the following parameter values: n=10000, a=2^16+3, M=2^31, seed=1298324.' \ No newline at end of file diff --git a/QID-3375-SFErandu/README.md b/QID-3375-SFErandu/README.md deleted file mode 100644 index c2f85e6..0000000 --- a/QID-3375-SFErandu/README.md +++ /dev/null @@ -1,66 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFErandu** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFErandu - -Published in : Statistics of Financial Markets - -Description : 'Generates uniform random numbers using RANDU generator and produces a 3d plot of -generated numbers where the hyperplains can be visible.' - -Keywords : 'graphical representation, hyperplain, plot, random, random-number-generation, randu, -scatterplot, simulation, uniform' - -See also : SFEfibonacci, SFErangen1, SFErangen1, SFErangen2, SFErangen2 - -Author : Awdesch Melzer - -Submitted : Thu, July 16 2015 by quantomas - -Example : 'A plot is provided for the following parameter values: n=10000, a=2^16+3, M=2^31, -seed=1298324.' - -``` - -![Picture1](SFErandu-1.png) - - -### R Code: -```r -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# install and load packages -libraries = c("TeachingDemos", "lattice") -lapply(libraries, function(x) if (!(x %in% installed.packages())) { - install.packages(x) -}) -lapply(libraries, library, quietly = TRUE, character.only = TRUE) - -# parameter settings -n = 10000 # sample size -a = 2^16 + 3 -M = 2^31 -seed = 1298324 # makes sure that the same numbers are generated each time the quantlet is executed -y = NULL - -# main computation -y[1] = seed -i = 2 -while (i <= n) { - y[i] = (a * y[i - 1])%%M - i = i + 1 -} -y = y/M - -# output -rotate.cloud(y[3:n] ~ y[1:(n - 2)] + y[2:(n - 1)], xlab = "", ylab = "", zlab = "", - type = "p", scales = list(arrows = FALSE, col = "black", distance = 1, - tick.number = 8, cex = 0.7, x = list(labels = round(seq(0, 1, length = 10), - 1)), y = list(labels = round(seq(0, 1, length = 10), 1)), z = list(labels = round(seq(0, 1, length = 10), 1))), col = "black", pch = 20, cex = 0.1) -``` diff --git a/QID-3375-SFErandu/SFErandu.gif b/QID-3375-SFErandu/SFErandu.gif new file mode 100644 index 0000000..9928790 Binary files /dev/null and b/QID-3375-SFErandu/SFErandu.gif differ diff --git a/QID-3375-SFErandu/SFErandu.py b/QID-3375-SFErandu/SFErandu.py new file mode 100644 index 0000000..5b36997 --- /dev/null +++ b/QID-3375-SFErandu/SFErandu.py @@ -0,0 +1,38 @@ +import numpy as np +from matplotlib import pyplot as plt +import matplotlib.animation as animation + +# parameter settings +save_figure = True # Generate a gif of the 3D plot? +n = 1000 +a = 1229 +b = 1 +M = 2048 +seed = 12 + +# main computation +y = [seed] +for i in range(1, n+1): + y.append((a * y[-1] + b)%M) # modulus + +y = np.array(y) +y = y/M + +#output +fig = plt.figure() +ax = fig.add_subplot(projection='3d') +ax.scatter(y[:-2], y[1:-1], y[2:]) +ax.set_title('Numbers generated using RANDU') +ax.set_xlabel('$U_{i-2}$') +ax.set_ylabel('$U_{i-1}$') +ax.set_zlabel('$U_i$') +plt.show() + +# Generate gif +if save_figure: + def rotate(angle): + ax.view_init(azim=angle) + + rot_animation = animation.FuncAnimation(fig, rotate, frames=np.arange(0, 362, 2), interval=100) + rot_animation.save('SFErandu.gif', dpi=80) + diff --git a/QID-3376-SFErangen1/Metainfo.txt b/QID-3376-SFErangen1/Metainfo.txt index e70d287..14de830 100644 --- a/QID-3376-SFErangen1/Metainfo.txt +++ b/QID-3376-SFErangen1/Metainfo.txt @@ -4,5 +4,6 @@ Description: 'Generates uniform random numbers using RANDU generator and produce Keywords: graphical representation, hyperplain, plot, random, random-number-generation, randu, scatterplot, simulation, uniform See also: SFEfibonacci, SFErandu, SFErangen2, SFErangen2 Author: Awdesch Melzer +Author[Python]: David Schulte Submitted: Thu, July 16 2015 by quantomas Example: 'A plot is provided for the following parameter values: n=1000, a=2, b=0, M=11, seed=12.' \ No newline at end of file diff --git a/QID-3376-SFErangen1/README.md b/QID-3376-SFErangen1/README.md deleted file mode 100644 index 3bb3eb0..0000000 --- a/QID-3376-SFErangen1/README.md +++ /dev/null @@ -1,60 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFErangen1** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFErangen1 - -Published in : Statistics of Financial Markets - -Description : 'Generates uniform random numbers using RANDU generator and produces a 3d plot of -generated numbers where the pairs from the hyperplains can be visible. Shows that the points -generated by the algorithm are lying on the straight lines with c = 1 and c = 0, whose points form -a lattice.' - -Keywords : 'graphical representation, hyperplain, plot, random, random-number-generation, randu, -scatterplot, simulation, uniform' - -See also : SFEfibonacci, SFErandu, SFErangen2, SFErangen2 - -Author : Awdesch Melzer - -Submitted : Thu, July 16 2015 by quantomas - -Example : 'A plot is provided for the following parameter values: n=1000, a=2, b=0, M=11, seed=12.' - -``` - -![Picture1](SFErangen1-1.png) - - -### R Code: -```r -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# parameter settings -n = 1000 -a = 2 -b = 0 -M = 11 -seed = 12 - -# main computation -y = NULL -y[1] = seed -i = 2 -while (i <= n) { - y[i] = (a * y[i - 1] + b)%%M # modulus - i = i + 1 -} -y = y/M - -# output -plot(y[1:(n - 2)], y[2:(n - 1)], col = "black", xlab = c(expression(U * bold(scriptstyle(atop(phantom(1), - (i - 1)))))), ylab = c(expression(U * bold(scriptstyle(atop(phantom(1), - i))))), xlim = c(0, 1.2), ylim = c(0, 1)) -``` diff --git a/QID-3376-SFErangen1/SFErange1.png b/QID-3376-SFErangen1/SFErange1.png new file mode 100644 index 0000000..62f1f68 Binary files /dev/null and b/QID-3376-SFErangen1/SFErange1.png differ diff --git a/QID-3376-SFErangen1/SFErange1.py b/QID-3376-SFErangen1/SFErange1.py new file mode 100644 index 0000000..d1f44c1 --- /dev/null +++ b/QID-3376-SFErangen1/SFErange1.py @@ -0,0 +1,30 @@ +import numpy as np +from matplotlib import pyplot as plt + +# parameter settings +save_figure = True +n = 1000 +a = 2 +b = 0 +M = 11 +seed = 12 + +# main computation +y = [seed] +for i in range(1, n+1): + y.append((a * y[-1] + b)%M) # modulus + +y = np.array(y) +y = y/M + +# output +fig = plt.figure() +ax = fig.add_subplot() +ax.scatter(y[:-1], y[1:]) +ax.set_title('Numbers generated using RANDU') +ax.set_xlabel('$U_{i-1}$') +ax.set_ylabel('$U_i$') +plt.show() + +if save_figure: + fig.savefig('SFErange1.png', transparent=True) diff --git a/QID-3377-SFErangen2/Metainfo.txt b/QID-3377-SFErangen2/Metainfo.txt index 4742b0f..4d74ec1 100644 --- a/QID-3377-SFErangen2/Metainfo.txt +++ b/QID-3377-SFErangen2/Metainfo.txt @@ -4,5 +4,6 @@ Description: 'Generates uniform random numbers using RANDU generator and produce Keywords: graphical representation, hyperplain, plot, random, random-number-generation, randu, scatterplot, simulation, uniform See also: SFEfibonacci, SFErandu, SFErangen1 Author: Awdesch Melzer +Author[Python]: David Schulte Submitted: Thu, July 16 2015 by quantomas Example: 'A plot is provided for the following parameter values: n=1000, a=1229, b=1, M= 2048, seed=12.' \ No newline at end of file diff --git a/QID-3377-SFErangen2/README.md b/QID-3377-SFErangen2/README.md deleted file mode 100644 index 793d792..0000000 --- a/QID-3377-SFErangen2/README.md +++ /dev/null @@ -1,60 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFErangen2** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFErangen2 - -Published in : Statistics of Financial Markets - -Description : 'Generates uniform random numbers using RANDU generator and produces a 2d plot of -generated numbers where the pairs from the hyperplains can be visible. Shows that the points -generated by the algorithm are lying on 5 straight lines, with c = 0; 1; 2; 3; 4.' - -Keywords : 'graphical representation, hyperplain, plot, random, random-number-generation, randu, -scatterplot, simulation, uniform' - -See also : SFEfibonacci, SFErandu, SFErangen1 - -Author : Awdesch Melzer - -Submitted : Thu, July 16 2015 by quantomas - -Example : 'A plot is provided for the following parameter values: n=1000, a=1229, b=1, M= 2048, -seed=12.' - -``` - -![Picture1](SFErangen2-1.png) - - -### R Code: -```r -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# parameter settings -n = 1000 -a = 1229 -b = 1 -M = 2048 -seed = 12 - -# main computation -y = NULL -y[1] = seed -i = 2 -while (i <= n) { - y[i] = (a * y[i - 1] + b)%%M - i = i + 1 -} -y = y/M - -# output -plot(y[1:(n - 2)], y[2:(n - 1)], col = "black", xlab = c(expression(U * bold(scriptstyle(atop(phantom(1), - (i - 1)))))), ylab = c(expression(U * bold(scriptstyle(atop(phantom(1), - i)))))) -``` diff --git a/QID-3377-SFErangen2/SFErange2.py b/QID-3377-SFErangen2/SFErange2.py new file mode 100644 index 0000000..9bfdd9f --- /dev/null +++ b/QID-3377-SFErangen2/SFErange2.py @@ -0,0 +1,30 @@ +import numpy as np +from matplotlib import pyplot as plt + +# parameter settings +save_figure = True +n = 1000 +a = 1229 +b = 1 +M = 2048 +seed = 12 + +# main computation +y = [seed] +for i in range(1, n+1): + y.append((a * y[-1] + b)%M) # modulus + +y = np.array(y) +y = y/M + +# output +fig = plt.figure() +ax = fig.add_subplot() +ax.scatter(y[:-1], y[1:]) +ax.set_title('Numbers generated using RANDU') +ax.set_xlabel('$U_{i-1}$') +ax.set_ylabel('$U_i$') +plt.show() + +if save_figure: + fig.savefig('SFErangen2.png', transparent=True) diff --git a/QID-3377-SFErangen2/SFErangen2.png b/QID-3377-SFErangen2/SFErangen2.png new file mode 100644 index 0000000..f267648 Binary files /dev/null and b/QID-3377-SFErangen2/SFErangen2.png differ diff --git a/QID-3403-SFEzomma/Metainfo.txt b/QID-3403-SFEzomma/Metainfo.txt index d85deef..23f8b80 100644 --- a/QID-3403-SFEzomma/Metainfo.txt +++ b/QID-3403-SFEzomma/Metainfo.txt @@ -21,6 +21,7 @@ Author: Author[Matlab]: - Ying Chen - Christian M. Hafner +Author[Python]: David Schulte Submitted: Sat, July 18 2015 by quantomas Submitted[Matlab]: Tue, August 30 2016 by Xiu Xu Example: 'User inputs [lower, upper] bound of Asset price S like [50,150], [lower, upper] bound of time to maturity tau like [0.05, 1], then plot of the Zomma of a call option is given.' \ No newline at end of file diff --git a/QID-3403-SFEzomma/README.md b/QID-3403-SFEzomma/README.md deleted file mode 100644 index 488eb09..0000000 --- a/QID-3403-SFEzomma/README.md +++ /dev/null @@ -1,134 +0,0 @@ -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFEzomma** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFEzomma -Published in: Statistics of Financial Markets -Description: 'Plots the Zomma of a call/put option. Zomma is divided by 100 to reflect a one-percentage point change in volatility.' -Keywords: -- asset -- black-scholes -- call -- financial -- graphical representation -- greeks -- option -- option-price -- plot -- put -- returns -- stock-price -- volatility -Author: -- Andreas Golle -- Awdesch Melzer -Author[Matlab]: -- Ying Chen -- Christian M. Hafner -Submitted: Sat, July 18 2015 by quantomas -Submitted[Matlab]: Tue, August 30 2016 by Xiu Xu -Example: 'User inputs [lower, upper] bound of Asset price S like [50,150], [lower, upper] bound of time to maturity tau like [0.05, 1], then plot of the Zomma of a call option is given.' -``` - -![Picture1](SFEzomma-1.png) - -![Picture2](SFEzomma-1_m.png) - -### R Code -```r - -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# install and load packages -libraries = c("lattice") -lapply(libraries, function(x) if (!(x %in% installed.packages())) {install.packages(x)} ) -lapply(libraries, library, quietly = TRUE, character.only = TRUE) - -# parameter settings -s1 = 50 # lower bound of Asset Price -s2 = 150 # upper bound of Asset Price -t1 = 0.05 # lower bound of Time to Maturity -t2 = 1 # upper bound of Time to Maturity -K = 100 # exercise price -r = 0.01 # interest rate -sig = 0.35 # volatility -d = 0 # dividend rate -b = r - d # cost of carry -steps = 60 - -meshgrid = function(a, b) { - list(x = outer(b * 0, a, FUN = "+"), y = outer(b, a * 0, FUN = "+")) -} - -first = meshgrid(seq(t1, t2, -(t1 - t2)/(steps - 1)), seq(t1, t2, -(t1 - t2)/(steps - 1))) - -tau = first$x -dump = first$y - -second = meshgrid(seq(s1, s2, -(s1 - s2)/(steps - 1)), seq(s1, s2, -(s1 - s2)/(steps - 1))) - -dump2 = second$x -S = second$y - -# Black Scholes -d1 = (log(S/K) + (r - d + sig^2/2) * tau)/(sig * sqrt(tau)) -d2 = d1 - sig * sqrt(tau) -# Greeks -gamma = dnorm(d1)/(S * (sig * sqrt(tau))) -zomma = gamma * ((d1 * d2 - 1)/sig) - -# Plot -title = bquote(expression(paste("Strike price is ", .(K), ", interest rate is ", - .(r), ", dividend rate is ", .(d), ", annual volatility is ", .(sig)))) - -wireframe((zomma/100) ~ tau * S, drape = T, ticktype = "detailed", main = expression(paste("Zomma as function of the time to maturity ", - tau, " and the asset price S")), sub = title, scales = list(arrows = FALSE, - col = "black", distance = 1, tick.number = 8, cex = 0.7, x = list(labels = round(seq(t1, - t2, length = 11), 1)), y = list(labels = round(seq(s1, s2, length = 11), - 1)), z = list(labels = round(seq(min(zomma/100), max(zomma/100), length = 11), - 4))), xlab = list(expression(paste("Time to Maturity ", tau)), rot = 30, - cex = 1.2), ylab = list("Asset Price S", rot = -40, cex = 1.2), zlab = list("Zomma", - rot = 95, cex = 1.1)) -``` - -automatically created on 2018-09-04 - -### MATLAB Code -```matlab - -clear all -close all -clc - -S_min = 50; % lower bound of Asset Price -S_max = 150; % upper bound of Asset Price -tau_min = 0.05; % lower bound of Time to Maturity -tau_max = 1; % upper bound of Time to Maturity -K = 100; % exercise price -r = 0.01; % interest rate -sig = 0.25; % volatility -d = 0; % dividend rate -b = r - d; % cost of carry -steps = 60; - -% main computation -[tau, dump] = meshgrid(tau_min : (tau_max - tau_min)/(steps - 1) : tau_max); -[dump2, S] = meshgrid(S_max : -(S_max - S_min)/(steps - 1) : S_min); - -d1 = (log(S/K) + (r - d + sig^2/2).*tau)./(sig.*sqrt(tau)); -d2 = d1 - sig.*sqrt(tau); -gamma = normpdf(d1)./(S.*(sig.*sqrt(tau))); -zomma = gamma .* ((d1.*d2 - 1)./sig); - -% plot -mesh(tau, S, zomma/100) -title('Zomma') -ylabel('Asset Price S'); -xlabel('Time to Maturity \tau'); -``` - -automatically created on 2018-09-04 \ No newline at end of file diff --git a/QID-3403-SFEzomma/SFEvomma.py b/QID-3403-SFEzomma/SFEvomma.py new file mode 100644 index 0000000..0db21f4 --- /dev/null +++ b/QID-3403-SFEzomma/SFEvomma.py @@ -0,0 +1,39 @@ +import numpy as np +from scipy.stats import norm +from matplotlib import pyplot as plt +from matplotlib import cm + +# parameter settings +save_figure = True +S_min = 50 # lower bound of Asset Price +S_max = 150 # upper bound of Asset Price +tau_min = 0.05 # lower bound of Time to Maturity +tau_max = 1 # upper bound of Time to Maturity +K = 100 # exercise price +r = 0.1 # riskfree interest rate +sig = 0.35 # volatility +d = 0.2 # dividend rate +steps = 60 # steps + +tau = np.linspace(tau_min, tau_max, steps) +S = np.linspace(S_max, S_min, steps) + + +def get_vomma(tau, S, K, r, d, sig): + y = (np.log(S/K) + (r - d - sig**2/2) * tau)/(sig * np.sqrt(tau)) + d1 = y+sig*np.sqrt(tau) + vega = np.exp(-d*tau)*S*np.sqrt(tau)*norm.pdf(d1) + + return vega*y*d1/sig + +X, Y = np.meshgrid(tau, S) +fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) +ax.plot_surface(X, Y, get_vomma(X, Y, K, r, d, sig), cmap=cm.viridis) +ax.set_title('Dependence of Vomma on Stock Price and Time to Maturity') +ax.set_xlabel('Time to Maturity') +ax.set_ylabel('Stock Price') +ax.set_zlabel('Vomma') +plt.show() + +if save_figure: + fig.savefig('SFEvomma.png', transparent=True) diff --git a/QID-3403-SFEzomma/SFEzomma.png b/QID-3403-SFEzomma/SFEzomma.png new file mode 100644 index 0000000..2a1c200 Binary files /dev/null and b/QID-3403-SFEzomma/SFEzomma.png differ diff --git a/QID-3432-SFEfibonacci/Metainfo.txt b/QID-3432-SFEfibonacci/Metainfo.txt index 52c9bec..0eb3259 100644 --- a/QID-3432-SFEfibonacci/Metainfo.txt +++ b/QID-3432-SFEfibonacci/Metainfo.txt @@ -4,5 +4,6 @@ Description: 'Generates uniform random numbers using Fibonacci Algorithm and pro Keywords: Fibonacci, graphical representation, plot, random, random-number-generation, scatterplot, simulation, uniform See also: SFErandu, SFErangen1, SFErangen2 Author: Wolfgang K. Haerdle +Author[Python]: David Schulte Submitted: Wed, July 22 2015 by quantomas Example: 'A plot is generated for the following parameter values: a=1366, b=150889, M=714025, n=10000.' \ No newline at end of file diff --git a/QID-3432-SFEfibonacci/README.md b/QID-3432-SFEfibonacci/README.md deleted file mode 100644 index bf5c4b2..0000000 --- a/QID-3432-SFEfibonacci/README.md +++ /dev/null @@ -1,73 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFEfibonacci** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFEfibonacci - -Published in : Statistics of Financial Markets - -Description : 'Generates uniform random numbers using Fibonacci Algorithm and produces a plot of -generated numbers.' - -Keywords : 'Fibonacci, graphical representation, plot, random, random-number-generation, -scatterplot, simulation, uniform' - -See also : SFErandu, SFErangen1, SFErangen2 - -Author : Wolfgang K. Haerdle - -Submitted : Wed, July 22 2015 by quantomas - -Example : 'A plot is generated for the following parameter values: a=1366, b=150889, M=714025, -n=10000.' - -``` - -![Picture1](SFEfibonacci-1.png) - - -### R Code: -```r -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# parameter settings -nn = 18 -a = 1366 -b = 150889 -M = 714025 -seed = 1234567 -n = 10000 -yy = c(seed) -i = 2 - -# Main computation -while (i <= nn) { - yy = cbind(yy, ((a * yy[i - 1] + b)%%M)) - i = i + 1 -} -y = yy/M -i = 19 - -while (i <= n + 18) { - zeta = y[i - 17] - y[i - 5] - if (zeta < 0) { - zeta = zeta + 1 - } - y[i] = zeta - i = i + 1 -} -y = y[19:n + 18] -n1 = n - 2 -n2 = n - 1 -dat = c(y[1:n1], y[2:n2]) - -# Plot -plot(y[1:n1], y[2:n2], type = "p", pch = 20, xlab = expression(U[i - 1]), ylab = expression(U[i]), - xaxp = c(0, 1, 10), yaxp = c(0, 1, 10), xlim = c(0, 1), ylim = c(0, 1)) - -``` diff --git a/QID-3432-SFEfibonacci/SFEfibonacci.png b/QID-3432-SFEfibonacci/SFEfibonacci.png new file mode 100644 index 0000000..09bcb2e Binary files /dev/null and b/QID-3432-SFEfibonacci/SFEfibonacci.png differ diff --git a/QID-3432-SFEfibonacci/SFEfibonacci.py b/QID-3432-SFEfibonacci/SFEfibonacci.py new file mode 100644 index 0000000..f9c7284 --- /dev/null +++ b/QID-3432-SFEfibonacci/SFEfibonacci.py @@ -0,0 +1,38 @@ +import numpy as np +from matplotlib import pyplot as plt + +# parameter settings +save_figure = True +nn = 18 +a = 1366 +b = 150889 +M = 714025 +seed = 1234567 +n = 10000 + +# Main computation +y = [seed] +for i in range(1, nn+1): + y.append((a * y[i - 1] + b)%M) + +y = [y_element / M for y_element in y] + +for i in range(19, n+18+1): + zeta = y[i - 17] - y[i - 5] + if zeta < 0: zeta += 1 + y.append(zeta) + +y = np.array(y) +y = y[19:n + 18] + +# output +fig = plt.figure() +ax = fig.add_subplot() +ax.scatter(y[:-1], y[1:], s=3) +ax.set_title('Numbers generated using Fibonacci Algorithm') +ax.set_xlabel('$U_{i-1}$') +ax.set_ylabel('$U_i$') +plt.show() + +if save_figure: + fig.savefig('SFEfibonacci.png', transparent=True) diff --git a/QID-3439-SFEVolSurfPlot/Metainfo.txt b/QID-3439-SFEVolSurfPlot/Metainfo.txt index 1d6af79..8af1a55 100644 --- a/QID-3439-SFEVolSurfPlot/Metainfo.txt +++ b/QID-3439-SFEVolSurfPlot/Metainfo.txt @@ -25,6 +25,7 @@ Author: - Maria Grith - Awdesch Melzer Author[Matlab]: Maria Grith +Author[Python]: David Schulte Submitted: Fri, July 24 2015 by quantomas Submitted[Matlab]: Tue, May 03 2016 by Meng Jou Lu Output[Matlab]: Plot of implied volatility surface. diff --git a/QID-3439-SFEVolSurfPlot/README.md b/QID-3439-SFEVolSurfPlot/README.md deleted file mode 100644 index 26a58d6..0000000 --- a/QID-3439-SFEVolSurfPlot/README.md +++ /dev/null @@ -1,338 +0,0 @@ -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFEVolSurfPlot** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFEVolSurfPlot -Published in: Statistics of Financial Markets -Description: 'Produces a graphic visualisation of the implied volatility surface of the DAX option. The original options are shown as blue points.' -Keywords: -- bisection-method -- black-scholes -- data visualization -- dax -- financial -- graphical representation -- implied-volatility -- index -- option -- plot -- surface -- visualization -- volatility -See also: -- SFEPCA -- SFEVolaCov -- SFEVolaPCA -- SFEVolaTermStructure -See also[Matlab]: 'SFEVolaTermStructure, SFEVolaCov, SFEVolaPCA, SFEPCA, SFEVolSurfPlot' -Author: -- Maria Grith -- Awdesch Melzer -Author[Matlab]: Maria Grith -Submitted: Fri, July 24 2015 by quantomas -Submitted[Matlab]: Tue, May 03 2016 by Meng Jou Lu -Output[Matlab]: Plot of implied volatility surface. -Datafiles: volsurfdata2.dat -``` - -![Picture1](SFEVolSurfPlot-1.png) - -![Picture2](SFEVolSurfPlot_m.png) - -### R Code -```r - -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# install and load packages -libraries = c("lattice") -lapply(libraries, function(x) if (!(x %in% installed.packages())) { - install.packages(x) -}) -lapply(libraries, library, quietly = TRUE, character.only = TRUE) - -# Black-Scholes Function -BS = function(S, K, Time, r, sig, type) { - d1 = (log(S/K) + (r + sig^2/2) * Time)/(sig * sqrt(Time)) - d2 = d1 - sig * sqrt(Time) - if (type == 1) { - value = S * pnorm(d1) - K * exp(-r * Time) * pnorm(d2) - } - if (type == 0) { - value = K * exp(-r * Time) * pnorm(-d2) - S * pnorm(-d1) - } - return(value) -} - -# Function to find BS Implied Volatility using Bisection Method -blsimpv = function(S, K, Time, r, market, type) { - sig = 0.2 - sig.up = 1 - sig.down = 0.001 - count = 0 - err = BS(S, K, Time, r, sig, type) - market - - # repeat until error is sufficiently small or counter hits 1000 - while (abs(err) > 1e-05 && count < 1000) { - if (err < 0) { - sig.down = sig - sig = (sig.up + sig)/2 - } else { - sig.up = sig - sig = (sig.down + sig)/2 - } - err = BS(S, K, Time, r, sig, type) - market - count = count + 1 - } - - # return NA if counter hit 1000 - if (count == 1000) { - return(NA) - } else { - return(sig) - } -} - -# load data -x = read.table("volsurfdata2.dat") - -# define variables -x[, 7] = x[, 1]/x[, 2] # define moneyness -Price = x[, 1] -Strike = x[, 2] -Rate = x[, 3] -Time = x[, 4] -Value = x[, 5] -Class = x[, 6] -mon = x[, 7] -n = length(x[, 1]) - -# calculate implied volatility -iv = rep(0, n) -for (i in 1:n) { - iv[i] = blsimpv(S = Price[i], K = Strike[i], Time = Time[i], r = Rate[i], market = Value[i], - type = Class[i]) -} - -firstmon = 0.8 -lastmon = 1.2 -firstmat = 0 -lastmat = 1 - -stepwidth = c(0.02, 1/52) -lengthmon = ceiling((lastmon - firstmon)/stepwidth[1]) -lengthmat = ceiling((lastmat - firstmat)/stepwidth[2]) - -mongrid = seq(0.8, 1.2, length = c(lengthmon + 1)) -matgrid = seq(0, 1, length = c(lengthmat + 1)) - -# grid function -meshgrid = function(a, b) { - list(x = outer(b * 0, a, FUN = "+"), y = outer(b, a * 0, FUN = "+")) -} - -# compute grid -gridone = meshgrid(mongrid, matgrid) - -MON = gridone$x -MAT = gridone$y - -gmon = lengthmon + 1L -gmat = lengthmat + 1L -uu = dim(x) -v = uu[1] - -# calculate the implied volatility surface -beta = matrix(0, gmat, gmon) -j = 1L -while (j < gmat + 1L) { - k = 1L - while (k < gmon + 1L) { - i = 1L - X = matrix(0, v, 3) - while (i < (v + 1L)) { - X[i, ] = c(1, x[i, 7] - MON[j, k], x[i, 4] - MAT[j, k]) - i = i + 1 - } - Y = iv - h1 = 0.1 - h2 = 0.75 - W = matrix(0, v, v) # Kernel matrix - i = 1L - while (i < (v + 1L)) { - u1 = (x[i, 7] - MON[j, k])/h1 - u2 = (x[i, 4] - MAT[j, k])/h2 - aa = 15/16 * (1 - u1^2)^2 %*% (abs(u1) <= 1)/h1 - bb = 15/16 * (1 - u2^2)^2 %*% (abs(u2) <= 1)/h2 - W[i, i] = aa %*% bb - i = i + 1L - } - est = solve(t(X) %*% W %*% X) %*% t(X) %*% W %*% Y - beta[j, k] = est[1] - k = k + 1L - } - j = j + 1L -} -IV = beta - -# select points for elimination -ex1 = which(x[, 4] > 1) # Time to maturity > 1 -ex2 = which(x[, 7] < 0.8 | x[, 7] > 1.2) # moneyness < 0.8 or > 1.2 -ex = c(ex1, ex2) - -xnew = x -xnew = xnew[-ex, ] # eliminate data points - -# redefine variables -Price = xnew[, 1] -Strike = xnew[, 2] -Rate = xnew[, 3] -Time = xnew[, 4] -Value = xnew[, 5] -Class = xnew[, 6] -mon = xnew[, 7] -n = length(xnew[, 1]) - -# calculate implied volatility for original options -iv = rep(0, n) -for (i in 1:n) { - iv[i] = blsimpv(Price[i], Strike[i], Time[i], Rate[i], Value[i], Class[i]) -} - -# define points -pts = cbind(mon, Time, iv) - -# plot -wireframe(IV ~ MON + MAT, drape = T, ticktype = "detailed", pts = pts, main = "", - aspect = c(1, 1), scales = list(arrows = FALSE, y = list(labels = seq(0, 1, 0.2)), - x = list(labels = seq(0.8, 1.4, 0.1)), z = list(labels = seq(0.2, 0.5, 0.05))), - ylab = list("Time to Maturity", rot = -38), xlab = list("Moneyness", rot = 33), - zlab = list("Implied Volatility", rot = 94), zlim = c(0.25, 0.45), panel.3d.wireframe = function(x, - y, z, xlim, ylim, zlim, xlim.scaled, ylim.scaled, zlim.scaled, pts, drape = drape, - ...) { - panel.3dwire(x, y, z, xlim = xlim, ylim = ylim, zlim = zlim, xlim.scaled = xlim.scaled, - ylim.scaled = ylim.scaled, zlim.scaled = zlim.scaled, drape = TRUE, ...) - - panel.3dscatter(pts[, 1], pts[, 2], pts[, 3], xlim = xlim, ylim = ylim, zlim = zlim, - xlim.scaled = xlim.scaled, ylim.scaled = ylim.scaled, zlim.scaled = zlim.scaled, - type = "p", col = c(4), lwd = 3, cex = 1, pch = c(19), .scale = TRUE, - ...) - }) -``` - -automatically created on 2018-05-28 - -### MATLAB Code -```matlab - - -clear -clc -close all - -load ('volsurfdata2.dat') -x = volsurfdata2; -x(:,7) = x(:,1)./x(:,2); - -Price = x(:,1); -Strike = x(:,2); -Rate = x(:,3); -Time = x(:,4); -Value = x(:,5); -Class = x(:,6); -mon = x(:,7); - -iv = blsimpv(Price, Strike, Rate, Time, Value,[],[], [],Class); - -firstmon = 0.8; -lastmon = 1.2; -firstmat = 0; -lastmat = 1; - -stepwidth = [0.02 1/52]; -lengthmon = ceil((lastmon-firstmon)/stepwidth(1)); -lengthmat = ceil((lastmat-firstmat)/stepwidth(2)); - -mongrid = linspace(0.8,1.2,lengthmon+1); -matgrid = linspace(0,1,lengthmat+1); - -[MON, MAT] = meshgrid(mongrid,matgrid); - -gmon = lengthmon+1; -gmat = lengthmat+1; -uu = size(x); -v = uu(1,1); - -beta = zeros(gmat,gmon); - -j = 1; -while (j1); -ex2 = find(x(:,7)<0.8 |x(:,7)>1.2); -ex = [ex1;ex2]; -x(ex,:) = []; - -Price = x(:,1); -Strike = x(:,2); -Rate = x(:,3); -Time = x(:,4); -Value = x(:,5); -Class = x(:,6); -mon = x(:,7); - -iv = blsimpv(Price, Strike, Rate, Time, Value,[],[], [],Class); - -surf(MON,MAT,IV) -colormap hsv -alpha(0.3) - -hold on -scatter3(mon, Time,iv, 'filled') -xlabel('Moneyness') -ylabel('Time to Maturity') -zlabel('Implied Volatility') -hold off -``` - -automatically created on 2018-05-28 \ No newline at end of file diff --git a/QID-3439-SFEVolSurfPlot/SFEVolSurfPlot.png b/QID-3439-SFEVolSurfPlot/SFEVolSurfPlot.png new file mode 100644 index 0000000..79ce6b6 Binary files /dev/null and b/QID-3439-SFEVolSurfPlot/SFEVolSurfPlot.png differ diff --git a/QID-3439-SFEVolSurfPlot/SFEVolSurfPlot.py b/QID-3439-SFEVolSurfPlot/SFEVolSurfPlot.py new file mode 100644 index 0000000..571ca03 --- /dev/null +++ b/QID-3439-SFEVolSurfPlot/SFEVolSurfPlot.py @@ -0,0 +1,65 @@ +import numpy as np +from matplotlib import pyplot as plt +from matplotlib import cm +import pandas as pd +from py_vollib.black_scholes.implied_volatility import implied_volatility +from statsmodels.nonparametric.kernel_regression import KernelReg +from scipy.stats import iqr + +save_figure = True +use_silverman_bw = False # Use Silverman's rule of thumb for kernel regression bandwith or cross-validation + +# Read the csv file +df = pd.read_csv('surf_1412.csv', names=['Price', 'Strike', 'Rate', 'Time', 'Value', 'Class']) +df.drop_duplicates(inplace=True) + +# Calculate moneyness +df['Moneyness'] = df['Price']/df['Strike'] + +# Drop data points that have extreme moneyness or too far away from maturity +df.drop(df[df['Time']>1].index, inplace=True) +df.drop(df[(df['Moneyness']<0.7) | (df['Moneyness']>1.2)].index, inplace=True) + +# Indicate if the row corresponds to a call or a put +df['Class'] = df['Class'].map({0: 'p', 1: 'c'}) + +# Computes implied volatility +def iv(row): + return implied_volatility(row['Value'], row['Price'], row['Strike'], row['Time'], row['Rate'], row['Class']) + + +df['Implied Volatility'] = df.apply(iv, axis=1) + +# Drop rows with Nan values +df.dropna(inplace=True) + +if use_silverman_bw: + + def compute_silverman_bw(column): + a = np.unique(column) + return 0.9 * np.min([np.std(a), iqr(a) / 1.34]) * len(a) ** (-1 / 5) + + bw = [compute_silverman_bw(column) for column in [df['Implied Volatility'], df['Time']]] + +else: + bw = 'cv_ls' + +# Do a kernel regression with gaussian kernel and bandwidth determined by cross-validation +kr = KernelReg(df['Implied Volatility'], [df['Time'], df['Moneyness']], 'cc', bw=bw) + +# Create a grid for the plot and predict the volatility surface on it +steps = 60 +tau = np.linspace(df['Time'].min(), df['Time'].max(), steps) +moneyness = np.linspace(df['Moneyness'].min(), df['Moneyness'].max(), steps) +mg = np.array(np.meshgrid(tau, moneyness)).reshape(2,-1) +estimate, _ = kr.fit(mg) + +# Plot +X, Y = np.meshgrid(tau, moneyness) +fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) +ax.plot_surface(X, Y, estimate.reshape(-1, steps), cmap=cm.viridis) +ax.scatter(df['Time'], df['Moneyness'], df['Implied Volatility'], c='r', marker='x') +plt.show() + +if save_figure: + fig.savefig('SFEVolSurfPlot.png', transparent=True) diff --git a/QID-3446-SFEDeltaHedging/Metainfo.txt b/QID-3446-SFEDeltaHedging/Metainfo.txt index 9601d4a..b0ac694 100644 --- a/QID-3446-SFEDeltaHedging/Metainfo.txt +++ b/QID-3446-SFEDeltaHedging/Metainfo.txt @@ -18,4 +18,5 @@ See also: - SFEDeltahedgingdepend - SFSdeltahedging Author: Felix Jung +Author[Python]: David Schulte Submitted: Sat, July 25 2015 by quantomas \ No newline at end of file diff --git a/QID-3446-SFEDeltaHedging/README.md b/QID-3446-SFEDeltaHedging/README.md deleted file mode 100644 index e0c8742..0000000 --- a/QID-3446-SFEDeltaHedging/README.md +++ /dev/null @@ -1,90 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFEDeltaHedging** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFEDeltaHedging - -Published in : Statistics of Financial Markets - -Description : 'Simulates 3 stock price path for a given specification of a geometric Brownian -motion. For each of these paths the positions and cumulative costs of a Delta hedging strategy are -plotted.' - -Keywords : 'black-scholes, brownian-motion, delta, financial, geometric-brownian-motion, graphical -representation, hedging, plot, simulation, stock-price, wiener-process' - -See also : SFEDeltahedgingLogic, SFEDeltahedgingdepend, SFSdeltahedging - -Author : Felix Jung - -Submitted : Sat, July 25 2015 by quantomas - -``` - -![Picture1](SFEDeltaHedging_1-1.png) - -![Picture2](SFEDeltaHedging_2-1.png) - - -### R Code: -```r -rm(list = ls(all = TRUE)) -graphics.off() - -# Declare stock price variables -n = 50 # periods (steps) -S0 = 98 # initial stock price -sig = 0.2 # volatility (uniform distributed on 0.1 to 0.5) - -# Declare option pricing variables -r = 0.05 # interest rate (uniform distributed on 0 to 0.1) -K = 100 # exerise price -t0 = 6/52 # current time (1 week = 1/52) -mat = 26/52 # maturity - -GeneratePaths = function(S0, sig, maturity, K, r, n, t0) { - dt = (maturity - t0)/n # period between steps n - t = seq(t0, maturity, l = n) # maturity - t0 divided in n intervals - tau = maturity - t # time to maturity - - # Simulate the stock price path - Wt = c(0, sqrt(dt) * cumsum(rnorm(n - 1, 0, 1))) - S = S0 * exp((r - 0.5 * sig^2) * t + sig * Wt) - - # Compute delta and the associated hedging costs - y = (log(S/K) + (r - sig^2/2) * tau)/(sig * sqrt(tau)) - delta = pnorm(y + sig * sqrt(tau)) - hedge.costs = c(delta[1] * S[1], (delta[2:n] - delta[1:(n - 1)]) * S[2:n]) - cum.hedge.costs = cumsum(hedge.costs) - - # Result - result = data.frame(S = S, CumCosts = cum.hedge.costs) - return(result) -} - -# Run three simulations -sim = cbind(GeneratePaths(S0 = S0, sig = sig, maturity = mat, K = K, r = r, n = n, - t0 = t0), GeneratePaths(S0 = S0, sig = sig, maturity = mat, K = K, r = r, n = n, - t0 = t0), GeneratePaths(S0 = S0, sig = sig, maturity = mat, K = K, r = r, n = n, - t0 = t0)) - -# Plot the stock prices -plot(x = 1:nrow(sim), y = sim[, 1], main = "Stock Price Paths", xlab = "Steps", ylab = "Stock price", - ylim = c(min(sim[, 1], sim[, 3], sim[, 5]), max(sim[, 1], sim[, 3], sim[, 5])), - type = "l", col = "darkorchid2") -lines(x = 1:nrow(sim), y = sim[, 3], col = "limegreen") -lines(x = 1:nrow(sim), y = sim[, 5], col = "firebrick2") -abline(h = K, col = 1) - -# Plot cumulative hedge costs -dev.new() -plot(x = 1:nrow(sim), y = sim[, 2], main = "Cumulative Hedge Costs", xlab = "Steps", - ylab = "Costs", ylim = c(min(sim[, 2], sim[, 4], sim[, 6]), max(sim[, 2], sim[, - 4], sim[, 6])), type = "l", col = "darkorchid2") -lines(x = 1:nrow(sim), y = sim[, 4], col = "limegreen") -lines(x = 1:nrow(sim), y = sim[, 6], col = "firebrick2") - -``` diff --git a/QID-3446-SFEDeltaHedging/SFEDeltaHedging.py b/QID-3446-SFEDeltaHedging/SFEDeltaHedging.py new file mode 100644 index 0000000..25666da --- /dev/null +++ b/QID-3446-SFEDeltaHedging/SFEDeltaHedging.py @@ -0,0 +1,58 @@ +import numpy as np +from scipy.stats import norm +from matplotlib import pyplot as plt + +# parameter settings +save_figure = True +n = 50 # periods (steps) +S0 = 98 # initial stock price +sig = 0.2 # volatility (uniform distributed on 0.1 to 0.5) +r = 0.05 # interest rate (uniform distributed on 0 to 0.1) +K = 100 # exercise price +t0 = 6/52 # current time (1 week = 1/52) +mat = 26/52 # maturity +sims = 3 # number of simulations + + +def generate_paths(S0, sig, maturity, K, r, n, t0): + dt = (maturity - t0) / n # period between steps n + t = np.linspace(t0, maturity, n) # maturity - t0 divided in n intervals + tau = maturity - t # time to maturity + + # Simulate the stock price path + Wt = np.concatenate((np.array([0]), np.sqrt(dt) * np.cumsum(np.random.normal(size=n - 1)))) + S = S0 * np.exp((r - 0.5 * sig ** 2) * t + sig * Wt) + + # Compute delta and the associated hedging costs + with np.errstate(divide='ignore'): + y = (np.log(S / K) + (r - sig ** 2 / 2) * tau) / (sig * np.sqrt(tau)) + delta = norm.cdf(y + sig * np.sqrt(tau)) + delta_diff = np.concatenate((np.array([0]), np.diff(delta))) + hedge_costs = S * delta_diff + cum_hedge_costs = np.cumsum(hedge_costs) + + return S, cum_hedge_costs + +# Plot +fig = plt.figure() +ax1 = fig.add_subplot(2,1,1) +ax1.set_title('Stock Price Paths') +ax1.set_xlabel('Steps') +ax1.set_ylabel('Stock Price') +ax2 = fig.add_subplot(2,1,2) +ax2.set_title('Cumulative Hedge Costs') +ax2.set_xlabel('Steps') +ax2.set_ylabel('Costs') + +ax1.axhline(K, c='black', linestyle='dashed') + +for _ in range(sims): + S, cum_edge_costs = generate_paths(S0, sig, mat, K, r, n, t0) + ax1.plot(S) + ax2.plot(cum_edge_costs) + +fig.tight_layout() +plt.show() + +if save_figure: + fig.savefig('SFEDeltahedging.png', transparent=True) diff --git a/QID-3446-SFEDeltaHedging/SFEDeltahedging.png b/QID-3446-SFEDeltaHedging/SFEDeltahedging.png new file mode 100644 index 0000000..dd40fd3 Binary files /dev/null and b/QID-3446-SFEDeltaHedging/SFEDeltahedging.png differ diff --git a/QID-955-SFEdelta/Metainfo.txt b/QID-955-SFEdelta/Metainfo.txt index eb07b2a..e2e410f 100644 --- a/QID-955-SFEdelta/Metainfo.txt +++ b/QID-955-SFEdelta/Metainfo.txt @@ -10,6 +10,7 @@ See also: SFEvanna, SFEvolga, SFEgamma, SFEvega, SFEtheta, SFEspeed, SFEcharmcal Author: Ying Chen, Christian M. Hafner Author[SAS]: Daniel T. Pele +Author[Python]: David Schulte Submitted: December 04 2011 by Dedy Dwi Prastyo; Dec 25 2015 by Lukas Borke Submitted[Matlab]: December 04 2011 by Dedy Dwi Prastyo; May 19 2016 by Petra Burdejova diff --git a/QID-955-SFEdelta/README.md b/QID-955-SFEdelta/README.md deleted file mode 100644 index 03b0e40..0000000 --- a/QID-955-SFEdelta/README.md +++ /dev/null @@ -1,234 +0,0 @@ - -[Visit QuantNet](http://quantlet.de/) - -## [Visit QuantNet](http://quantlet.de/) **SFEdelta** [Visit QuantNet 2.0](http://quantlet.de/) - -```yaml - -Name of QuantLet : SFEdelta - -Published in : Statistics of Financial Markets - -Description : 'Plots the Delta of a call option as a function of the time to maturity and the asset -price.' - -Keywords : 'asset, black-scholes, call, european-option, financial, graphical representation, -greeks, option, option-price, plot' - -See also : 'SFEvanna, SFEvolga, SFEgamma, SFEvega, SFEtheta, SFEspeed, SFEcharmcall, SFEcolor, -SFEultima, SFEvomma, SFEzomma, SFEdvegadtime' - -Author : Ying Chen, Christian M. Hafner - -Author[SAS] : Daniel T. Pele - -Submitted : December 04 2011 by Dedy Dwi Prastyo; Dec 25 2015 by Lukas Borke - -Submitted[Matlab] : December 04 2011 by Dedy Dwi Prastyo; May 19 2016 by Petra Burdejova - -Submitted[SAS] : Tue, June 17 2014 by Franziska Schulz - -Example : 'For given [lower, upper] bound of Asset price S like [50,150] and [lower, upper] bound -of time to maturity tau like [0.01, 1] a plot of the Delta of a call option is produced.' - -``` - -![Picture1](SFEdelta-1(Matlab).png) - -![Picture2](SFEdelta-1.png) - -![Picture3](SFEdelta-1_sas.png) - - -### R Code: -```r - -# clear variables and close windows -rm(list = ls(all = TRUE)) -graphics.off() - -# install and load packages -libraries = c("lattice") -lapply(libraries, function(x) if (!(x %in% installed.packages())) { -install.packages(x) -}) -lapply(libraries, library, quietly = TRUE, character.only = TRUE) - -# parameter settings -S_min = 50 # lower bound of Asset Price -S_max = 150 # upper bound of Asset Price -tau_min = 0.01 # lower bound of Time to Maturity -tau_max = 1 # upper bound of Time to Maturity -K = 100 # exercise price -r = 0.1 # riskfree interest rate -sig = 0.85 # volatility -d = 0.2 # dividend rate -steps = 60 # steps - -Tau = seq(tau_min, tau_max, by = (tau_max - tau_min)/(steps - 1)) -S = seq(S_max, S_min, by = -(S_max - S_min)/(steps - 1)) - -delta = function(Tau, S, K, r, d, sig) { - y = (log(S/K) + (r - d + sig^2/2) * Tau)/(sig * sqrt(Tau)) - return(pnorm(y + sig * sqrt(Tau))) -} - -mesh = outer(Tau, sort(S), delta, K = K, r = r, d = d, sig = sig) -title = bquote(expression(paste("Strike price is ", .(K), ", interest rate is ", - .(r), ", dividend rate is ", .(d), ", annual volatility is ", .(sig)))) - -# Plot -wireframe(mesh, drape = T, main = expression(paste("Delta as function of the time to maturity ", - tau, " and the asset price S")), sub = title, scales = list(arrows = FALSE, - col = "black", distance = 1, tick.number = 8, cex = 0.7, x = list(labels = round(seq(tau_min, - tau_max, length = 7), 1)), y = list(labels = round(seq(S_min, S_max, length = 7), - 1))), xlab = list(expression(paste("Time to Maturity ", tau)), rot = 30, - cex = 1.2), ylab = list("Asset Price S", rot = -40, cex = 1.2), zlab = list("Delta", - cex = 1.1)) - -``` - -### MATLAB Code: -```matlab -% user inputs parameters -disp('Please input [lower, upper] bound of Asset price S as: [50,150]') ; -disp(' ') ; -para=input('[lower, upper] bound of S ='); -while length(para) < 2 - disp('Not enough input arguments. Please input in 1*2 vector form like [50,150] or [50 150]'); - para=input('[lower, upper] bound of S='); -end -S_min = para(1); -S_max = para(2); - -disp(' ') ; -disp('Please input [lower, upper] bound of time to maturity tau as: [0.01, 1]') ; -disp(' ') ; -para2=input('[lower, upper] bound of tau =') ; -while length(para2) < 2 - disp('Not enough input arguments. Please input in 1*2 vector form like [0.01, 1] or [0.01 1]'); - para2=input('[lower, upper] bound of tau ='); -end -tau_min=para2(1); -tau_max=para2(2); - -% main computation -K = 100; % exercise price -r = 0 ; % interest rate -sig = 0.25 ; % volatility -d = 0; % dividend rate -b = r-d; % cost of carry -steps = 60; - -[tau,dump] = meshgrid([tau_min:(tau_max-tau_min)/(steps-1):tau_max]); -[dump2,S] = meshgrid([S_max:-(S_max-S_min)/(steps-1):S_min]); - -d1 = (log(S/K)+(r-d+sig^2/2).*tau)./(sig.*sqrt(tau)); -delta = normcdf(d1); - -% plot -mesh(tau,S,delta); -title('Delta') -ylabel('Asset Price S'); -xlabel('Time to Maturity \\tau'); - -``` - -### SAS Code: -```sas - -* Reset the working evironment; -goptions reset = all; -proc datasets lib = work nolist kill; -run; - -*************************************************************************** -..................Please input the parameters!............................. -***************************************************************************; - -%let S_min = 50 ; *Lower Bound of Asset Price S; -%let S_max = 150 ; *Upper Bound of Asset Price S; -%let tau_min = 0.01 ; *Lower Bound of Time to Maturity tau; -%let tau_max = 1 ; *Upper Bound of Time to Maturity tau; - -* main computation; - -proc iml; -S_min = &S_min; S_max = &S_max; tau_min = &tau_min; tau_max = &tau_max; - -K = 100; * exercise price; -r = 0 ; * interest rate; -sig = 0.25 ; * volatility; -d = 0; * dividend rate; -b = r-d; * cost of carry; -steps = 60; - -*Computing tau; - -tau = j(steps,steps,0); - -do i = 1 to nrow(tau); -tau[i,] = (0:59)*(tau_max-tau_min)/(steps-1) +tau_min; -end; - -*Computing S; - -S = j(steps,steps,0); -do i = 1 to nrow(tau); -S[,i] = (0:59)`*(-(s_max-s_min)/(steps-1)) +s_max; -end; - -*Computing delta; - -d1 = (log(S/K)+(r-d+sig**2/2)*tau)/(sig*sqrt(tau)); -delta = cdf('Normal',d1); - -*Creating frid for 3d surface plot; - -S = (shape(S,1))`; -delta = (shape(delta,1))`; -tau = (shape(tau,1))`; -d3d = S||delta||tau; - -create d3d from d3d; append from d3d; -close d3d; - -quit; - - -data d3d;set d3d; -rename col1 = S col2 = delta col3 = tau; - -*Plot the 3d surface graph; - - title h = 2 f = default 'Delta as function of the time to maturity ' -h = 3 f = greek '74'x h = 2 f = default ' and the asset price S'; -proc g3d data = d3d ; - plot S*tau = delta/ cbottom = blue ctop = red - rotate = 45 -grid zmin = 0 zmax = 1 ; -run; -quit; - -*The following section creates an animated 3D plot; - -/* Designate a GIF file for the G3D output, like below. */ -filename anim 'd:delta.gif'; -** Set the GOPTIONs necessary for the **/ -/** animation. **/; -goption reset dev=gifanim gsfmode=replace -border gsfname=anim xpixels=640 ypixels=480 iteration=0 delay=60 gepilog='3B'x -/* add a termination char to the end of the GIF file */ -disposal=background; - -proc g3d data = d3d ; - plot S*tau = delta/ cbottom = blue ctop = red - rotate = 45 to 350 by 10 -grid zmin = 0 zmax = 1 ; -run; -quit; - - -*Open the file 'd:delta.gif' and enjoy the 3D animation; - -``` diff --git a/QID-955-SFEdelta/SFEdelta.png b/QID-955-SFEdelta/SFEdelta.png new file mode 100644 index 0000000..9fc62df Binary files /dev/null and b/QID-955-SFEdelta/SFEdelta.png differ diff --git a/QID-955-SFEdelta/SFEdelta.py b/QID-955-SFEdelta/SFEdelta.py new file mode 100644 index 0000000..736898c --- /dev/null +++ b/QID-955-SFEdelta/SFEdelta.py @@ -0,0 +1,38 @@ +import numpy as np +from scipy.stats import norm +from matplotlib import pyplot as plt +from matplotlib import cm + +# parameter settings +save_figure = True +S_min = 50 # lower bound of Asset Price +S_max = 150 # upper bound of Asset Price +tau_min = 0.01 # lower bound of Time to Maturity +tau_max = 1 # upper bound of Time to Maturity +K = 100 # exercise price +r = 0.1 # riskfree interest rate +sig = 0.85 # volatility +d = 0.2 # dividend rate +steps = 60 # steps + +tau = np.linspace(tau_min, tau_max, steps) +S = np.linspace(S_max, S_min, steps) + + +def get_delta(tau, S, K, r, d, sig): + y = (np.log(S/K) + (r - d + sig**2/2) * tau)/(sig * np.sqrt(tau)) + + return norm.cdf(y + sig * np.sqrt(tau)) + + +X, Y = np.meshgrid(tau, S) +fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) +ax.plot_surface(X, Y, get_delta(X, Y, K, r, d, sig), cmap=cm.viridis) +ax.set_title('Dependence of Delta on Stock Price and Time to Maturity') +ax.set_xlabel('Time to Maturity') +ax.set_ylabel('Stock Price') +ax.set_zlabel('Delta') +plt.show() + +if save_figure: + fig.savefig('SFEdelta.png', transparent=True)