Probability Analysis: Continuous vs. Discrete Probability Distributions with Python, R and Shiny

shiny

The purpose of this post is to introduce the concept of probabilities, and some of the probability models that can be generated with Python, R and Shiny.

Here, you will be shown:

  • The importance of a normal distribution
  • How to generate a normal distribution and run a Monte Carlo simulation
  • Discrete probability distributions including the Poisson and Binomial distribution
  • How to create your own Shiny app to visualise cumulative binomial probabilities! 🙂

 
 

The concept of a normal distribution

One of the most important continuous probability distributions is the normal distribution:

rnorm

A normal distribution is one where 68% of the values drawn lie one standard deviation away from the mean of that sample.

In a normal distribution:

  1. The mean, mode and median are equal to each other.
  2. The distribution is perfectly symmetrical around the center.
  3. The distribution is symmetric, unimodal and asymptotic.

The idea of a normal distribution is an important one since it can allow for a better prediction of commonly occuring events. According to the law of large numbers, should a sample size grow large enough, the characteristics of that sample size will approximate a normal distribution, and this makes it easier to make predictions given particular data.

However, an interesting observation is that as the number of time periods increases, we are more likely to also see highly significant deviations from the mean as well, in which the overall distribution would be substantially impacted.

Normal Distributions and the Law of Large Numbers

Let’s illustrate this using an example. Using a normal distribution model generated by Python, suppose that we have a financial security with a 0.6% daily return and a 2.5% daily standard deviation:

import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

#Monte Carlo Simulation
mu=0.6
sigma=2.5
x = mu + sigma * np.random.randn(5)
num_bins = 50

# Histogram
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='blue', alpha=0.5)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
plt.plot(bins, y, 'r--')
plt.xlabel('Values')
plt.ylabel('Probability')
plt.title(r'Monte Carlo Simulation - 5')

# Spacing Adjustment
plt.subplots_adjust(left=0.15)
plt.show()

In this context, we are generating 5 random numbers with a mean of 0.6% and standard deviation of 2.5%:
montecarlo 5
 
We see that the distribution of our data is not particularly consistent, and often times our results will trade in a narrow range of -1% to 3.5% for instance; which we reasonably expect as the numbers are centered around the mean. However, let us suppose that we now run our program on 1000 observations:

import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

#Monte Carlo Simulation
mu=0.6
sigma=2.5
x = mu + sigma * np.random.randn(1000)
num_bins = 50

# Histogram
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='blue', alpha=0.5)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
plt.plot(bins, y, 'r--')
plt.xlabel('Values')
plt.ylabel('Probability')
plt.title(r'Monte Carlo Simulation - 1000')

# Spacing Adjustment
plt.subplots_adjust(left=0.15)
plt.show()

monte carlo 1000

We now see that our data is largely centred around the mean, and the histogram takes the general shape of a normal distribution, i.e. the distribution follows the 3-sigma rule where 68% of values are one standard deviation away from the mean, 95% of values lie two standard deviations away, while 99.7% of them lie within three standard deviations.

Note that while the majority of our values are now centered around the mean, the distribution also yields “extreme” values, i.e. we see that returns can differ from the mean by as much as 10 percent. This has important implications for trading strategies, since the model implies that the longer a security is held, the more chance we have of observing extreme values.

Monte Carlo Simulation and Random Walk Generation

The purpose of a Monte Carlo simulation is to observe a range of potential outcomes based on a numerical simulation. For instance, if an investor chooses to hold an asset with a given level of return and volatility, then the same can be modelled to examine a range of potential gains and losses over a specified period.

The below shows how to calculate a price path of a stock using a random walk for a given level of return (mu) and volatility (vol). Moreover, our histogram plots allow us to observe a range of potential returns throughout the period as well as frequency of those returns.

import numpy as np
import math
import matplotlib.pyplot as plt
from scipy.stats import norm
 
#Define Variables
T = 250 #Number of trading days (we also run at 1000 for the purposes of comparison).
mu = 0.09 #Return
vol = 0.1 #Volatility
 
daily_returns=np.random.normal(mu/T,vol/math.sqrt(T),T)+1
  
price_list = [200]
for x in daily_returns:
    price_list.append(price_list[-1]*x)
  
#Generate Plots
plt.plot(price_list)
plt.hist(daily_returns-1, 100) #Note that we run the lines plt.plot() and plt.hist() separately with plt.show(), not simultaneously.
plt.show()

 
Observations and Graphs

We see that when we run the simulation across 1000 trading days as opposed to 250, the distribution of returns comes to represent one where we do not positive or negative skew since the extremities of returns are identical at +/-0.1. In this regard, the higher our number of observations (trading days), the more our histogram comes to represent a normal distribution. Whereas, the lower the number of trading days, we see that we have negative skew in that the lowest return was -0.02 whereas the highest return was 0.015.

