AI7 min read

Time Series Forecasting

Predict future values from time-based data.

Robert Anderson
December 18, 2025
0.0k0

Predict the future with data.

What is Time Series?

Data collected over time: stock prices, temperature, sales.

Goal: Predict future values

Key Concepts

Trend: Long-term direction (up/down)
Seasonality: Repeating patterns (summer/winter)
Noise: Random fluctuations

Simple Moving Average

import pandas as pd

# Calculate 7-day moving average
df['MA_7'] = df['sales'].rolling(window=7).mean()

# Predict: next value = average of last 7

ARIMA Model

Classic time series model:

from statsmodels.tsa.arima.model import ARIMA

# Fit ARIMA
model = ARIMA(data, order=(1, 1, 1))
model_fit = model.fit()

# Forecast next 10 days
forecast = model_fit.forecast(steps=10)
print(forecast)

LSTM for Time Series

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
import numpy as np

# Prepare data: use last 30 days to predict next day
def create_sequences(data, seq_length=30):
    X, y = [], []
    for i in range(len(data) - seq_length):
        X.append(data[i:i+seq_length])
        y.append(data[i+seq_length])
    return np.array(X), np.array(y)

X, y = create_sequences(prices)

# Build model
model = Sequential([
    LSTM(50, return_sequences=True, input_shape=(30, 1)),
    LSTM(50),
    Dense(1)
])

model.compile(optimizer='adam', loss='mse')
model.fit(X, y, epochs=50, batch_size=32)

# Predict
next_day = model.predict(last_30_days)

Prophet (by Facebook)

Easy and powerful:

from fbprophet import Prophet

# Data needs 'ds' (date) and 'y' (value)
df = pd.DataFrame({
    'ds': dates,
    'y': values
})

model = Prophet()
model.fit(df)

# Forecast 365 days
future = model.make_future_dataframe(periods=365)
forecast = model.predict(future)

# Plot
model.plot(forecast)

Evaluation Metrics

from sklearn.metrics import mean_absolute_error, mean_squared_error

mae = mean_absolute_error(y_true, y_pred)
rmse = np.sqrt(mean_squared_error(y_true, y_pred))

print(f"MAE: {mae}")
print(f"RMSE: {rmse}")

Real Applications

  • Stock price prediction
  • Sales forecasting
  • Weather prediction
  • Traffic forecasting
  • Energy consumption

Best Practices

  1. Check for stationarity
  2. Handle seasonality
  3. Use walk-forward validation
  4. Don't predict too far ahead

Remember

  • Time order matters!
  • Don't shuffle data
  • Use Prophet for easy start
  • LSTM for complex patterns
#AI#Intermediate#Time Series