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
I'll help you create a comprehensive forecasting solution with backtesting. Here's a step-by-step approach using Python:
import pandas as pd import numpy.polynomial.polynomial as poly import numpy as np from sklearn.metrics import mean_absolute_percentage_error import matplotlib.pyplot as plt from datetime import timedelta # Assuming your dataframe is called 'df' # First, let's create the forecasting function using polynomial regression def create_polynomial_model(df, degree=2): # Convert dates to numeric values (days since start) x = np.arange(len(df)) y = df['od_gross'].values # Fit polynomial coefficients = poly.polyfit(x, y, degree) polynomial = poly.Polynomial(coefficients) return polynomial def calculate_smape(actual, predicted): return 100 * np.mean(2 * np.abs(actual - predicted) / (np.abs(actual) + np.abs(predicted))) def backtest_forecast(df, test_periods=[30, 90, 365], degree=2): results = {} # For each test period for period in test_periods: # Split data train = df[:-period].copy() test = df[-period:].copy() # Create and fit model model = create_polynomial_model(train, degree) # Generate predictions x_test = np.arange(len(train), len(df)) predictions = model(x_test) # Calculate SMAPE smape = calculate_smape(test['od_gross'].values, predictions) results[period] = { 'smape': smape, 'actual': test['od_gross'].values, 'predicted': predictions, 'dates': test['Date'].values } return results def plot_backtest_results(results, df): fig, axes = plt.subplots(len(results), 1, figsize=(15, 5*len(results))) for idx, (period, result) in enumerate(results.items()): ax = axes[idx] if len(results) > 1 else axes # Plot actual values ax.plot(result['dates'], result['actual'], label='Actual', color='blue') # Plot predictions ax.plot(result['dates'], result['predicted'], label='Predicted', color='red', linestyle='--') ax.set_title(f'{period} Days Forecast (SMAPE: {result["smape"]:.2f}%)') ax.legend() ax.grid(True) plt.xticks(rotation=45) plt.tight_layout() plt.show() # Main execution def run_forecast_analysis(df): # Sort by date df = df.sort_values('Date') # Run backtesting results = backtest_forecast(df) # Plot results plot_backtest_results(results, df) # Print SMAPE scores print("\nSMAPE Scores:") for period, result in results.items(): print(f"{period} days: {result['smape']:.2f}%") # Usage example: # run_forecast_analysis(df)To use this code:
- Make sure your DataFrame has 'Date' and 'od_gross' columns
- The Date column should be in datetime format
- Run the analysis:
run_forecast_analysis(df)This solution:
- Uses polynomial regression for forecasting
- Performs backtesting for 30, 90, and 365 days
- Calculates SMAPE (Symmetric Mean Absolute Percentage Error)
- Creates visualizations for each forecast period
- Shows actual vs predicted values
- Displays SMAPE scores for each period
You can adjust the polynomial degree by modifying the
degreeparameter inbacktest_forecast(). A higher degree might fit the data better but could lead to overfitting.Would you like me to explain any part in more detail or help you modify the code for your specific needs?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.