10% Volatility Over 250 Trading Days

250 trading days histogram

10% Volatility Over 1000 Trading Days

1000 trading days

As we can see, our distribution takes more of a normal U-shape as the number of trading days is increased from 250 to 1000.

Random Walk at 10% Volatility

figure_10 volatility

Random Walk at 30% Volatility

figure_30volatility

When we increase the vol variable from 0.1 (10%) to 0.3 (30%), we see that while our random walk shows higher peaks and valleys, there is a lower return overall – demonstrating that the higher the volatility, the lower the effective return.
 
 

Discrete Probability Distributions

However, what about distributions that are not necessarily normal? Let us take a look at two particular distributions that fit into the discrete category:

  • Poisson Distribution
  • Binomial Distribution

Poisson Distribution

A Poisson Distribution is a probability distribution which calculates the probability of a set of independent occurrences within a fixed time or space. e.g. Let us suppose that a prestigious college receives 1000 applications in a particular time interval. On average, 20 applications are accepted.

However, we know that while the average is 20, our distribution allows for the possibility that the actual number of applications accepted could be greater or less than 20. In this regard, the Poisson distribution graphs by means of a histogram the probability or frequency of occurring events that both coincide with the average as well as deviate from the average.

As a case in point, we demonstrate in Python and R the Poisson distribution for 1000 independent trades (trials) given a lambda value of 20:

Python

#Import libraries:
import numpy as np
import matplotlib.pyplot as plt
 
#l=lambda and x=number of observations approximating normal distribution
l=20
x=1000
 
#s = Poisson Distribution
s = np.random.poisson(l, x)
#Histogram plotted with 10 bins
plt.hist(s, 10)
plt.show()

poisson python

R

x=0:40
lambda=20
#dpois = Poisson Distribution
probability = dpois(x,lambda)
#Histogram plot
plot(x, probability, type="h", col="blue")

poissonr

From the above plots, we can see that while the distribution peaks at 20, we have varying degrees of probability across our histogram.

Binomial Distribution

In conducting probability analysis, the two variables that take account of the chance of an event happening are N (number of observations) and λ (lambda – our hit rate/chance of occurrence in a single interval).

probability = 1 – ((1 – λ)N)

For instance, let us suppose that the odds of scoring a goal in the first five minutes of a football match is 0.05 – this is our probability.

Now, let us suppose that 50 different soccer matches are played. The probability that a goal will be scored in the first five minutes of a match now increases to over 92%:

1 – ((1 – 0.05)50) = 0.923055

Based on the law of large numbers, the larger the number of trials; the larger the probability of an event happening even if the probability within a single trial is very low. So, let us generate a cumulative binomial probability to demonstrate how probability increases given an increase in the number of trials.

