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.

41

Finally we specify the Metropolis sampler to be used and then actually sample(..) the results.

These results are stored in the trace variable:

# Use PyMC3 to construct a model context

basic_model = pymc3.Model()

with basic_model:

# Define our prior belief about the fairness

# of the coin using a Beta distribution

theta = pymc3.Beta("theta", alpha=alpha, beta=beta)

# Define the Bernoulli likelihood function

y = pymc3.Binomial("y", n=n, p=theta, observed=z)

# Carry out the MCMC analysis using the Metropolis algorithm

# Use Maximum A Posteriori (MAP) optimisation as initial value for MCMC

start = pymc3.find_MAP()

# Use the Metropolis algorithm (as opposed to NUTS or HMC, etc.)

step = pymc3.Metropolis()

# Calculate the trace

trace = pymc3.sample(

iterations, step, start, random_seed=1, progressbar=True

)

Notice how the specification of the model via the PyMC3 API is akin to the actual mathematical

specification of the model with minimal "boilerplate" code. We will demonstrate the

power of this API in later chapters when we come to specify some more complex models.

Now that the model has been specified and sampled, we wish to plot the results. We create

a histogram from the trace (the list of all accepted samples) of the MCMC sampling using

50 bins. We then plot the analytic prior and posterior beta distributions using the SciPy

stats.beta.pdf(..) method. Finally, we add some labelling to the graph and display it:

# Plot the posterior histogram from MCMC analysis

bins=50

plt.hist(

trace["theta"], bins,

histtype="step", normed=True,

label="Posterior (MCMC)", color="red"

)

# Plot the analytic prior and posterior beta distributions

x = np.linspace(0, 1, 100)

plt.plot(

x, stats.beta.pdf(x, alpha, beta),

"--", label="Prior", color="blue"

)

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

Saved successfully!

Ooh no, something went wrong!