Saturday, June 27, 2026
HomeUncategorizedTime Series Analysis in Python: Complete Guide with Examples (2026)

Time Series Analysis in Python: Complete Guide with Examples (2026)

Table of Content

Time series analysis is essential for any data scientist working with sequential data — stock prices, sales forecasts, weather patterns, web traffic, and more. This complete guide covers everything from basics to production forecasting in Python.

What is Time Series Data?

Time series data is a sequence of data points collected at successive points in time. It has four key components: Trend (long-term direction), Seasonality (periodic patterns), Cyclical (irregular fluctuations), and Residual (random noise).

Loading and Visualizing Time Series

import pandas as pd
import matplotlib.pyplot as plt

# Load time series data
df = pd.read_csv('sales_data.csv', parse_dates=['date'], index_col='date')

# Plot
df['sales'].plot(figsize=(12, 4), title='Monthly Sales')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.show()

# Resample to monthly averages
monthly = df['sales'].resample('M').mean()
monthly.plot()

Decomposition

from statsmodels.tsa.seasonal import seasonal_decompose

result = seasonal_decompose(df['sales'], model='additive', period=12)
result.plot()
plt.tight_layout()
plt.show()

Stationarity Test (ADF)

from statsmodels.tsa.stattools import adfuller

def check_stationarity(series):
    result = adfuller(series.dropna())
    print(f'ADF Statistic: {result[0]:.4f}')
    print(f'p-value: {result[1]:.4f}')
    if result[1] < 0.05:
        print('✅ Series is stationary')
    else:
        print('❌ Series is non-stationary — differencing needed')

check_stationarity(df['sales'])

# If non-stationary, difference the series
df['sales_diff'] = df['sales'].diff()
check_stationarity(df['sales_diff'])

ARIMA Forecasting

from statsmodels.tsa.arima.model import ARIMA
from sklearn.metrics import mean_absolute_error

# Split train/test
train = df['sales'][:-12]
test = df['sales'][-12:]

# Fit ARIMA(p,d,q)
model = ARIMA(train, order=(1, 1, 1))
fitted = model.fit()

# Forecast
forecast = fitted.forecast(steps=12)

# Evaluate
mae = mean_absolute_error(test, forecast)
print(f'MAE: {mae:.2f}')

# Plot
plt.figure(figsize=(12, 4))
train.plot(label='Train')
test.plot(label='Actual')
forecast.plot(label='Forecast')
plt.legend()
plt.show()

Facebook Prophet — Easiest Forecasting in 2026

from prophet import Prophet

# Prophet requires 'ds' (date) and 'y' (value) columns
df_prophet = df.reset_index().rename(columns={'date': 'ds', 'sales': 'y'})

model = Prophet(
    yearly_seasonality=True,
    weekly_seasonality=False,
    daily_seasonality=False
)
model.fit(df_prophet)

# Forecast 12 months ahead
future = model.make_future_dataframe(periods=12, freq='M')
forecast = model.predict(future)
model.plot(forecast)
model.plot_components(forecast)
plt.show()

FAQ

ARIMA vs Prophet vs LSTM — which should I use?

Prophet for quick, interpretable forecasting (great for business users). ARIMA when you need statistical rigor and understand the model. LSTM for complex patterns where traditional models fail. Start with Prophet, move to LSTM only if needed.

How much data do I need for time series forecasting?

At minimum: 2-3x the forecast horizon. For monthly forecasting 12 months ahead, you need at least 24-36 months of history. More data = better seasonal pattern detection.

Leave feedback about this

  • Rating

Latest Posts

List of Categories