13.08.2022 Views

advanced-algorithmic-trading

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

68

"""

Download, calculate and plot the AMZN logarithmic returns.

"""

print("Downloading and plotting AMZN log returns...")

amzn = pdr.get_data_yahoo("AMZN", start_date, end_date)

amzn["returns"] = amzn["Adj Close"]/amzn["Adj Close"].shift(1)

amzn.dropna(inplace=True)

amzn["log_returns"] = np.log(amzn["returns"])

amzn["log_returns"].plot(linewidth=0.5)

plt.ylabel("AMZN daily percentage returns")

plt.show()

return amzn

def configure_sample_stoch_vol_model(log_returns, samples):

"""

Configure the stochastic volatility model using PyMC3

in a ’with’ context. Then sample from the model using

the No-U-Turn-Sampler (NUTS).

Plot the logarithmic volatility process and then the

absolute returns overlaid with the estimated vol.

"""

print("Configuring stochastic volatility with PyMC3...")

model = pm.Model()

with model:

sigma = pm.Exponential(’sigma’, 50.0, testval=0.1)

nu = pm.Exponential(’nu’, 0.1)

s = GaussianRandomWalk(’s’, sigma**-2, shape=len(log_returns))

logrets = pm.StudentT(

’logrets’, nu,

lam=pm.math.exp(-2.0*s),

observed=log_returns

)

print("Fitting the stochastic volatility model...")

with model:

trace = pm.sample(samples)

pm.traceplot(trace, model.vars[:-1])

plt.show()

print("Plotting the log volatility...")

k = 10

opacity = 0.03

plt.plot(trace[s][::k].T, ’b’, alpha=opacity)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!