1. Understand the Goal: The user wants a program for time series forecasting. This is a broad request. I need to decide on the scope, language, library, and specific model to make the example useful and runnable.
-
Determine the Language: Python is the de facto standard for data science and machine learning. It's the safest and most helpful choice.
-
Determine the Library:
- Statsmodels: Good for classical statistical methods (ARIMA, SARIMA, ETS). Good for understanding basics.
- Scikit-learn: Can be used with feature engineering (lag features), but not native time series handling.
- Prophet (by Meta): Very popular, easy to use, handles seasonality well.
- NeuralProphet / PyTorch Forecasting: Overkill for a simple example.
- Naive/Pandas: Good for baseline, but maybe too simple.
Decision: I will provide two examples.
- Example 1: A simple, classical statistical approach using ARIMA (via
statsmodels). It's standard.
- Example 2: A modern, robust approach using Prophet. It's user-friendly and often produces better results with less tuning.
-
Determine the Dataset: I shouldn't ask the user to download an external CSV to run the code immediately. I should generate synthetic data or use a built-in dataset.
- Synthetic Data: I can create a trend + seasonality + noise. This is best because it guarantees the code runs without dependencies on external files.
-
Drafting Example 1: ARIMA (Statsmodels)
- Imports:
pandas, numpy, matplotlib.pyplot, statsmodels.api.
- Data Generation: Create a date range, a linear trend, a sine wave for seasonality, and random noise.
- Preprocessing: Set the date as index.
- Model:
ARIMA or SARIMAX. Since I added seasonality, SARIMAX is better, but ARIMA is easier to explain. Let's stick to statsmodels.tsa.arima.model.ARIMA for simplicity, or maybe ExponentialSmoothing.
- Refinement: Let's use
statsmodels.tsa.seasonal.seasonal_decompose to show analysis, then ExponentialSmoothing (Holt-Winters) because it handles trend/seasonality intuitively without needing to explain (p,d,q) parameters in depth immediately. Actually, ARIMA is more requested. Let's provide a simple ARIMA example but note that parameters need tuning.
- Steps:
- Generate data.
- Split train/test.
- Fit model.
- Predict.
- Plot.
-
Drafting Example 2: Prophet (Facebook/Meta)
- Imports:
pandas, prophet (need to mention pip install prophet).
- Data Prep: Prophet requires specific column names:
ds (date) and y (value).
- Model:
Prophet().
- Fit/Predict:
fit(), make_future_dataframe(), predict().
- Plot:
model.plot(fcst).
-
Refining the "Program" Structure:
A single script is good, but structuring it as a tutorial or a modular script is better.
I will provide:
- Prerequisites: How to install libraries.
- Option 1 (Classical): Using
statsmodels (ARIMA).
- Option 2 (Modern): Using
Prophet (often easier/better results).
- Evaluation: How to check accuracy (MAE/RMSE).
-
Writing the Code (Mental Draft & Checks):
-
Synthetic Data:
import pandas as pd
import numpy as np
dates = pd.date_range(start='2023-01-01', periods=100, freq='D')
values = np.linspace(0, 10, 100) + np.random.normal(0, 1, 100)
-
ARIMA:
from statsmodels.tsa.arima.model import ARIMA
model = ARIMA(data, order=(5,1,0)) # Standard simple order
model_fit = model.fit()
forecast = model_fit.forecast(steps=10)
-
Prophet:
from prophet import Prophet
df = pd.DataFrame({'ds': dates, 'y': values})
m = Prophet()
m.fit(df)
future = m.make_future_dataframe(periods=30)
forecast = m.predict(future)
-
Adding Evaluation: I should include a metric like Mean Squared Error (MSE) or Mean Absolute Error (MAE) so the user knows how to interpret the result.
-
Final Polish:
- Add comments explaining why we do things (e.g., splitting data).
- Ensure code is copy-paste runnable (using synthetic data).
- Explain when to use which method.
-
Self-Correction during drafting:
- Issue:
statsmodels syntax changes frequently.
- Fix: Use the latest standard
statsmodels.tsa.arima.model.ARIMA (not the old statsmodels.tsa.arima_model).
- Issue: Prophet can be tricky to install on some Windows environments (requires compiler sometimes, though pip wheels are usually fine now).
- Fix: Stick to standard pip install instructions.
-
Final Output Structure:
- Introduction.
- Prerequisites (pip install).
- Approach 1: Statsmodels (Classical/Statistical) - Good for smaller datasets, explainability.
- Approach 2: Prophet (Modern/Machine Learning) - Good for business data with seasonality.
- Explanation of metrics.
This thought process moves from understanding the vague request to selecting the best tools for a demo, creating self-contained code, and ensuring the user understands how to run and evaluate it.
Time series forecasting is a broad field. The best approach depends on your data (e.g., does it have seasonality? Is it strictly linear?).
Below is a complete Python program that generates synthetic time series data and demonstrates two of the most common forecasting methods:
- ARIMA (Classical Statistical Method): Good for data with trends but no complex seasonality.
- Prophet (Modern Method by Meta): Excellent for data with strong trends and seasonality (e.g., daily sales).
Prerequisites
You will need Python installed. Run the following command to install the necessary libraries:
pip install pandas numpy matplotlib statsmodels prophet
The Python Program
Save this code in a file named forecast.py and run it.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.arima.model import ARIMA
from prophet import Prophet
# ==========================================
# 1. Generate Synthetic Data
# ==========================================
def generate_data(days=200):
"""Creates a synthetic time series with trend and seasonality."""
np.random.seed(42)
dates = pd.date_range(start='2023-01-01', periods=days, freq='D')
# Create a linear trend
trend = np.linspace(10, 50, days)
# Create some seasonality (sine wave)
seasonality = 10 * np.sin(np.linspace(0, 20, days))
# Add random noise
noise = np.random.normal(0, 2, days)
values = trend + seasonality + noise
df = pd.DataFrame({'Date': dates, 'Value': values})
return df
# ==========================================
# 2. Method: ARIMA (Statistical)
# ==========================================
def forecast_arima(df, forecast_periods=30):
"""
Uses ARIMA (AutoRegressive Integrated Moving Average).
Best for: Non-seasonal data or data where you manually handle differencing.
"""
print("Running ARIMA Model...")
# ARIMA requires the data to be in a Series with a DatetimeIndex
series = df.set_index('Date')['Value']
# Split into train/test (we keep the last 'forecast_periods' for validation)
train = series[:-forecast_periods]
test = series[-forecast_periods:]
# Fit the ARIMA model (p=5, d=1, q=0 are hyperparameters chosen simply for demo)
# p: Lag order (past values)
# d: Degree of differencing (make data stationary)
# q: Order of moving average (past forecast errors)
model = ARIMA(train, order=(5, 1, 0))
model_fit = model.fit()
# Forecast
forecast_result = model_fit.forecast(steps=forecast_periods)
# Plot
plt.figure(figsize=(10, 5))
plt.plot(train.index, train, label='Historical Data')
plt.plot(test.index, test, label='Actual Future', color='green')
plt.plot(test.index, forecast_result, label='ARIMA Forecast', color='red', linestyle='--')
plt.title('ARIMA Time Series Forecast')
plt.legend()
plt.show()
return model_fit
# ==========================================
# 3. Method: Prophet (Machine Learning)
# ==========================================
def forecast_prophet(df, forecast_periods=30):
"""
Uses Facebook Prophet.
Best for: Data with strong seasonal effects and missing data.
"""
print("Running Prophet Model...")
# Prophet requires columns to be named specifically: 'ds' and 'y'
df_prophet = df.rename(columns={'Date': 'ds', 'Value': 'y'})
# Split data
train = df_prophet[:-forecast_periods]
# Initialize and fit model
model = Prophet(yearly_seasonality=True, daily_seasonality=False)
model.fit(train)
# Create future dataframe (dates to predict)
future = model.make_future_dataframe(periods=forecast_periods)
# Predict
forecast = model.predict(future)
# Plot (Prophet has its own built-in plotting)
fig1 = model.plot(forecast)
plt.title('Prophet Time Series Forecast')
plt.show()
# Plot components (Trend vs Seasonality)
fig2 = model.plot_components(forecast)
plt.show()
return model
# ==========================================
# Main Execution
# ==========================================
if __name__ == "__main__":
# 1. Get Data
data = generate_data()
print(f"Generated {len(data)} days of data.")
print("Please close the plot window to see the next model.")
# 2. Run ARIMA
forecast_arima(data)
# 3. Run Prophet
forecast_prophet(data)
How this works
- Synthetic Data: Since we don't have your specific CSV file, the
generate_data function creates a dummy dataset. It combines a linear upward trend, a wave pattern (seasonality), and random noise.
- ARIMA:
- This is a classical statistical method.
- It looks at past values (lags) and past errors to predict the future.
- Note: In a real scenario, you would need to tune the
order=(p,d,q) parameters specifically to your data.
- Prophet:
- This is a library released by Meta (Facebook).
- It is generally easier to use because it automatically detects seasonality (e.g., "sales go up on weekends").
- It requires columns to be renamed to
ds (datestamp) and y (value).
Which one should you use?
- Use ARIMA if your data is small, strictly linear, and you understand statistics well enough to tune parameters.
- Use Prophet if you have daily/weekly business data (like website traffic or sales) with gaps, holidays, or strong seasonal patterns.