Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import datetime
- import pprint
- import matplotlib.pyplot as plt
- import numpy as np
- import pandas as pd
- import pandas_datareader as pdr
- import pymc3 as pm
- from pymc3.distributions.timeseries import GaussianRandomWalk
- import seaborn as sns
- def obtain_amazon_prices(start_date, end_date):
- print("Downloading and plotting AWZN 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 stoch_vol_model(log_returns, samples):
- print("Configuring stochastic volatility with PyMC3...")
- model = pm.Model()
- with model:
- sigma = pm.Exponential('sigma', 10.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) #pm.traceplot(trace, model.vars[:-1])
- plt.show()
- print("Plotting the log volatility...")
- k = 10 #step size
- opacity = 0.03
- plt.plot(trace[s][::k].T, 'b', alpha=opacity)
- plt.xlabel('Time')
- plt.ylabel('Log volatility')
- plt.show()
- print("Plotting the absolute returns overlaid with vol...")
- plt.plot(np.abs(np.exp(log_returns))-1.0, linewidth=0.5)
- plt.plot(np.exp(trace[s][::k].T), 'r', alpha=opacity)
- plt.xlabel("Trading days")
- plt.ylabel("Absolute returns/volatility")
- plt.show()
- if __name__ == '__main__':
- print(pm.__version__)
- start = datetime.datetime(2006, 1, 1)
- end = datetime.datetime(2015, 12, 31)
- amzn = obtain_amazon_prices(start, end)
- log_returns = np.array(amzn["log_returns"])
- samples = 2000;
- stoch_vol_model(log_returns, samples)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement