← Back to Python

All Topics

Advertisement

Learn/Python/Machine Learning

Time Series Forecasting

Topic: Forecasting

Advertisement

Introduction

Time series forecasting predicts future values based on historical patterns.

Simple Methods

import pandas as pd
from sklearn.metrics import mean_absolute_error

# Moving average
df["ma_7"] = df["value"].rolling(window=7).mean()
df["ma_30"] = df["value"].rolling(window=30).mean()

# Exponential smoothing
df["ema"] = df["value"].ewm(span=7).mean()

# Naive forecast
df["naive"] = df["value"].shift(1)

Prophet

from prophet import Prophet

df = pd.DataFrame({
    "ds": pd.date_range("2023-01-01", periods=365),
    "y": sales_data
})

model = Prophet(yearly_seasonality=True, weekly_seasonality=True)
model.fit(df)

future = model.make_future_dataframe(periods=30)
forecast = model.predict(future)

ARIMA

from statsmodels.tsa.arima.model import ARIMA

model = ARIMA(df["value"], order=(5, 1, 0))
fitted = model.fit()

forecast = fitted.forecast(steps=30)

Practice Problems

  1. Create time series plots
  2. Detect trends and seasonality
  3. Use moving averages
  4. Fit ARIMA model
  5. Compare forecasting methods

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →