plot_TSLM_forecast <- function(sales_data, product_id, start_date, partition_date) {
  fc_avg_column <- paste0("fc_avg.", product_id)
  
  # Read and preprocess the data
  fc_avg_tsibble <- sales_data |>
    mutate(Date = as.Date(Date, format = "%Y-%m-%d")) |>
    select(Date, all_of(fc_avg_column)) |>
    rename(sales = all_of(fc_avg_column)) |>
    as_tsibble(index = Date)

  # Split the data into training and validation sets based on the partition date
  train.fc_avg_tsibble <- fc_avg_tsibble |>  filter_index( start_date ~ partition_date)
  valid.fc_avg_tsibble <- fc_avg_tsibble |> filter(Date > as.Date(partition_date))
  
  # Fit a TSLM model with seasonality and quadratic trend
  train.lm <- train.fc_avg_tsibble |> 
    model(TSLM(sales ~ trend() + I(trend()^2) + season()))
  
  # Generate forecasts for validation period
  h <- nrow(valid.fc_avg_tsibble)
  fc.lm <- train.lm |> forecast(h = h)
  
  # Report on the model
  report(train.lm)

  # Calculate accuracy metrics
  accuracy_metrics <- accuracy(fc.lm, valid.fc_avg_tsibble)

  # Plot the model and residuals
  p.model <- train.fc_avg_tsibble |>
    autoplot(sales) +
    geom_line(data = valid.fc_avg_tsibble, aes(x = Date, y = sales), colour = "black") + # actual data in validation period
    geom_line(data = fc.lm, aes(x = Date, y = .mean), colour = "blue1", linetype = "dashed", size = 0.3) +
    autolayer(fitted(train.lm), level = NULL, colour="blue1", size = 0.3) +
    xlab("Date") + ylab("Sales") +
    theme(legend.position = "none") +
    geom_vline(xintercept = as.numeric(as.Date(partition_date)), linetype = "solid", color = "grey55", size = 0.6) +
    scale_x_date(date_breaks = "6 months", date_labels = "%Y %b") # Monthly scale for x-axis

  # Error plot
  train_errors <- train.fc_avg_tsibble
  #train_errors$sales_forecast <- fitted(train.lm)
  fitted_values <- fitted(train.lm) |>
                  as_tibble() |>
                  mutate(Date = as.Date(Date, format = "%Y-%m-%d")) |>
                  select(Date, sales = .fitted) |>
                  as_tsibble(index = Date)

  train_errors$error <- train_errors$sales - fitted_values$sales

  valid_errors <- valid.fc_avg_tsibble
  valid_errors$sales_forecast <- fc.lm$.mean
  valid_errors$error <- valid_errors$sales - valid_errors$sales_forecast

  all_errors <- bind_rows(train_errors, valid_errors)
  p.error <- ggplot(all_errors, aes(x = Date, y = error)) +
    geom_line(colour = "red") +
    geom_hline(yintercept = 0, linetype = "dashed") +
    xlab("Time") + ylab("Error") +
    theme_minimal() +
    scale_x_date(date_breaks = "6 months", date_labels = "%Y %b") # Monthly scale for x-axis
  
  print(p.model)
  print(p.error)
  print(accuracy_metrics)
}

 sales.data <- read.csv("project_data.csv")

全部data去 train/valid

 start_date <- "2021-05-07"
 partition_date <- "2023-03-23"
 
 plot_TSLM_forecast(sales.data, "1272962", start_date, partition_date)
