Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
holoviz
GitHub Repository: holoviz/panel
Path: blob/main/examples/apps/django_multi_apps/gbm/pn_model.py
2014 views
1
import hvplot
2
import hvplot.pandas
3
import numpy as np
4
import pandas as pd
5
import param
6
7
import panel as pn
8
9
10
class GBM(param.Parameterized):
11
# interface
12
mean = param.Number(default=5, bounds=(.0, 25.0))
13
volatility = param.Number(default=5, bounds=(.0, 50.0))
14
maturity = param.Integer(default=1, bounds=(0, 25))
15
n_observations = param.Integer(default=10, bounds=(2, 100))
16
n_simulations = param.Integer(default=20, bounds=(1, 500))
17
refresh = pn.widgets.Button(name="Refresh", button_type='primary')
18
19
def __init__(self, **params):
20
super().__init__(**params)
21
22
# update the plot for every changes
23
# @param.depends('mean', 'volatility', 'maturity', 'n_observations', 'n_simulations', watch=True)
24
# refresh the plot only on button refresh click
25
@param.depends('refresh.clicks')
26
def update_plot(self, **kwargs):
27
df_s = pd.DataFrame(index=range(0, self.n_observations))
28
29
for s in range(0, self.n_simulations):
30
name_s = f"stock_{s}"
31
df_s[name_s] = self.gbm(spot=100,
32
mean=self.mean/100,
33
vol=self.volatility/100,
34
dt=self.maturity / self.n_observations,
35
n_obs=self.n_observations)
36
37
return df_s.hvplot(grid=True, colormap='Paired', value_label="Level", legend=False)
38
39
@staticmethod
40
def gbm(spot: float, mean: float, vol: float, dt: float, n_obs: int) -> np.ndarray:
41
""" Geometric Brownian Motion
42
43
:param spot: spot value
44
:param mean: mean annualised value
45
:param vol: volatility annualised value
46
:param dt: time steps
47
:param n_obs: number of observation to return
48
:return: a geometric brownian motion np.array()
49
"""
50
# generate normal random
51
rand = np.random.standard_normal(n_obs)
52
# initialize the parameters
53
S = np.zeros_like(rand)
54
S[0] = spot
55
# loop to generate the brownian motion
56
for t in range(1, n_obs):
57
S[t] = S[t - 1] * np.exp((mean - (vol ** 2) / 2) * dt + vol * rand[t] * np.sqrt(dt))
58
# return the geometric brownian motion
59
return S
60
61