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.

65

6.3.2 Model Specification in PyMC3

Now that the returns have been calculated attention will turn towards specifying the Bayesian

model via the priors described above. As in previous chapters the model is instantiated via the

pm.Model() syntax in a with context. Each prior is then defined as above:

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

)

..

..

It remains to sample the model with the No-U-Turn Sampler MCMC procedure.

6.3.3 Fitting the Model with NUTS

Now that the model has been specified it is possible to run the NUTS MCMC sampler and

generate a traceplot in a similar manner to that carried out in the previous chapter on Bayesian

Linear Regression. Thankfully PyMC3 abstracts much of the implementation details of NUTS

away from us, allowing us to concentrate on the important procedure of model specification.

For this example 2000 samples are used in the NUTS sampler. Note that this will take some

time to calculate. It took 15-20 minutes on my desktop PC to produce the plots below. The

API for sampling is very straightforward. Under a with context the model simply utilises the

pm.sample method to produce a trace object that can later be used for visualisation of marginal

parameter distributions and the sample trace itself:

..

..

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

with model:

trace = pm.sample(samples)

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

Saved successfully!

Ooh no, something went wrong!