Firstly, we define a function (with probabilities set at 2%, 4%, and 6%, along with trials of up to 100:
 

par(bg = '#191661', fg = '#ffffff', col.main = '#ffffff', col.lab = '#ffffff', col.axis = '#ffffff')

#lambda = probability of event occuring in a single trial
#powers = number of trials
#mu = overall probability given n number of trials

muCalculation <- function(lambda, powers) {1 - ((1 - lambda)^powers)}
probability_at_lambda <- sapply(c(0.02, 0.04, 0.06), muCalculation, seq(0, 100, 1))

Then, we can set up our data as a data frame and then plot as normal:

probability_at_lambdadf=data.frame(probability_at_lambda)
col_headings <- c("probability1","probability2","probability3")
names(probability_at_lambdadf) <- col_headings
probability_at_lambdadf
attach(probability_at_lambdadf)
plot(probability_at_lambdadf$probability1,type="o",col="#b1aef4", xlab="N", ylab="Probability", xlim=c(0, 100), ylim=c(0.0, 1.0), pch=19)
lines(probability_at_lambdadf$probability2,type="o",col="red", xlab="N", ylab="Probability2", xlim=c(0, 100), ylim=c(0.0, 1.0), pch=19)
lines(probability_at_lambdadf$probability3,type="o",col="green", xlab="N", ylab="Probability3", xlim=c(0, 100), ylim=c(0.0, 1.0), pch=19)
title(main="Probability Chart")
grid(nx = NULL, ny = NULL, col = "lightgray", lty = "dotted",
     lwd = par("lwd"), equilogs = TRUE)
legend("bottomright", probability[2], c("probability_at_lambda_1","probability_at_lambda_2", "probability_at_lambda_3"), cex=0.6, col=c("#b1aef4","red","green"), pch=21:22, lty=1:2)
proc.time()

Sample Table

Here is a sample table with the calculated probabilities (probability_at_lambdadf):

probability

Plot

Accordingly, here is a plot of the probabilities:

probability
 
 

Analyse Cumulative Binomial Probability with a Shiny Web Application

This is an example of a Shiny Web application that can calculate cumulative binomial probabilities on the fly.

You’ll remember that our previous R script invoked a function to calculate binomial probabilities based on lambda (the probability of an event happening), and the power value (or number of trials).

The idea is that while the probability of an individual event happening may be low, the cumulative probability of the event happening increases with the number of trials.

1 - ((1 - λ)N)

Here is an example of a Shiny Web App that allows us to manipulate the lambda values using a set of sliders and automatically update the probability curve.

To run this app, open the R Studio console and click File -> New File -> Shiny Web App and select either Single File to paste the ui.R and server.R codes together, or Multiple File to paste them separately.

shiny

Additionally, if you are new to Shiny you can find my full tutorial on Sitepoint that describes how to build and run a Shiny app from scratch.

ui.R

A few points when setting up the UI (User Interface):

  • lambda represents the probability of an event occurring in a single trial
  • The slider input allows the user to set different values for lambda based on the associated probability
  • The plot is then outputted with the output being designated the name "ProbPlot".
library(shiny)

# Define UI for application that draws a probability plot
shinyUI(fluidPage(
  
  # Application title
  titlePanel("Cumulative Binomial Probability Plot"),
  
  # Sidebar with a slider input for value of lambda
  sidebarLayout(
    sidebarPanel(
      sliderInput("lambda",
                  "Probability 1:",
                  min = 0,
                  max = 1,
                  value = 0.01),
      sliderInput("lambda2",
                  "Probability 2:",
                  min = 0,
                  max = 1,
                  value = 0.01),
      sliderInput("lambda3",
                  "Probability 3:",
                  min = 0,
                  max = 1,
                  value = 0.01)
    ),
    
    # Show a plot of the generated probability plot
    mainPanel(
      plotOutput("ProbPlot")
    )
  )
))

server.R

Now, we set up the server - this is the part that takes the inputs and calculates the output that is eventually shown in the UI.

  • The lambda values represent the inputs that we defined in the UI; i.e. the user sets the probability from the slider.
  • The probability function is defined: {1 - ((1 - lambda)^powers)}
  • The separate probability arrays are then calculated (probability_at_lambda, probability_at_lambda2, probability_at_lambda3)
  • The probability is then plotted.
library(shiny)
library(ggplot2)
library(scales)

# Shiny Application
shinyServer(function(input, output) {
  
  # Reactive expressions
  output$ProbPlot <- renderPlot({
    
    # generate lambda based on input$lambda from ui.R
    l=0:1
    lambda <- seq(min(l), max(l), length.out = input$lambda)
    probability=lambda
    l2=0:1
    lambda2 <- seq(min(l2), max(l2), length.out = input$lambda2)
    probability=lambda
    l3=0:1
    lambda3 <- seq(min(l3), max(l3), length.out = input$lambda3)
    probability=lambda
    
    # generate trials based on lambda value
    muCalculation <- function(lambda, powers) {1 - ((1 - lambda)^powers)}
    probability_at_lambda <- sapply(input$lambda, muCalculation, seq(0, 100, 1))
    probability_at_lambda2 <- sapply(input$lambda2, muCalculation, seq(0, 100, 1))
    probability_at_lambda3 <- sapply(input$lambda3, muCalculation, seq(0, 100, 1))
    
    # draw the probability
    par(bg = '#191661', fg = '#ffffff', col.main = '#ffffff', col.lab = '#ffffff', col.axis = '#ffffff')
    plot(probability_at_lambda,type="o",col="#b1aef4", xlab="N", ylab="Probability", xlim=c(0, 100), ylim=c(0.0, 1.0), pch=19)
    lines(probability_at_lambda2,type="o",col="red", xlab="N", ylab="Probability2", xlim=c(0, 100), ylim=c(0.0, 1.0), pch=19)
    lines(probability_at_lambda3,type="o",col="green", xlab="N", ylab="Probability3", xlim=c(0, 100), ylim=c(0.0, 1.0), pch=19)
    title(main="Cumulative Binomial Probability")
  })
  
})

 
 

Conclusion

Today, you have learned how to:

  • Generate a normal distribution and Monte Carlo simulation in Python
  • Identify the differences between continuous and discrete probability distributions
  • Generate Poisson and Binomial Distributions using R
  • Use Shiny to visualise cumulative binomial probability

Code Scripts and Datasets

Hope you enjoyed this tutorial!

All code scripts and datasets for my tutorials are available by subscribing to my mailing list.

Upon subscription, you will receive full access to the codes and datasets for my tutorials, as well as a comprehensive course in regression analysis in both Python and R.

Leave a Reply

Your email address will not be published. Required fields are marked *