This is the note that I took while learning the Fundamentals of Quantitative Modeling Coursera course.
Week 1 Introduction
Purpose of the course
- expose to the language of modelling
- see different models
- learn to model and critique models
- associate business process characteristics with appropriatepriate models (which model should I use?)
- understand the value & limitation of quantitative models
What is a Model
- a formal description of a business process
- equations + random variables
- simplification of complex sturcture
- models rely on assumptions
- the models are implemented in computer programmes
Examples of Models
- diamond price as a function of its weight
- spread of epidemic over time
- the relationship between demand and price (what happen to sales if I increase the price?)
- the uptake of a new product in the market (can I forcast the number of units to be sold?)
Mathmatical Functions
- linear function: $y = a x + b$ (price of diamond)
- exponential: $y = a \exp(b x)$ (early spread of epidemic)
- power function: $y = a x^b$ (the relationship between demand and price)
- logistic function: $y = L / [1 + \exp(-k(x - x_0))]$ (uptake of new product)
How Models are Used
- Prediction: from $x$ calculate $y$.
- Forecasting: for time series, tell what happens in the future.
- Optimisation: find the maximum/minimum
- Ranking & Targeting: Giving limited resources, which potential product should be targeted for potential purchases
- Explore “what-if” scenarios
- Interpreting coefficients in a model
- Sensitivity analysis: assessing the susceptibility of the model on the assumptions
Benefits of Modelling
- Identifying gaps in current understanding
- Making assumptions explicity
- Having a well-defined description of business process
- Creating an institutional memory (to replace the “smart guys” in the company)
- A decision support tool
- serendipitous (偶然的) insight generator
Key Steps in Modelling
┌──────────────────┐ ┌────────────────────┐
│ │ │ ┌───────────────┐ │
│ ┌──────────────┐ │ │ │ Sensitivity │ │
│ │Define inputs │ │ ┌──────────┐ │ │ Analysis │ │ ┌──────────────┐
│ │ & Outputs │ │ │ │ │ └───────────────┘ │ │ │ ┌──────────────┐
│ └──────────────┘ │ │formulate │ │ │ │ Fit for │ │ Implement │
│ │────▶│ model │────▶│ ┌───────────────┐ │────▶│ purpose? │────[ Yes ] ─▶│ Model │
│ ┌──────────────┐ │ │ │ │ │ Validate │ │ │ │ └──────────────┘
│ │ Define scope │ │ └──────────┘ │ │ model │ │ └──────────────┘
│ └──────────────┘ │ │ │ forecasts │ │ │
│ │ │ └───────────────┘ │ │
└──────────────────┘ └────────────────────┘ │
▲ │
│ │
└───────────────────────────────────[ No ]─────────────────────────┘
- Scope: what range would the model apply. (For instance, the price-weight relationship may only hold from 1-2 crela)
- What if the model does not work?
- if the observation is different from prediction, try to understand the reason of the difference. (the difference is very imformative)
- modelling is a continuumuous and evolutiontionary process (no steady state).
- we overcome the limitations of the model by iteration
A Vocabulary for Modeling
- Data Driven & Theory Driven
- Theory: the logical consequences given assumptions and relationships.
- Data: approximation of the underlying process that generates the observed data.
┌─────────────────────────────────────────────────────────────┐ │ Empirical <-----------------------------> Theoretical │ └─────────────────────────────────────────────────────────────┘ There is a *spectrum* for models, which can be labelled as *data driven* or *theory driven*.
-
Determinstic & Probabilistic/Stochastic
-
determinstic: given fixed input, there is always a fixed output.
-
stochastic: different output might be generated from the same input
-
- Discrete & Continuous Variables
- Static & Dynamic
- Static: try to capture a single snapshot of the business process (given a website’s installed software base, what are the chances that it is compromised today?)
- Dynamic: the evolution of the process itself is of interest. The model descries the movement from state to state. (given a person’s participation in a job training programme, how long will it take until he/she finds a job?)
Week 2 Linear Models
Introduction
- linear models
- $y = mx + b$, the slope ($m$) is constant
- example: Cost = 100 + 30 q, where q is the number of produced units
- can be optimised via linear programming
- growth and decay in discrete time
- Examples: The number of customers at time $t$; The revenue in quarter $q$
- Proportional growth: a constant percentage increase (rather than amount)
- Simple interest: interest is only earned on the principle investment → linear growth
- Compound interest: the interest itself earns interest →
- growth and decay in continous time
- classical optimisation (classical - using calculus)
Constant Proportionate Growth
┌────────┬────────┬────────┬────────┬────────┐ │ TIME │ 0 │ 1 │ 2 │ 3 │ ├────────┼────────┼────────┼────────┼────────┤ │ AMOUNT │ P0 │ P0 Θ │ P0 Θ^2 │ P0 Θ^3 │ └────────┴────────┴────────┴────────┴────────┘
- $P_0$: initial amount
- $\theta$: growth factor
- this is called geometric series
- The sum of geometric series ($S_t$) is:
Present and Future Value
If the prevailingiling interest rate (现行利率) is 4%, which options is better?
- Getting $1000 now
- Getting $1500 in ten years
This question is equal to
- How much we would have invest today, to get $1500 in ten years?
- How much $1000 would worth in ten years?
The equation is,
\[P_t = P_0 \theta^t\]since $P_t = 1000 \times 1.04^{10} = 1480.2443$, we should take 1500.
Continuous Compounding
The compounding period approachs 0, the process is continuous.
If a principle amount $P_0$ is continuously compounded at a nominal annual interest rate of $R \%$, then at year $t$, we have
\[P_t = P_0 \exp(r t)\]where $r = R / 100$.
The exponential function also describes the beginning of an epidemic.
Optimisation
Consider the demand model which gives the relationship between the quantity $Q$ and the price $P$.
\[Q = 60000 P^{-2.5}\]If the price of producing one unit of product is constant ($c = 2$), how do we maximise the profit?
\[\begin{aligned} \mathrm{Profit} &= \mathrm{Revenue} - \mathrm{Cost} \\ &= P \times Q - c\times Q \\ &= Q(P - c) \\ &= 60,000 \times P^{-2.5}(P - c) \\ &= 60,000 \times (P^{-1.5} - c \times P^{-2.5}) \end{aligned}\]Taking the derivatives.
\[\begin{aligned} \frac{d\ \mathrm{Profit}}{dP} &= 60,000 \times (-1.5 \times P^{-2.5} + 2.5c \times P^{-3.5}) \rightarrow 0 \\ &\rightarrow 2.5c \times P^{-1} = 1.5 \\ &\rightarrow P = 2.5 c / 1.5 \\ & \rightarrow P_\mathrm{opt}\approx 3.333 \;(c = 2) \end{aligned}\]generally, if the relationship follows
\[Q = a P^\beta; \mathrm{Cost} = P - c\]then the best price is
\[P_\mathrm{opt} = \frac{c b}{1 + b}\]Week 3 Probabilistic Models
Introduction
- random variables and probability distributions
- probabilistic models incorporates the uncertainty, which is good
- uncertainty == risk
Regression Models
- Linear fit of data points + prediciton interval
Probability Trees
- Propagate probabilities through a sequence of events.
Monte-Carlo Simulation
The method is used to model complicated examples. For instance, if the value of $b$ for the optimisation problem in Week 2 is a random variable following uniform distribution. We can calculate the distirubiton of the optimum price.
Example:
import numpy as np
c = 2
b = np.random.uniform(-2, -3, 100000)
popt = c * b / (1 + b)
mean, std = popt.mean(), popt.std()
print(f"The opt price is {mean:.4f}, with std of {std:.4f}")
The opt price is 3.3869, with std of 0.2797.
Markov Models
The Markov model is a dynamic model for discrete state transition. The model is expressed as probability transition matrix.
For instance, a person may change its state between employed, unemployed, and looking for job. These states were illustrated in the following graph.
┌──[ 0.2 ]──┐
│ │
▼ │
┌──────────────────┐ │
│ │ │
┌──────▶│ Unemployed │──┴─────┐
│ │ (1) │ │
│ └──────────────────┘ │
[ 0.2 ] [ 0.8 ]
│ │
│ │
│ ▼
┌──────────────────┐ ┌──────────────────┐
│ │ │ Looking │
┌─▶│ Employed │◀────[ 0.5 ]────│ for Job │◀─┐
│ │ (3) │ │ (2) │ │
│ └──────────────────┘ └──────────────────┘ │
│ │ │ │
│ │ │ │
└──[ 0.8 ]───┘ └──[ 0.5 ]──┘
The corresponding transition matrix is \(\left( \begin{matrix} 0.2 & 0.8 & 0.0 \\ 0.0 & 0.5 & 0.5 \\ 0.2 & 0.0 & 0.8 \end{matrix} \right)\) Markov chain model is characterised by the lack of memory, meaning the history of the chain will not affect the probability for the next state. This is the assumption of Markov chains.
Example
import numpy as np
def change_state(state, rand_num):
new_state = None
if state == 1:
if rand_num < 0.2: new_state = 1
else: new_state = 2
elif state == 2:
if rand_num < 0.5: new_state = 2
else: new_state = 3
elif state == 3:
if rand_num < 0.8: new_state = 3
else: new_state = 1
return new_state
def simulate(state_init, n_sample):
rand_nums = np.random.random(n_sample)
result = np.zeros(n_sample)
state = state_init
for i in range(n_sample):
state = change_state(state, rand_nums[i])
result[i] = state
return result
if __name__ == "__main__":
n_sample = 5000000
state_init = 1
result = simulate(state_init, n_sample).astype(int)
print("The stationary probabilities are (Simulation)")
for i in range(3):
print(f"P({i+1})={np.sum(result == i+1) / len(result):.4f}", end='; ')
# calculating from transition matrix
P = np.array((
(0.2, 0.8, 0.0), # pij ---> state i to j
(0.0, 0.5, 0.5),
(0.2, 0.0, 0.8),
)).T # pij ---> state j to i
s_init = np.array((1.0, 0.0, 0.0))
s = s_init.copy()
for _ in range(1000):
s = P @ s
print("\n\nStationary Probabilities are (MCMC):")
for i in range(3):
print(f"P({i+1})={s[i]:.4f}", end='; ')
# calculating from the eigen vector
eigvals, eigvecs = np.linalg.eig(P)
v_eq = np.abs(eigvecs.T[np.argmin(np.abs(eigvals - 1.0))])
v_eq = v_eq / v_eq.sum() # probability sum --> 1
print(
"\n\nStationary Probabilities are (Analytical):"
)
for i in range(3):
print(f"P({i+1})={v_eq[i]:.4f}", end='; ')
Result:
The stationary probabilities are (Simulation)
P(1)=0.1515; P(2)=0.2428; P(3)=0.6057;
Stationary Probabilities are (MCMC):
P(1)=0.1515; P(2)=0.2424; P(3)=0.6061;
Stationary Probabilities are (Analytical):
P(1)=0.1515; P(2)=0.2424; P(3)=0.6061;
Common Probability Distributions
- Bernoulli Distribution (toss a coin)
- Binomial Distribution (toss a coin many times)
- Normal Distribution (common)
The emprical rule
For normal distribution, the probability in these following ranges are
- $(\mu - \sigma, \mu + \sigma)$: 68%
- $(\mu - 2\sigma, \mu + 2\sigma)$: 95%
- $(\mu - 3\sigma, \mu + 3\sigma)$: 99.7%
Example: if the daily return of Apple’s stock follows normal distribution with $\mu = 0.13\%, \sigma = 2.34\%$, what is the probability that tomorrow Apple’s stock price increase by more than 2.47%?
- calculate Z score: $Z = (2.47 - 0.13) / 2.34 = 1$
- since the increase is 1 $\sigma$ on the right hand side of the distribution, its probability is $100\% - 50\% - 68\%/2 = 16\%$
Week 4 Regression Model
Regression Models
- A single regression model uses a single predictor $X$ to predict the mean of $Y$.
- If the relationship between $X$ and $Y$ is linear, we call it a linear regression, written as $\mathbb{E}(Y\vert X)=b_0 + b_1X$.
- The linear assisiation between two variables are captured by the correlation, which is a value between -1 and 1.
- The regression model can be used to:
- prediction
- coefficient interpreting
- how much variability is $Y$ explained by $X$? (as a numerical measure)
- The coefficient of the model can be found via the least square fit
- The fitting minimizes $(Y_\mathrm{pred} - Y_\mathrm{obs})^2$
- The difference $Y_\mathrm{pred} - Y_\mathrm{obs}$ is the residual, which allows us to assess the fitting quality.
- To assess the fitting, the two options are frequently reported.
- the $R^2$ measures how much variability of $Y$ is explained by the linear regression model. It is the square of the correlation. (The larger the better.)
- The root mean squared error (RMSE) measures the standard deviation (std) of the residuals. (The smaller the better.)
- The RMSE can be input for prediction interval, with following assumptions.
- For a fixed value of $X$, the distribution of $Y_\mathrm{obs}$ follows a normal distribuition, centerd arbound $Y_\mathrm{pred}$.
- The standerd deviation $\sigma$ of the distribution can be estimated by RMSE
- With these assumptions, we can plot $Y_\mathrm{pred} \pm 2\,\mathrm{RMSE}$ as the 95% prediction interval.
- We can also fit a curve to the data, if the linear relationship does not hold. Sometimes, the log-log plot shows linear relation.
Multiple Regression
- Multiple regression inclues many ($n$) predictor variables, meaning a vector $\mathbf{X} \in \mathbb{R}^n$ is used to predict $Y \in \mathbb{R}$.
- For two varialbes, the model is $\mathbb{E}(Y \vert X_1, X_2) = b_0 + b_1 X_1 + b_2 X_2$.
Logistic Regression
\[\mathbb{E}(Y=1\vert X=x) = \frac{\exp(x\beta)}{1 + \exp(x\beta)}\]- The logistic regression is suitable for discrete (Yes $\vert$ No) variable
- Always predict between 0 and 1