Skip to content

Instantly share code, notes, and snippets.

@x213212
Last active November 24, 2018 09:18
增加動畫
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.stats as scs
from matplotlib import animation
S0 = 100
r = 0.05
sigma = 0.25
T = 1.0
I = 10
M = 50
dt = T/M
S = np.zeros((M + 1,I))
S[0] = S0
print (S[0])
for t in range(1,M+1):
S[t] = S[t-1]*np.exp((r-0.5*sigma**2)*dt+sigma*np.sqrt(dt)*np.random.standard_normal(I))
print (t)
print (M+1)
plt.figure(figsize=(16,8))
#define q as the 1% empirical qunatile, this basically means that 99% of the values should fall between here
q = np.percentile(S, 1)
# Plot a line at the 1% quantile result
plt.axvline(x=q, linewidth=4, color='r')
# Starting Price
plt.figtext(0.6, 0.8, s="Start price: $%.2f" %S0 )
# Mean ending price
plt.figtext(0.6, 0.7, "Mean final price: $%.2f" % S.mean())
# Variance of the price (within 99% confidence interval)
plt.figtext(0.6, 0.6, "VaR(0.99): $%.2f" % (S0 - q,))
# Display 1% quantile
plt.figtext(0.15, 0.6, "q(0.99): $%.2f" % q)
plt.hist(S[-1],bins = 50)
plt.xlabel('price')
plt.ylabel('frequency')
#plt.show()
plt.figure(figsize=(16,8))
fig, ax = plt.subplots()
global test
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
#graph_data = open('example.txt','r').read()
#lines = graph_data.split('\n')
xs = []
ys = []
for line in range (0,I ,1):
xs.append(line)
test =0
def animate(i):
global test
if(test < I):
#ax1.plot(xs[:test], ys[ :test])
#ax1.clear()
for y in range (0,M ,1):
ax1.plot(S[:test,:])
test= test +1
ani = animation.FuncAnimation(fig, animate, frames=100, interval=20,
blit=False)
#plt.show()
ani.save('/animation.gif', writer='imagemagick', fps=60)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment