Code the statistical models
Time to run the three statistical models from Lesson 3 as real Python: the moving average, the linear regression trend, and ARIMA. It is only a handful of lines each. Press Run on every block to see the output on NCB's real prices, then build one yourself by dragging code into order.
These examples are made for Google Colab, a free website that runs Python in your browser. There is a full Colab walkthrough in the Week 2 course. Here, the Run buttons show you exactly what each block prints, so you can read the code first and run it for real later.
Step 1: put the prices in a table
pandas gives you a DataFrame, a spreadsheet you steer with code. We load NCB's twenty closing prices and peek at the last few rows.
import pandas as pd
# NCB Financial Group (NCBFG) daily closes, Jamaica Stock Exchange
prices = [52.50, 57.15, 58.00, 60.00, 58.99, 58.95, 58.50, 60.00,
61.00, 60.77, 61.00, 62.99, 62.98, 63.00, 65.00, 66.45,
70.00, 74.95, 75.35, 74.50]
ncb = pd.DataFrame({"close": prices})
print(ncb.tail())
close 15 66.45 16 70.00 17 74.95 18 75.35 19 74.50
Statistical model 1: the moving average
The naive forecast (tomorrow equals today) and the moving average are one line each with pandas.
# Naive: tomorrow = today (the last close)
naive = ncb["close"].iloc[-1]
# Moving average: the mean of the last 3 closes
ma3 = ncb["close"].tail(3).mean()
print("Naive forecast: J$", round(naive, 2))
print("Moving-avg forecast: J$", round(ma3, 2))
Naive forecast: J$ 74.5 Moving-avg forecast: J$ 74.93
Statistical model 2: the linear regression trend
numpy fits a straight trend line in one call with polyfit, then we stretch it out to forecast Tuesday, two trading days after the last close.
import numpy as np
days = np.arange(len(ncb)) # 0, 1, 2, ... 19
slope, start = np.polyfit(days, ncb["close"], 1)
tuesday = start + slope * 21 # day 21 = the next Tuesday
print("Trend rises by J$", round(slope, 2), "per day")
print("Trend forecast for Tuesday: J$", round(tuesday, 2))
Trend rises by J$ 0.98 per day Trend forecast for Tuesday: J$ 74.39
Statistical model 3: ARIMA
ARIMA is the professional time-series workhorse. The statsmodels library fits it in two lines and forecasts the next few days. The three numbers in order tell it how much recent history and recent error to lean on.
from statsmodels.tsa.arima.model import ARIMA
model = ARIMA(ncb["close"], order=(1, 1, 1)).fit()
forecast = model.forecast(2) # Monday and Tuesday
print(forecast.round(2))
20 74.62 21 74.71 Name: predicted_mean, dtype: float64
Outputs shown here are pre-generated so you can read along without a Python setup. Notice the three statistical models land close together, near J$74 to J$75, which is a good sign.
Your turn: build the moving average by hand
Drag the six code lines into the right order so the program computes the average of NCB's last four closes and prints it. Watch your indentation: the line inside the loop is pushed in.
Code lines (drag from here)
Your program (drop in order)
Getting real stock data into Colab
The prices above were typed straight into the code, which is perfect for learning. For a bigger project, you have two easy paths:
Reading a file you uploaded is just pd.read_csv("ncb.csv"). From there, every line above works the same, whether you have twenty days or twenty years.
- pandas holds prices in a DataFrame you shape with code.
- The moving average is one line; the trend is one
np.polyfit. - ARIMA from statsmodels forecasts the next days in two lines.
- All three statistical models are quick, need little data, and land in the same neighbourhood.
Next: the same idea for the machine learning models, with a chart in Python.