## Series: sales 
## Model: TSLM 
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -25.350  -6.249   0.266   6.171  49.956 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)    1.765e+01  1.628e+00  10.840  < 2e-16 ***
## trend()        6.933e-03  8.471e-03   0.818 0.413414    
## I(trend()^2)   3.418e-06  1.194e-05   0.286 0.774793    
## season()week2  4.000e+00  1.567e+00   2.552 0.010923 *  
## season()week3  5.271e+00  1.567e+00   3.364 0.000813 ***
## season()week4  2.022e+00  1.567e+00   1.290 0.197419    
## season()week5 -2.671e+00  1.567e+00  -1.705 0.088740 .  
## season()week6 -1.629e+00  1.567e+00  -1.040 0.298819    
## season()week7 -1.333e+00  1.567e+00  -0.850 0.395431    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 10.97 on 677 degrees of freedom
## Multiple R-squared: 0.08585, Adjusted R-squared: 0.07505
## F-statistic: 7.948 on 8 and 677 DF, p-value: 2.9162e-10
## Warning: The output of `fortify(<fable>)` has changed to better suit usage with the ggdist package.
## If you're using it to extract intervals, consider using `hilo()` to compute intervals, and `unpack_hilo()` to obtain values.
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Plot variable not specified, automatically selected `.vars = .fitted`
## Warning in geom_line(eval_tidy(expr(aes(!!!aes_spec))), data = object, ..., :
## Ignoring unknown parameters: `level`

## # A tibble: 1 × 10
##   .model                  .type    ME  RMSE   MAE   MPE  MAPE  MASE RMSSE   ACF1
##   <chr>                   <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl>
## 1 TSLM(sales ~ trend() +… Test  0.298  5.79  4.45 -5.96  20.4   NaN   NaN 0.0903
 plot_TSLM_forecast(sales.data, "1394919", start_date, partition_date)
## Series: sales 
## Model: TSLM 
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -111.066  -22.145   -3.292   20.834  143.325 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)    7.520e+01  5.520e+00  13.622  < 2e-16 ***
## trend()        9.812e-02  2.873e-02   3.415 0.000675 ***
## I(trend()^2)  -2.438e-04  4.049e-05  -6.020 2.86e-09 ***
## season()week2  1.473e+01  5.315e+00   2.772 0.005727 ** 
## season()week3  2.923e+01  5.315e+00   5.500 5.37e-08 ***
## season()week4  1.866e+01  5.315e+00   3.512 0.000475 ***
## season()week5  2.091e+00  5.315e+00   0.393 0.694152    
## season()week6  2.395e+00  5.315e+00   0.451 0.652384    
## season()week7 -4.124e-01  5.315e+00  -0.078 0.938169    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 37.2 on 677 degrees of freedom
## Multiple R-squared: 0.2166,  Adjusted R-squared: 0.2074
## F-statistic:  23.4 on 8 and 677 DF, p-value: < 2.22e-16
## Warning: The output of `fortify(<fable>)` has changed to better suit usage with the ggdist package.
## If you're using it to extract intervals, consider using `hilo()` to compute intervals, and `unpack_hilo()` to obtain values.
## Plot variable not specified, automatically selected `.vars = .fitted`
## Warning in geom_line(eval_tidy(expr(aes(!!!aes_spec))), data = object, ..., :
## Ignoring unknown parameters: `level`

## # A tibble: 1 × 10
##   .model                   .type    ME  RMSE   MAE   MPE  MAPE  MASE RMSSE  ACF1
##   <chr>                    <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 TSLM(sales ~ trend() + … Test   15.1  23.6  19.3  18.9  39.4   NaN   NaN 0.338
 plot_TSLM_forecast(sales.data, "1602373", start_date, partition_date)
## Series: sales 
## Model: TSLM 
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -57.021 -15.431  -3.982   9.530 149.716 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)    4.145e+01  3.900e+00  10.626  < 2e-16 ***
## trend()       -3.314e-02  2.030e-02  -1.633   0.1030    
## I(trend()^2)   2.090e-05  2.861e-05   0.730   0.4654    
## season()week2  8.403e+00  3.755e+00   2.238   0.0256 *  
## season()week3  2.005e+01  3.755e+00   5.339 1.28e-07 ***
## season()week4  1.231e+01  3.755e+00   3.279   0.0011 ** 
## season()week5  1.270e+00  3.755e+00   0.338   0.7352    
## season()week6  3.963e-01  3.755e+00   0.106   0.9160    
## season()week7 -3.111e+00  3.755e+00  -0.828   0.4078    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 26.29 on 677 degrees of freedom
## Multiple R-squared: 0.09799, Adjusted R-squared: 0.08733
## F-statistic: 9.194 on 8 and 677 DF, p-value: 4.6349e-12
## Warning: The output of `fortify(<fable>)` has changed to better suit usage with the ggdist package.
## If you're using it to extract intervals, consider using `hilo()` to compute intervals, and `unpack_hilo()` to obtain values.
## Plot variable not specified, automatically selected `.vars = .fitted`
## Warning in geom_line(eval_tidy(expr(aes(!!!aes_spec))), data = object, ..., :
## Ignoring unknown parameters: `level`

