python-Mcmc 墨蓝 2021-11-19 14:08 197阅读 0赞 Python pandas的效率比较: 1 from time import time 2 from math import exp,sqrt,log 3 from random import gauss,seed 4 seed(20000) 5 t0 = time() 6 7 S0 = 100 8 K = 105 9 T = 1.0 10 r = 0.05 11 sigma = 0.2 12 M = 50 13 dt = T / M 14 I = 250000 15 16 S = [] 17 for i in range(I): 18 path = [] 19 for t in range(M + 1): 20 if(t == 0): 21 path.append(S0) 22 else: 23 z = gauss(0.0,1.0) 24 St = path[t-1] * exp((r - 0.5 * sigma ** 2) * dt + sigma * sqrt(dt) * z) 25 path.append(St) 26 S.append(path) 27 28 C0 = exp(-r * T) * sum([max(path[-1]-K,0) for path in S]) / I 29 30 tpy = time() - t0 31 print "European Option Vlue %7.3f" % C0 32 print "Duration in Seconds %7.3f" % tpy 引用numpy 1 import math 2 import numpy as np 3 from time import time 4 5 np.random.seed(20000) 6 t0 = time() 7 8 S0 = 100 9 K = 105 10 T = 1.0 11 r = 0.05 12 sigma = 0.2 13 M = 50 14 dt = T / M 15 I = 250000 16 17 S = np.zeros((M+1,I)) 18 S[0] = S0 19 for t in range(1,M+1): 20 z = np.random.standard_normal(I) 21 S[t] = S[t-1] * np.exp((r - 0.5 * sigma ** 2) * dt + sigma * math.sqrt(dt) * z) 22 23 C0 = math.exp(-r * T) * np.sum(np.maximum(S[-1]-K,0)) / I 24 25 tpy = time() - t0 26 print "European Option Vlue %7.3f" % C0 27 print "Duration in Seconds %7.3f" % tpy 1 import math 2 from numpy import * 3 from time import time 4 5 random.seed(20000) 6 t0 = time() 7 8 S0 = 100 9 K = 105 10 T = 1.0 11 r = 0.05 12 sigma = 0.2 13 M = 50 14 dt = T / M 15 I = 250000 16 17 S = S0 * exp(cumsum((r - 0.5 * sigma ** 2) * dt + sigma * math.sqrt(dt) * random.standard_normal((M+1,I)), axis=0)) 18 S[0] = S0 19 20 print maximum(S[-1]-K,0) 21 22 C0 = math.exp(-r * T) * sum(maximum(S[-1]-K,0)) / I 23 24 tpy = time() - t0 25 print "European Option Vlue %7.3f" % C0 26 print "Duration in Seconds %7.3f" % tpy 转载于:https://www.cnblogs.com/wn19910213/p/5103830.html
还没有评论,来说两句吧...