Lesson 6,
Topic 2
In Progress
Python code that solves the tasks given at the end of the presentation
Lesson Progress
0% Complete
Run the code with the different parameters
import math
import matplotlib.pyplot as plt
a = 16807
c = 0
m = (2**31) - 1
results = []
prices = []
time = []
n = 300
def bm():
X_old = 0
T = 1
seed = 1
i = 0
t_i = 0
results.append(X_old)
while i < n:
rd = (a * seed + c) % m
seed = rd
U1 = rd/m
rd = (a * seed + c) % m
seed = rd
U2 = rd/m
R = -2*math.log(U1)
V = 2*math.pi*U2
Z1 = math.sqrt(R)*math.cos(V)
t_i_plus1 = T/n*(i+1)
X_new = X_old + math.sqrt(t_i_plus1-t_i)*Z1
results.append(X_new)
X_old = X_new
i += 1
Z2 = math.sqrt(R)*math.sin(V)
t_i = t_i_plus1
t_i_plus1 = T/n*(i+1)
X_new = X_old + math.sqrt(t_i_plus1-t_i)*Z2
results.append(X_new)
X_old = X_new
i += 1
t_i = t_i_plus1
print("Standarta Brauna kustības [0,5] rezultāti \n")
for r in results:
print(r)
print("\n\n")
plt.plot(results)
plt.xlabel("Laiks")
plt.ylabel("Akcijas cena (€)")
plt.title("Akcijas cenas simulācija ar Brauna kustību")
plt.show()
def gbm():
S_old = 50
drift = 0.05
sigma = 0.35
T = 1
seed = 2
i = 0
t_i = 0
prices.append(S_old)
time.append(t_i)
while i < n:
rd = (a * seed + c) % m
seed = rd
U1 = rd/m
rd = (a * seed + c) % m
seed = rd
U2 = rd/m
R = -2*math.log(U1)
V = 2*math.pi*U2
Z1 = math.sqrt(R)*math.cos(V)
t_i_plus1 = T/n*(i+1)
S_new = S_old*math.exp((drift-0.5*sigma**2)*(t_i_plus1-t_i)+sigma*math.sqrt(t_i_plus1-t_i)*Z1)
prices.append(S_new)
time.append(t_i_plus1)
S_old = S_new
i += 1
Z2 = math.sqrt(R)*math.sin(V)
t_i = t_i_plus1
t_i_plus1 = T/n*(i+1)
S_new = S_old*math.exp((drift-0.5*sigma**2)*(t_i_plus1-t_i)+sigma*math.sqrt(t_i_plus1-t_i)*Z1)
prices.append(S_new)
time.append(t_i_plus1)
S_old = S_new
i += 1
t_i = t_i_plus1
print("Akciju cenas simulācijas ar GBM rezultāti \n")
for p in prices:
print(p)
plt.plot(time, prices)
plt.xlabel("Laiks")
plt.ylabel("Akcijas cena (€)")
plt.title("Akcijas cenas simulācija ar Ģeometrisko Brauna kustību")
plt.show()
#bm()
gbm()