I want to make a forecast, I have a daily data of sales, the graph is gradually…
- User
I want to make a forecast, I have a daily data of sales, the graph is gradually (perfectly looks like a polynonial or tangent line). How to make a forecast method that can be backtested on previos 365 days, caluclating the smape, on first 30 days, 90 days, and 365 days of backtest, and visualise the backtest results. The df has 'Date' and 'od_gross' columns
- Assistant
To perform a forecasting analysis on your daily sales data (
dfwith columnsDateandod_gross) and backtest it on previous 365 days with SMAPE (Symmetric Mean Absolute Percentage Error) calculated on 30-day, 90-day, and 365-day intervals, you can use a polynomial regression or a tangent-like trend model.Here's a step-by-step guide using polynomial regression (since you mentioned the data looks like a polynomial or tangent line), with backtesting, SMAPE calculation, and visualization of the results.
✅ Step-by-Step Forecasting with Backtesting in Python
1. Import Required Libraries
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_percentage_error
2. Prepare the Data
# Make sure 'Date' is a datetime and set it as index df['Date'] = pd.to_datetime(df['Date']) df = df.set_index('Date').sort_index() # Fill missing dates and forward fill values if needed df = df.asfreq('D') # Create a numeric time index for regression df['t'] = np.arange(len(df))
3. Define Forecasting and Backtesting Function
def smape(y_true, y_pred): return 100 * np.mean(2 * np.abs(y_pred - y_true) / (np.abs(y_true) + np.abs(y_pred))) def backtest_forecast(df, target_col='od_gross', degree=3, backtest_days=[30, 90, 365]): results = {} t = df['t'].values y = df[target_col].values plt.figure(figsize=(14, 8)) plt.plot(df.index, y, label='Actual', color='black') for days in backtest_days: train_idx = -days t_train, y_train = t[:train_idx], y[:train_idx] t_test, y_test = t[train_idx:], y[train_idx:] # Polynomial Regression poly = PolynomialFeatures(degree=degree) X_train_poly = poly.fit_transform(t_train.reshape(-1, 1)) model = LinearRegression() model.fit(X_train_poly, y_train) # Forecast X_test_poly = poly.transform(t_test.reshape(-1, 1)) y_pred = model.predict(X_test_poly) # SMAPE smape_score = smape(y_test, y_pred) results[days] = smape_score # Plot plt.plot(df.index[train_idx:], y_pred, label=f'Poly {degree} Backtest {days} days (SMAPE={smape_score:.2f}%)') plt.title("Backtest Results with Polynomial Forecast") plt.xlabel("Date") plt.ylabel("Sales") plt.legend() plt.grid(True) plt.tight_layout() plt.show() return results
4. Run the Backtest and Get Results
results = backtest_forecast(df, degree=3) print("Backtest SMAPE Results:") for days, error in results.items(): print(f"{days} days backtest SMAPE: {error:.2f}%")
5. Optional: Forecast Future Values
def forecast_future(df, degree=3, steps=30): t = df['t'].values y = df['od_gross'].values poly = PolynomialFeatures(degree=degree) X_poly = poly.fit_transform(t.reshape(-1, 1)) model = LinearRegression() model.fit(X_poly, y) future_t = np.arange(t[-1] + 1, t[-1] + steps + 1) future_poly = poly.transform(future_t.reshape(-1, 1)) forecast = model.predict(future_poly) # Create future dates last_date = df.index[-1] future_dates = pd.date_range(last_date, periods=steps + 1, freq='D')[1:] forecast_df = pd.DataFrame({ 'Date': future_dates, 'Forecast': forecast }).set_index('Date') return forecast_df
6. Plot Future Forecast
forecast_df = forecast_future(df, degree=3, steps=30) plt.figure(figsize=(12, 6)) plt.plot(df.index, df['od_gross'], label='Historical') plt.plot(forecast_df.index, forecast_df['Forecast'], label='Forecast', linestyle='--') plt.title('30-Day Sales Forecast') plt.xlabel('Date') plt.ylabel('Sales') plt.legend() plt.grid(True) plt.show()
📌 Notes:
- Polynomial Degree: You can try different degrees (e.g., 2 or 4) to see which fits better.
- Alternative Models: If the trend looks more like a tangent curve, you could try fitting a custom nonlinear model using
scipy.optimize.curve_fit. - Robustness: Polynomial regression can overfit long-term trends. Consider using SARIMA, Prophet, or Exponential Smoothing for more robust time series forecasting if needed.
Would you like to try a nonlinear model (e.g., exponential or tangent-like) instead?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.