Zero Labs
Industry News / AI

Product Forecasting through Time Series Analysis (Modelling)

Source · Towards AI By Nikumbhdeepti

From the publisher’s feed, collected in the ZeroLabs newsroom.

This article is Part 3 of the blog series “Product Sales Forecasting through Time Series Analysis”. Here, we focus on designing and evaluating forecasting models using machine learning, deep learning, and statistical time-series techniques.The objective of this part of blog is to build robust forecasting models that can accurately capture underlying patterns in sales data and generate reliable future predictions.The model development process follows a structured approach, consisting of:Data preprocessing and feature preparationModel selection based on data characteristicsModel training and validationPerformance evaluation using appropriate metricsFinal model selection and deployment readinessThe dataset used for this study is available at LINKGiven the complex and hierarchical nature of the data, the modeling approach begins with region-level segregation. This allows each region’s unique sales behavior, seasonality, and demand patterns to be captured more effectively.For region-wise forecasting, multiple models were designed and evaluated. This includesLinear RegressionXGBoostSARIMAXFacebook’s ProphetEach model is trained independently on region-level sales data and evaluated using standard forecasting performance metrics such as Mean Absolute Percentage Error (MAPE), Mean Squared Error (MSE), Mean Absolute Error (MAE), and R² score.Based on the evaluation results, the best-performing model for each region is identified. Using these selected models, the forecasting framework was further extended to the store level, enabling more granular predictions.To demonstrate practical business value, the top five best-performing stores were identified within each region, and their future sales trends were visualized using the chosen forecasting models.Let's delve deep in each phase of model developmentData preprocessing and feature preparationThis step begins by understanding the data. This includes the count of features, the total samples in the dataset, and identifying the continuous and categorical columns.Dataset feature detailsprint("The total samples in the data",len(train_df))print(" the dimension of dataset",train_df.shape)The total samples in the dataset are 188340 and the dimension of the dataset is (188340, 10)#continuous variables with cardinaityprint("The categorical columns and their caridnality")print("Store_Type",train_df['Store_Type'].nunique())print("Store_id",train_df['Store_id'].nunique())print("Holiday",train_df['Holiday'].nunique())print("Location_Type",train_df['Location_Type'].nunique())print("Region_code",train_df['Region_Code'].nunique())print("Discount",train_df['Discount'].nunique())The categorical columns and their cardinalityStore_Type: 4Store_id: 365Holiday: 2Location_Type: 5Region_code: 4Discount: 2Understanding the cardinality of categorical variables is a critical step in feature engineering, as it directly influences the choice of encoding technique. For features with low cardinality and no intrinsic ordering, techniques such as one-hot encoding and label encoding are appropriate. In contrast, high-cardinality features are better handled using embedding-based approaches, which efficiently capture complex relationships while controlling dimensionality.#using one hot encoding for Store_Type,Location_Type and Region_codestore_type_dummies=pd.get_dummies(train_df['Store_Type'],prefix='Store_Type',dummy_na=False,dtype=int)store_type_features=pd.concat([train_df[['ID']],store_type_dummies],axis=1)store_type_dummies=pd.get_dummies(test_df['Store_Type'],prefix='Store_Type',dummy_na=False,dtype=int)store_type_features=pd.concat([test_df[['ID']],store_type_dummies],axis=1)location_type_dummies=pd.get_dummies(train_df['Location_Type'],prefix='Location_Type',dummy_na=False,dtype=int)location_type_dummies=pd.concat([train_df[['ID']],location_type_dummies],axis=1)location_type_dummies=pd.get_dummies(test_df['Location_Type'],prefix='Location_Type',dummy_na=False,dtype=int)location_type_dummies=pd.concat([test_df[['ID']],location_type_dummies],axis=1)region_code_dummies=pd.get_dummies(train_df['Region_Code'],prefix='Region_Code',dummy_na=False,dtype=int)region_code_dummies=pd.concat([train_df[['ID']],region_code_dummies],axis=1)region_code_dummies=pd.get_dummies(test_df['Region_Code'],prefix='Region_Code',dummy_na=False,dtype=int)region_code_dummies=pd.concat([test_df[['ID']],region_code_dummies],axis=1)Given that the problem statement focuses on time-series forecasting, the date column plays a pivotal role. In many real-world datasets, date fields are often stored as strings; therefore, converting the date column into a proper datetime format is essential for extracting temporal features and enabling time-series modeling.train_df_fe['Date']=pd.to_datetime(train_df_fe['Date'])test_df_fe['Date']=pd.to_datetime(test_df_fe['Date'])As part of data cleaning, the dataset was examined for null values and duplicate records. There are no null values and duplicate values present in the dataset.nul_values_info=train_df.isna().sum()train_df=train_df.drop_duplicates()print("the size of dataset after removing duplicates",len(train_df))As part of the data preprocessing phase, numerical features such as sales and order quantities were scaled to ensure that all input variables lie within a comparable range. Feature scaling is particularly important for many machine learning models, as it prevents features with larger magnitudes from dominating the learning process.In this work, Min–Max normalization was applied to rescale numerical variables to a fixed range, typically between 0 and 1. This transformation improves model stability and training efficiency.Special care was taken to avoid data leakage during scaling. The scaler was fitted only on the training data using fit_transform and subsequently applied to the test data using transform. This ensures that no information from the test set influences the training process, preserving the integrity of model evaluation.scaler=MinMaxScaler()x_train_scaled=scaler.fit_transform(X_train)x_val_scaled=scaler.transform(X_val)scaler_y=MinMaxScaler()y_train_scaled=scaler_y.fit_transform(y_train.values.reshape(-1,1))y_val_scaled=scaler_y.fit_transform(y_val.values.reshape(-1,1))The dataset is then segregated at the region level, after which the average daily sales and average daily order quantities are computed for each region. This aggregation results in a region-wise time series, where each region is represented by continuous temporal data capturing its average sales and order behavior over time.region_eda_avg = {}for region, data in region_eda.items(): avg_df = ( data .groupby('Date', as_index=False) .agg( avg_sales=('Sales', 'mean'), avg_orders=('#Order', 'mean') ) ) region_eda_avg[region] = avg_dfAverage sales and orders for region R1As a result, for each region, we obtain daily time-series data of average sales and average order quantities spanning from January 1, 2018, to May 31, 2019, resulting in 516 observations per region. This structured time-series dataset serves as the foundation for the subsequent modeling phase, enabling the application of statistical, machine learning, and deep learning forecasting techniques.Model selection based on data characteristicsSince the objective of this study is to design forecasting models that predict continuous sales values over time, it is essential to select algorithms capable of capturing both numerical relationships and temporal dependencies within the data.Thus, models chosen include linear regression and XGBoost for capturing trend and feature-based relationships, long short-term memory (LSTM) networks for modeling long-term temporal dependencies, and statistical time-series models such as SARIMAX and Facebook Prophet for handling seasonality, trends, and calendar effects.This models enables a comprehensive comparison across machine learning, deep learning, and classical time-series approaches, ensuring robust and reliable forecasting performance.Model training and validationMachine learning models such as linear regression and XGBoost depend on independent input features to generate predictions. However, in a time-series forecasting context, these independent features are historical data and must be explicitly introduced, as these models do not inherently capture temporal relationships.To address this, lag features were created. Lag features represent past values of the target variable and are included as predictors in the model. They are generated by shifting the time series backward by a specified number of time periods, allowing the model to learn from historical patterns. In this study, a 7-day lag window was used. This means that sales from the previous seven days are used as input features to predict the sales value for the next day. The choice of a 7-day lag aligns with the weekly seasonality identified during the exploratory data analysis and enables the models to capture short-term temporal dependencies effectively.In the code , for every region, average sales are captured, and then lag features are calculated , a train-test split is done, values are normalized using a min-max scaler, and a linear regression model is trained and validated using MAPE, MSE, MAE, and R-square.model_list = []lag = 7lr_mape={}lr_rsquare={}lr_mae={}lr_mse={}for region, data in region_eda_avg.items(): sales = data['avg_sales'].values # 1D numpy array X, y = [], [] for i in range(lag, len(sales)): X.append(sales[i - lag:i]) y.append(sales[i]) X = np.array(X) y = np.array(y) # Train / validation split X_train, X_val, y_train, y_val = train_test_split( X, y, test_size=0.2, shuffle=False ) # minmax scaler scaler=MinMaxScaler() x_train_scaled=scaler.fit_transform(X_train) x_val_scaled=scaler.transform(X_val) scaler_y=MinMaxScaler() y_train_scaled=scaler_y.fit_transform(y_train.reshape(-1,1)) y_val_scaled=scaler_y.transform(y_val.reshape(-1,1)) model = LinearRegression() model.fit(x_train_scaled, y_train_scaled) y_pred=model.predict(x_val_scaled) y_pred=scaler_y.inverse_transform(y_pred.reshape(-1,1)) mape=mean_absolute_percentage_error(y_val,y_pred.flatten()) mae=mean_absolute_error(y_val,y_pred.flatten()) mse=mean_squared_error(y_val,y_pred.flatten()) r_square=r2_score(y_val,y_pred.flatten()) lr_mape[region]=mape lr_rsquare[region]=r_square lr_mae[region]=mae lr_mse[region]=mse model_list.append(model) filename = f'linear_regression_model_{region}.pkl' with open(filename, 'wb') as file: pickle.dump(model, file) print(f"Saved model for region {region} | MSE: {mse:.2f} | MAE: {mae:.2f} | MAPE: {mape:.2f} | R square:{r_square:.2f}")For the XGBoost model, a GridSearchCV approach is used to identify the optimal set of hyperparameters, including learning rate, maximum tree depth, and subsampling ratio. Once the best-performing parameter combination was identified, the final XGBoost model is trained using these optimized settings.lag = 7param_grid = { 'learning_rate': [0.01, 0.05, 0.1], 'max_depth': [3, 5, 7], 'subsample': [0.8, 0.9, 1.0]}model_list = []xgboost_mape={}xgboost_rsquare={}xgboost_mae={}xgboost_mse={}for region, data in region_eda_avg.items(): sales = data['avg_sales'].values # 1D numpy array X, y = [], [] for i in range(lag, len(sales)): X.append(sales[i - lag:i]) y.append(sales[i]) X = np.array(X) y = np.array(y) # Train / validation split X_train, X_val, y_train, y_val = train_test_split( X, y, test_size=0.2, shuffle=False ) # minimax scaler scaler=MinMaxScaler() x_train_scaled=scaler.fit_transform(X_train) x_val_scaled=scaler.transform(X_val) scaler_y=MinMaxScaler() y_train_scaled=scaler_y.fit_transform(y_train.reshape(-1,1)) y_val_scaled=scaler_y.transform(y_val.reshape(-1,1)) grid_search = GridSearchCV(XGBRegressor(), param_grid,cv=5) grid_search.fit(x_train_scaled, y_train_scaled) best_params= grid_search.best_params_ print(f"The best parameter for {region} | are: {best_params} ") xgb_model = XGBRegressor(**best_params) xgb_model.fit(x_train_scaled, y_train_scaled) y_pred=xgb_model.predict(x_val_scaled) y_pred=scaler_y.inverse_transform(y_pred.reshape(-1,1)) mape=mean_absolute_percentage_error(y_val,y_pred.flatten()) mae=mean_absolute_error(y_val,y_pred.flatten()) mse=mean_squared_error(y_val,y_pred.flatten()) r_square=r2_score(y_val,y_pred.flatten()) xgboost_mape[region]=mape xgboost_rsquare[region]=r_square xgboost_mae[region]=mae xgboost_mse[region]=mse model_list.append(xgb_model) filename = f'linear_regression_model_{region}.pkl' with open(filename, 'wb') as file: pickle.dump(model, file) print(f"Saved model for Store {region} | MSE: {mse:.2f} | MAE: {mae:.2f} | MAPE: {mape:.2f} | R square:{r_square:.2f}")In the case of Long Short-Term Memory (LSTM) networks, the model requires sequential and temporally ordered data as input. To accommodate this, lag features with a window size of 7 time steps were constructed, consistent with the weekly seasonality observed during EDA.An LSTM architecture consisting of 7 LSTM units followed by a Dense output layer was implemented. Since LSTM models expect input data in a 3-dimensional format ,a proper reshaping of the input data was a critical preprocessing step to ensure correct model training.lstm_model_list = []lag = 7lstm_mape={}lstm_rsquare={}lstm_mse={}lstm_mae={}for region, data in region_eda_avg.items(): sales = data['avg_sales'].values # 1D numpy array X, y = [], [] for i in range(lag, len(sales)): X.append(sales[i - lag:i]) y.append(sales[i]) X = np.array(X) y = np.array(y) # Train / validation split X_train, X_val, y_train, y_val = train_test_split( X, y, test_size=0.2, shuffle=False ) # minimax scaler scaler=MinMaxScaler() x_train_scaled=scaler.fit_transform(X_train) x_val_scaled=scaler.transform(X_val) scaler_y=MinMaxScaler() y_train_scaled=scaler_y.fit_transform(y_train.reshape(-1,1)) y_val_scaled=scaler_y.transform(y_val.reshape(-1,1)) # converting the input in 3D shape as required by LSTM x_train=np.reshape(x_train_scaled,(x_train_scaled.shape[0],x_train_scaled.shape[1],1)) x_val=np.reshape(x_val_scaled,(x_val_scaled.shape[0],x_val_scaled.shape[1],1)) model=Sequential() model.add(LSTM(7,return_sequences=False,input_shape=(7,1))) model.add(Dense(1)) model.compile(optimizer='adam',loss='mean_squared_error') model.fit(x_train,y_train_scaled,batch_size=64,epochs=20,verbose=1,validation_data=(x_val,y_val_scaled)) y_pred=model.predict(X_val) y_pred=scaler_y.inverse_transform(y_pred) mape=mean_absolute_percentage_error(y_val,y_pred.flatten()) r_square=r2_score(y_val,y_pred.flatten()) mse=mean_squared_error(y_val,y_pred.flatten()) mae=mean_absolute_error(y_val,y_pred.flatten()) lstm_mape[region]=mape lstm_rsquare[region]=r_square lstm_mse[region]=mse lstm_mae[region]=mae lstm_model_list.append(model) filename = f'LSTM_model_{region}.pkl' with open(filename, 'wb') as file: pickle.dump(model, file) print(f"Saved model for Store {region} | MSE: {mse:.2f} | MAE: {mae:.2f} | MAPE: {mape:.2f} | R square:{r_square:.2f}")In addition to machine learning and deep learning approaches, statistical time-series models such as SARIMAX and Facebook Prophet were implemented to explicitly model trend and seasonality.SARIMAX was selected because of its ability to capture seasonal patterns while also incorporating exogenous variables such as discounts and holidays, which were shown during EDA to influence sales. Prophet, on the other hand, was chosen for its support of multiple seasonalities (for example, weekly and monthly) and its robustness to missing values and trend changes.Prior to implementing SARIMAX, the region-wise sales time series was evaluated for stationarity using the Augmented Dickey–Fuller (ADF) test. This checks whether a time series has a constant mean and variance over time. The test results indicated that the region-wise sales series passed the Dickey–Fuller test, confirming that the data is stationary and suitable for SARIMAX modeling without additional differencing.# Applying the dickey fuller test to check if series are stationaryresult=[]for region, data in region_eda_avg.items(): test_data=data['avg_sales'] ad_test=adfuller(test_data) result.append({'region':region, 'p-value':ad_test[1], 'stationary':ad_test[1] }) ad_result=pd.DataFrame(result)Result of ADFuller testTo determine appropriate parameters for the SARIMAX models, Autocorrelation Function (ACF) and Partial Autocorrelation Function (PACF) plots were generated for the region-wise sales time series.The ACF plot captures both direct and indirect correlations between observations at different lags and is primarily used to identify the Moving Average (MA) component of the model. A gradual decay or distinct spikes in the ACF help determine the appropriate value of q. In contrast, the PACF plot measures only the direct correlation between observations and is used to identify the autoregressive (AR) component, where a sharp cutoff after a specific lag indicates the value of p.Across all regions, the PACF plots show a significant spike at lag 1, with subsequent lags falling within the confidence interval. This clear cutoff after the first lag suggests an autoregressive order of p = 1. Similarly, the ACF plots exhibit a significant spike at lag 1 followed by a gradual decay, without a sharp cutoff, indicating a moving average order of q = 1.ACF and PACF plots for all the regionsThe SARIMAX model is then designed and forecast for the next 60 days is plotted.sarimax_result={}p=1q=1#sesonality peroidP,D,Q,S=1,0,1,7for region, data in region_eda_avg.items(): data=data['avg_sales'] model=SARIMAX(data,order=(p,0,q),seasonal_order=(P,D,Q,S)) result=model.fit() sarimax_result[region]=result print(f"The AIC value for the {region} stationary series is : {result.aic}")forecast_future={}step=61for store,result in sarimax_result.items(): forecast=result.get_forecast(steps=step) forecast_frame=forecast.summary_frame() forecast_future[store]=forecast_frameForecast for region R1Region-wise 61-day forecast using SARIMAXAs observed during the EDA phase, sales show a clear positive uplift on discounted days. To capture this behavior, discount is incorporated as an exogenous variable in the SARIMAX model. By including this external regressor, the model is able to account for the impact of promotional activities on sales patterns.#exog for the train and test setexog_train={region: data[['Date','Holiday','Discount']].groupby('Date')[['Holiday','Discount']].max().astype(float) for region, data in train_df.groupby("Region_Code")}exog_test={region: data[['Date','Holiday','Discount']].groupby('Date')[['Holiday','Discount']].max().astype(float) for region, data in test_df.groupby("Region_Code")}#SARIMAX with exogenexo_sarimax_result={}p=1q=3#sesonality peroidP,D,Q,S=1,0,1,7for region, data in region_eda_avg.items(): data=data.set_index('Date') exog=exog1[region] data.index = pd.to_datetime(data.index) exog.index = pd.to_datetime(exog.index) model=SARIMAX(data['avg_sales'],exog=exog,order=(p,0,q),seasonal_order=(P,D,Q,S),enforce_stationarity=False, enforce_invertibility=False) result=model.fit() exo_sarimax_result[region]=result print(f"The AIC value for the {region} stationary series is : {result.aic}")The model is then used to forecast sales for the next 61 days, and the resulting forecasts are visualized. A noticeable difference can be observed when compared to forecasts without exogenous variables, clearly demonstrating how incorporating discount information improves the model’s ability to reflect real-world sales dynamics.Region-wise sales forecast using SARIMAX with exogenNext, Facebook Prophet is implemented as a forecasting model. Prophet offers several practical advantages, including ease of use, strong automation, and robustness to real-world, noisy datasets. It is particularly well suited for business time-series problems, as it automatically captures multiple seasonality patterns (daily, weekly, and yearly), incorporates holiday effects, and requires minimal manual hyperparameter tuning.exo_prophet_mape_scores = {}exo_prophet_r_square = {}exo_prophet_mae = {}exo_prophet_mse = {}test_size = 104for region, series in region_eda_avg.items(): try: # Prepare data for Prophet df = ( series .copy() .rename(columns={'Date': 'ds', 'avg_sales': 'y'}) ) train = df[:-test_size] test = df[-test_size:] # Get fitted Prophet model model = models[region] # Forecast exactly test horizon future = model.make_future_dataframe( periods=test_size, freq='D', include_history=False ) forecast = model.predict(future) # Extract numeric arrays y_true = test['y'].values y_pred = forecast['yhat'].values # Sanity check assert len(y_true) == len(y_pred) # Metrics mape = mean_absolute_percentage_error(y_true, y_pred) r2 = r2_score(y_true, y_pred) mse = mean_squared_error(y_true, y_pred) mae = mean_absolute_error(y_true, y_pred) exo_prophet_mape_scores[region] = mape exo_prophet_r_square[region] = r2 exo_prophet_mse[region] = mse exo_prophet_mae[region] = mae print( f"{region} | " f"MAPE: {mape:.3f} | " f"R²: {r2:.3f} | " f"MSE: {mse:.3f} | " f"MAE: {mae:.3f}" ) except Exception as e: print(f"{region} failed: {e}")A sample visualization of Prophet’s forecast for Region R1 is shown below. From the plot, it can be observed that the predicted sales values closely follow the actual sales trend, indicating that Prophet is able to effectively capture the underlying patterns and seasonality present in the data.Prophet sales and forecasting for region R1Performance evaluation using appropriate metricsAll the models are evaluated on the MAPE,MAE,MSE and R square metrics.Primary metrics used for deciding the best models are MAPE and MAE.Region R1 performance evaluationRegion R2 performance evaluationRegion R3 performance evaluationRegion R4 performance evaluationLinear regression and XGBoost models indicates high forecast accuracy, meaning predictions deviate from actual sales by only 10–12% on average.MAE and MSE are the lowest among all models, suggesting consistently small prediction errors.R² values rages between 0.50–0.55 indicating that more than 50% of the variance in sales is explained by these models.In all the regions , this patterns appear to be relatively stable and linear, making ML models with lag variables well-suited. XGBoost does not significantly outperform Linear Regression, suggesting limited non-linear complexity in the data.LSTM’s demonstrate poor performance with a very high MAPE and MSE and MAE and negative Rsquare. LSTM models require large datasets and strong sequential dependencies to perform well. In this case the time series length of 516 days is relatively small.As a result, the LSTM model overfits and fails to generalize.Prophet and SARIMAX give moderate performance with Prophet performing better than SARIMAX and LSTM’s. Apart from Linear Regression and XGBoost, Prophet can be next best option for forecasting as it effectively models trend and seasonality.Moving forward with the analysis, once the best-performing models at the regional level are identified, the forecasting is further drilled down to the store level. This enables a more granular understanding of sales behavior and supports store-specific decision-making.A new train–test split is created at the store level, ensuring that information such as store ID, holiday indicators, and discount flags is retained. In addition to lag-based features, a rolling mean is computed to capture short-term sales trends and smooth out daily fluctuations.For each store, the following features are used as inputs to the Linear Regression and XGBoost models:● 7-day lag features to incorporate recent historical patterns● Rolling mean of sales to capture local trends● Holiday indicator to account for calendar effects● Discount indicator to model promotional impactThis feature-rich setup allows the models to learn both temporal dependencies and external business drivers, resulting in more accurate and actionable store-level sales forecasts.Region R1 datasetOnce the data is ready , best identified models i.e Linear Regression and XGBoost are trained and validated.Here a news performance measure SMAPE which is a variation of MAPE is used. The model achieves an SMAPE of less than 20% also MAPE and MAE are low indicating a good forecasting model.Performance of linear regression on store-level dataThe results of XGBoost are also comparatively better than Linear Regression, as its resulted in low SMAPE,MAPE and MAE.Performance of XGBoost on store-level dataStore-level forecasting is performed separately for each region using the test dataset. To generate predictions in a realistic time-series manner, a recursive forecasting approach is adopted.For each store, the last 7 days of data from the training set are first extracted. These historical values are used to compute the lag features and rolling mean required for predicting the first time step in the test period. The resulting feature set comprising store ID, holiday flag, discount flag, 7 lag values, and rolling mean are then fed into the Linear Regression and XGBoost models to generate the sales prediction for the first test date.lag_steps = 7for store_id in region_test["Store_id"].unique(): # get last 7 sales for this store from TRAIN sales = ( test_lag_r1[test_lag_r1["Store_id"] == store_id] .sort_values("Date")["Sales"] .tail(lag_steps) .values ) # skip stores with insufficient history if len(sales) continue # assign lags with lag1 recent for i in range(1, lag_steps + 1): region_test.loc[ region_test["Store_id"] == store_id, f"lag_{i}" ] = sales[-i]For subsequent test dates, the newly predicted sales value is shifted and treated as a lagged input, and a new rolling mean is recalculated. This updated feature set is used to predict the next time step. The process continues iteratively until forecasts are generated for the entire test horizon.future_prediction = {}lag_cols = [f'lag_{i}' for i in range(1, 8)]for store_id in region_test['Store_id'].unique(): future_prediction[store_id] = [] # last known row for this store last_row = region_test.loc[ region_test['Store_id'] == store_id ].iloc[-1] # initialize lags lag_values = last_row[lag_cols].values.astype(float) # future exogenous data exog_data = test_data_r1.loc[ test_data_r1['Store_id'] == store_id, ['Holiday', 'Discount'] ].iloc[:61].reset_index(drop=True) for i in range(61): rolling_mean = lag_values.mean() X = pd.DataFrame([{ 'Store_id': store_id, 'Holiday': exog_data.loc[i, 'Holiday'], 'Discount': exog_data.loc[i, 'Discount'], **dict(zip(lag_cols, lag_values)), 'rolling_mean': rolling_mean }]) # predict next_pred = model.predict(scaler.transform(X))[0] future_prediction[store_id].append(scaler_y.inverse_transform(next_pred.reshape(-1, 1))) # update lags lag_values = np.roll(lag_values, 1) lag_values[0] = next_predTo effectively present store-level performance across regions, the top-performing stores are identified for each region based on forecast accuracy and sales trends.Top five best performing stores in region R1 are shown as a sample.Similarly best performing stores are identified for all the other regions.Best top 5 stores for region R1Key Take aways:● Sales behavior varies significantly across regions and stores● Feature-based machine learning models (Linear Regression and XGBoost)● Discounts have a clear positive impact on sales● Seasonality is present but not uniformly dominant across regions.● LSTM models struggled due to limited data size and weaker long-term temporal dependencies● Lag features and rolling statistics are critical for time-series forecasting with ML models● Recursive forecasting enables realistic store-level predictions● Store-level forecasting uncovers actionable insights, allowing identification of top-performing and low-performing stores within each region, supporting targeted operational and strategic decisions.The complete implementation, including data preprocessing, exploratory data analysis, model development, evaluation, and forecasting , is available on GitHub. You can find the full codebase at the link below:GitHub Repository: https://github.com/deeptinikumbh/Product-Sales-Forecasting-Product Forecasting through Time Series Analysis (Modelling) was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.