## # A tibble: 1 × 10
##   .model                   .type    ME  RMSE   MAE   MPE  MAPE  MASE RMSSE  ACF1
##   <chr>                    <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 TSLM(sales ~ trend() + … Test  -14.3  18.0  15.0 -111.  112.   NaN   NaN 0.203

抓前16週(15 train / 1 validation)

 start_date <- "2022-12-29"
 partition_date <- "2023-04-13"
 
 plot_TSLM_forecast(sales.data, "1272962", start_date, partition_date)
## Series: sales 
## Model: TSLM 
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -19.0201  -3.8496  -0.6457   5.2748  22.9431 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   14.7082757  2.8260079   5.205 1.09e-06 ***
## trend()        0.3338939  0.0982553   3.398 0.000985 ***
## I(trend()^2)  -0.0025481  0.0008896  -2.864 0.005125 ** 
## season()week2  3.2214875  2.7551739   1.169 0.245168    
## season()week3  4.4833837  2.7548843   1.627 0.106890    
## season()week4  6.0170427  2.7547413   2.184 0.031354 *  
## season()week5 -3.9108686  2.7547413  -1.420 0.158905    
## season()week6 -2.9003504  2.7548843  -1.053 0.295047    
## season()week7 -3.0180693  2.7551739  -1.095 0.276046    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 7.658 on 97 degrees of freedom
## Multiple R-squared: 0.2846,  Adjusted R-squared: 0.2256
## F-statistic: 4.823 on 8 and 97 DF, p-value: 5.1064e-05
## Warning: The output of `fortify(<fable>)` has changed to better suit usage with the ggdist package.
## If you're using it to extract intervals, consider using `hilo()` to compute intervals, and `unpack_hilo()` to obtain values.
## Plot variable not specified, automatically selected `.vars = .fitted`
## Warning in geom_line(eval_tidy(expr(aes(!!!aes_spec))), data = object, ..., :
## Ignoring unknown parameters: `level`

## # A tibble: 1 × 10
##   .model                  .type    ME  RMSE   MAE   MPE  MAPE  MASE RMSSE   ACF1
##   <chr>                   <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl>
## 1 TSLM(sales ~ trend() +… Test   5.28  6.78  5.28  18.3  18.3   NaN   NaN -0.311
 plot_TSLM_forecast(sales.data, "1394919", start_date, partition_date)
## Series: sales 
## Model: TSLM 
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -27.121 -10.051  -2.198  11.341  36.424 
## 
## Coefficients:
##                Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   37.852845   5.420133   6.984 3.61e-10 ***
## trend()        0.225463   0.188448   1.196 0.234450    
## I(trend()^2)  -0.003181   0.001706  -1.864 0.065348 .  
## season()week2 18.830150   5.284277   3.563 0.000570 ***
## season()week3 19.598946   5.283722   3.709 0.000346 ***
## season()week4 28.240770   5.283447   5.345 5.99e-07 ***
## season()week5  7.355621   5.283447   1.392 0.167045    
## season()week6  3.876834   5.283722   0.734 0.464882    
## season()week7  4.737741   5.284277   0.897 0.372167    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 14.69 on 97 degrees of freedom
## Multiple R-squared: 0.3715,  Adjusted R-squared: 0.3197
## F-statistic: 7.167 on 8 and 97 DF, p-value: 2.0147e-07
## Warning: The output of `fortify(<fable>)` has changed to better suit usage with the ggdist package.
## If you're using it to extract intervals, consider using `hilo()` to compute intervals, and `unpack_hilo()` to obtain values.
## Plot variable not specified, automatically selected `.vars = .fitted`
## Warning in geom_line(eval_tidy(expr(aes(!!!aes_spec))), data = object, ..., :
## Ignoring unknown parameters: `level`

