# import libraries
import pandas as pd
from statsforecast import StatsForecast
from statsforecast.models import WindowAverage, Naive, SeasonalNaive
import matplotlib.pyplot as plt
Python Code
# read data
= pd.read_csv("../posts/2024-10-02-ts-fundamentals-whats-a-time-series/example_ts_data.csv")
data_raw
= (
data_raw # select columns
"Country", "Product", "Date", "Revenue"]]
data_raw[[# change data types
.assign(= pd.to_datetime(data_raw["Date"]),
Date = pd.to_numeric(data_raw["Revenue"])
Revenue
)
)
# print the first few rows
print(data_raw.head())
# filter on specific series
= data_raw[(data_raw["Country"] == "United States") & (data_raw["Product"] == "Ice Cream")]
us_ic_raw
# create unique id
"unique_id"] = us_ic_raw["Country"] + "_" + us_ic_raw["Product"]
us_ic_raw[
# convert date to datetime
"Date"] = pd.to_datetime(us_ic_raw["Date"])
us_ic_raw[
# plot the data
=(10, 6))
plt.figure(figsize"Revenue"], label="Ice Cream Revenue")
plt.plot(us_ic_raw.index, us_ic_raw["Date")
plt.xlabel("Revenue")
plt.ylabel("Ice Cream Revenue in United States")
plt.title( plt.legend()
# get final data for forecasting
= us_ic_raw[["unique_id", "Date", "Revenue"]].copy()
us_ic_clean
# set up models to train
= [
models = 12), # meanf
WindowAverage(window_size # naive
Naive(), =12), # snaive
SeasonalNaive(season_length
]
= StatsForecast(
sf =models,
models='ME'
freq
)
# fit the model and forecast for 12 months ahead
= sf.forecast(df = us_ic_clean,
Y_hat_df = "Date",
time_col = "Revenue",
target_col = "unique_id",
id_col =12,
h=False)
fitted
print(Y_hat_df.head())
# convert date to be first of the month
"Date"] = Y_hat_df["Date"].dt.to_period("M").dt.to_timestamp() Y_hat_df[
# concat both df together
= pd.concat([us_ic_clean, Y_hat_df], axis=0)
combined_df
# make date the index
"Date", inplace=True)
combined_df.set_index(
print(combined_df.head())
# plot the combined data
=(10, 6))
plt.figure(figsize
# plot the original revenue data as line and forecast as dotted line
"Revenue"], label="Actual Revenue")
plt.plot(combined_df.index, combined_df["WindowAverage"], label="12 Month Avg", linestyle='dotted')
plt.plot(combined_df.index, combined_df["Naive"], label="Naive", linestyle='dotted')
plt.plot(combined_df.index, combined_df["SeasonalNaive"], label="Seasonal Naive", linestyle='dotted')
plt.plot(combined_df.index, combined_df[
# chart formatting
"Date")
plt.xlabel("Revenue")
plt.ylabel("Benchmark Forecasting Results for US Ice Cream Revenue")
plt.title(
plt.legend()
# save the plot
# plt.savefig("chart1", dpi = 300, bbox_inches = "tight")