importmatplotlib.pyplotaspltimportseabornassnsfromstatsmodels.graphics.tsaplotsimportplot_acfsns.set_theme(context="paper",style="ticks",palette="colorblind")_,ax=plt.subplots(figsize=(10,13),nrows=3)sns.lineplot(df,x="ds",y="y",color="k",ax=ax[0])ax[0].set_title("Walmart Sales in CA")ax[0].set_ylabel("Sales")sns.lineplot((df.loc[(df.ds>="2015-01-01")&(df.ds<"2016-01-01")]),x="ds",y="y",color="k",ax=ax[1],)ax[1].set_title("Walmart Sales in CA in 2015")ax[1].set_ylabel("Sales")plot_acf(df.y,ax=ax[2],color="k")
defforecast_test(forecaster_pred:callable,df_train:pd.DataFrame,df_test:pd.DataFrame,)->pd.DataFrame:"""Generate forecasts for tests :param forecaster_pred: forecasting function/method :param df_train: train dataframe :param df_test: test dataframe """dfs_pred=[]foriinrange(len(df_test)):logger.debug(f"Prediction Step: {i}")df_pred_input_i=pd.concat([df_train,df_test[:i]]).reset_index(drop=True)df_pred_output_i=forecaster_pred(df_pred_input_i)df_pred_output_i["step"]=idfs_pred.append(df_pred_output_i)df_y_hat=pd.concat(dfs_pred)returndf_y_hat
defvisualize_predictions(df_train:pd.DataFrame,df_test:pd.DataFrame,df_pred:pd.DataFrame,model_name:str,n_ahead:Optional[int]=None,title:Optional[str]=None,ax:Optional[plt.axes]=None,)->None:""" Visualizes the forecasts :param df_train: train dataframe :param df_test: test dataframe :param df_pred: prediction dataframe :param model_name: which model to visualize :param n_ahead: which future step to visualze :param title: title of the chart :param ax: matplotlib axes """ifaxisNone:_,ax=plt.subplots(figsize=(10,6.18))sns.lineplot(df_train,x="ds",y="y",ax=ax)sns.lineplot(df_test,x="ds",y="y",color="k",ax=ax)ifn_aheadisNone:sns.lineplot(df_pred,x="ds",y=model_name,hue="step",linestyle="dashed",ax=ax)else:dfs_pred_n_ahead=[]foriindf_pred.step.unique():dfs_pred_n_ahead.append(df_pred.loc[df_pred.step==i].iloc[n_ahead-1:n_ahead])df_pred_n_ahead=pd.concat(dfs_pred_n_ahead)sns.lineplot(df_pred_n_ahead,x="ds",y=model_name,linestyle="dashed",ax=ax)ax.set_title("Sales Forecast"iftitleisNoneelsetitle)ax.set_ylabel("Sales")ax.set_xlabel("Date")# ax.legend(prop={'size': 15})# ax.grid()
defevaluate_step(df_pred:pd.DataFrame,df_true:pd.DataFrame)->pd.DataFrame:"""Metrics averaged over all series, one column per model."""df=df_pred.merge(df_true,on=["unique_id","ds"],how="left")models=[cforcindf.columnsifcnotin("unique_id","ds","y","step","index")]returnevaluate(df,metrics=[mse,mae,rmse],models=models,agg_fn="mean")