## # A tibble: 1 × 10
##   .model                  .type    ME  RMSE   MAE   MPE  MAPE  MASE RMSSE   ACF1
##   <chr>                   <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl>
## 1 TSLM(sales ~ trend() +… Test   28.9  33.0  28.9  42.5  42.5   NaN   NaN -0.197
 plot_TSLM_forecast(sales.data, "1602373", start_date, partition_date)
## Series: sales 
## Model: TSLM 
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -25.2579  -6.5151  -0.5722   4.6082  24.1008 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   35.3363130  3.5459199   9.965  < 2e-16 ***
## trend()       -0.2170833  0.1232854  -1.761 0.081420 .  
## I(trend()^2)   0.0004234  0.0011163   0.379 0.705314    
## season()week2 -1.0868426  3.4570413  -0.314 0.753904    
## season()week3  6.2199664  3.4566780   1.799 0.075064 .  
## season()week4 13.6592620  3.4564984   3.952 0.000147 ***
## season()week5  0.7643775  3.4564984   0.221 0.825447    
## season()week6  0.4686463  3.4566780   0.136 0.892437    
## season()week7 -5.1612651  3.4570413  -1.493 0.138690    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 9.609 on 97 degrees of freedom
## Multiple R-squared: 0.417,   Adjusted R-squared: 0.3689
## F-statistic: 8.673 on 8 and 97 DF, p-value: 7.3047e-09
## Warning: The output of `fortify(<fable>)` has changed to better suit usage with the ggdist package.
## If you're using it to extract intervals, consider using `hilo()` to compute intervals, and `unpack_hilo()` to obtain values.
## Plot variable not specified, automatically selected `.vars = .fitted`
## Warning in geom_line(eval_tidy(expr(aes(!!!aes_spec))), data = object, ..., :
## Ignoring unknown parameters: `level`

## # A tibble: 1 × 10
##   .model                  .type    ME  RMSE   MAE   MPE  MAPE  MASE RMSSE   ACF1
##   <chr>                   <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl>
## 1 TSLM(sales ~ trend() +… Test  0.723  3.23  2.31  2.09  11.0   NaN   NaN -0.391

抓前4週

 start_date <- "2023-03-23"
 partition_date <- "2023-04-13"
 
 plot_TSLM_forecast(sales.data, "1272962", start_date, partition_date)
## Series: sales 
## Model: TSLM 
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -7.6318 -4.0282  0.1093  3.8117  8.5211 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   23.95265    5.13018   4.669 0.000439 ***
## trend()       -0.28073    0.96925  -0.290 0.776661    
## I(trend()^2)   0.01951    0.04095   0.477 0.641602    
## season()week2 10.02263    5.16342   1.941 0.074244 .  
## season()week3  4.93261    5.17469   0.953 0.357868    
## season()week4 -0.19643    5.18226  -0.038 0.970340    
## season()week5 -0.03116    5.18226  -0.006 0.995293    
## season()week6 -4.57159    5.17469  -0.883 0.393037    
## season()week7 -6.48438    5.16342  -1.256 0.231280    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 6.611 on 13 degrees of freedom
## Multiple R-squared: 0.4859,  Adjusted R-squared: 0.1696
## F-statistic: 1.536 on 8 and 13 DF, p-value: 0.23605
## Warning: The output of `fortify(<fable>)` has changed to better suit usage with the ggdist package.
## If you're using it to extract intervals, consider using `hilo()` to compute intervals, and `unpack_hilo()` to obtain values.
## Plot variable not specified, automatically selected `.vars = .fitted`
## Warning in geom_line(eval_tidy(expr(aes(!!!aes_spec))), data = object, ..., :
## Ignoring unknown parameters: `level`

## # A tibble: 1 × 10
##   .model                  .type    ME  RMSE   MAE   MPE  MAPE  MASE RMSSE   ACF1
##   <chr>                   <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl>
## 1 TSLM(sales ~ trend() +… Test  -4.02  7.28  6.21 -20.1  25.9   NaN   NaN -0.158
 plot_TSLM_forecast(sales.data, "1394919", start_date, partition_date)
## Series: sales 
## Model: TSLM 
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -19.3842  -8.6081   0.5295   8.6205  17.9660 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)   
## (Intercept)   35.08106   10.81660   3.243  0.00641 **
## trend()       -3.25658    2.04360  -1.594  0.13505   
## I(trend()^2)   0.15566    0.08634   1.803  0.09462 . 
## season()week2 29.53516   10.88668   2.713  0.01775 * 
## season()week3 27.83426   10.91044   2.551  0.02414 * 
## season()week4 43.48871   10.92640   3.980  0.00157 **
## season()week5 11.16518   10.92640   1.022  0.32549   
## season()week6  6.86367   10.91044   0.629  0.54019   
## season()week7 14.25085   10.88668   1.309  0.21320   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 13.94 on 13 degrees of freedom
## Multiple R-squared: 0.6404,  Adjusted R-squared: 0.4192
## F-statistic: 2.894 on 8 and 13 DF, p-value: 0.043152
## Warning: The output of `fortify(<fable>)` has changed to better suit usage with the ggdist package.
## If you're using it to extract intervals, consider using `hilo()` to compute intervals, and `unpack_hilo()` to obtain values.
## Plot variable not specified, automatically selected `.vars = .fitted`
## Warning in geom_line(eval_tidy(expr(aes(!!!aes_spec))), data = object, ..., :
## Ignoring unknown parameters: `level`

## # A tibble: 1 × 10
##   .model                   .type    ME  RMSE   MAE   MPE  MAPE  MASE RMSSE  ACF1
##   <chr>                    <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 TSLM(sales ~ trend() + … Test  -10.4  24.9  22.1 -29.5  41.7   NaN   NaN 0.113
 plot_TSLM_forecast(sales.data, "1602373", start_date, partition_date)
## Series: sales 
## Model: TSLM 
## 
## Residuals:
##       Min        1Q    Median        3Q       Max 
## -17.58371  -3.07210  -0.02828   2.44006  14.89366 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)   
## (Intercept)   24.57905    7.25149   3.390  0.00484 **
## trend()       -0.87962    1.37004  -0.642  0.53201   
## I(trend()^2)   0.04153    0.05788   0.718  0.48572   
## season()week2 -2.05003    7.29847  -0.281  0.78322   
## season()week3 -6.62620    7.31440  -0.906  0.38147   
## season()week4  1.38123    7.32510   0.189  0.85335   
## season()week5 -1.69440    7.32510  -0.231  0.82067   
## season()week6 -0.85309    7.31440  -0.117  0.90893   
## season()week7 -4.09485    7.29847  -0.561  0.58430   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 9.345 on 13 degrees of freedom
## Multiple R-squared: 0.1492,  Adjusted R-squared: -0.3744
## F-statistic: 0.285 on 8 and 13 DF, p-value: 0.9592
## Warning: The output of `fortify(<fable>)` has changed to better suit usage with the ggdist package.
## If you're using it to extract intervals, consider using `hilo()` to compute intervals, and `unpack_hilo()` to obtain values.
## Plot variable not specified, automatically selected `.vars = .fitted`
## Warning in geom_line(eval_tidy(expr(aes(!!!aes_spec))), data = object, ..., :
## Ignoring unknown parameters: `level`

## # A tibble: 1 × 10
##   .model                   .type    ME  RMSE   MAE   MPE  MAPE  MASE RMSSE  ACF1
##   <chr>                    <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 TSLM(sales ~ trend() + … Test  -8.53  10.9  9.12 -57.9  59.8   NaN   NaN 0.272