Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
Time series analysis in Python means loading observations that are ordered in time into a pandas object with a proper date index, plotting and decomposing them, testing whether they are stationary, fitting a model such as ARIMA with statsmodels, and checking the residuals before you forecast. The statsmodels time series module (statsmodels.tsa, stable release 0.15.0) and the pandas time series tools cover that whole workflow with free, open-source packages.
This page is an end-to-end map of that workflow for researchers, with the exact import paths and parameters taken from the current official documentation. Each step links to a deeper CASRAI page where one exists, so you can stay on the main path here and go deeper only where your data needs it.
What time series analysis in Python is used for in research
A time series is a set of measurements of the same quantity taken in time order: monthly case counts, daily sensor readings, quarterly outcomes, annual citation counts. Time order matters because neighbouring observations are usually related, which breaks the independence assumption behind many standard tests. Python tooling for this has three jobs: handling dates and frequencies correctly (pandas), describing structure such as trend, seasonality and autocorrelation (statsmodels), and fitting and forecasting with models (statsmodels, plus specialist packages listed in the alternatives table below).
Typical research questions are descriptive (is there a seasonal cycle, and how strong is it), inferential (does an intervention coincide with a change in level), and predictive (what does the model expect over the next periods). The steps below serve all three, but the model-fitting step is the one that is most sensitive to assumptions, so the sections on stationarity and residual checks are not optional extras.
How to install or access it
The statsmodels installation page gives two routes. With pip, run python -m pip install statsmodels. With conda, run conda install -c conda-forge statsmodels. The documented minimum versions are Python 3.9 or later, NumPy 1.23.5, SciPy 1.8, pandas 1.4 and Patsy 0.5.6. pandas itself is installed separately: the pandas documentation lists pip install pandas and conda install -c conda-forge pandas. The statsmodels graphics functions used for autocorrelation plots draw with Matplotlib, so install it as well if your environment does not already have it.
python -m pip install statsmodels pandas matplotlib
Step-by-step: from raw dates to a fitted ARIMA model
Step 1. Build a clean, sorted DatetimeIndex
Convert your date column with pd.to_datetime, which turns a list or column of date strings into a DatetimeIndex; passing errors="coerce" turns unparseable entries into NaT instead of raising an error, which lets you find and inspect bad rows rather than lose the whole load. Then make the dates the index and sort it. The pandas time series guide warns that some methods “may have unexpected or incorrect behavior if the dates are unsorted”, so sorting is a required step, not tidiness.
import pandas as pd
df = pd.read_csv("measurements.csv")
df["date"] = pd.to_datetime(df["date"], errors="coerce")
df = df.dropna(subset=["date"]).set_index("date").sort_index()
y = df["value"]
Two index details cause quiet errors later. First, pd.date_range defaults to calendar-day frequency and includes both the start and end dates, so a range you build to match your data must use the frequency your data actually has. Second, time zones: tz_localize("UTC") attaches a zone to naive timestamps and tz_convert converts between zones, so decide on one zone before you merge series from different instruments. If you need to change the sampling interval, for example to aggregate to coarser bins, ts.resample("2h").mean() is the documented pattern; the CASRAI guide on pandas resample covers aggregation choices and gaps in detail.
Step 2. Plot the series and decompose it
Plot first (y.plot() uses Matplotlib through pandas) and look for trend, repeating seasonal patterns, outliers and breaks. Then separate the components with seasonal_decompose from statsmodels.tsa.seasonal. Its signature is seasonal_decompose(x, model='additive', filt=None, period=None, two_sided=True, extrapolate_trend=0). The model is either 'additive' or 'multiplicative' (abbreviated 'add' and 'mul'). The period argument must be given when x is not a pandas object or when its index has no frequency set. The function returns a DecomposeResult with trend, seasonal and resid attributes. The statsmodels time series reference also lists an STL class in the same module for a decomposition method that is configured through a class interface.
from statsmodels.tsa.seasonal import seasonal_decompose
result = seasonal_decompose(y, model="additive", period=12)
result.plot()
Here period=12 is only an example for monthly data with a yearly cycle; set it to the number of observations in one seasonal cycle in your own data.
Step 3. Look at autocorrelation
The autocorrelation function shows how strongly the series correlates with its own past values at each lag. In statsmodels, from statsmodels.graphics.tsaplots import plot_acf gives the plot; its signature is plot_acf(x, ax=None, lags=None, *, alpha=0.05, use_vlines=True, adjusted=False, fft=False, missing='none', ...), and the lag and alpha options after the star are keyword-only. The shaded band is a confidence interval at the level set by alpha (95% for alpha=0.05), computed with Bartlett’s formula for raw data. Bars outside the band indicate autocorrelation that is significantly different from zero at that level. A partial version, pacf, lives in statsmodels.tsa.stattools next to acf. For interpretation of the shapes you see, read the CASRAI guide on autocorrelation in time series data.
from statsmodels.graphics.tsaplots import plot_acf
plot_acf(y, lags=24)
Step 4. Test for stationarity
ARIMA-type models assume the series is stationary after differencing, so test before you choose the differencing order. adfuller in statsmodels.tsa.stattools runs the augmented Dickey-Fuller test. Its signature is adfuller(x, maxlag=None, regression='c', autolag='AIC', ...). The regression argument takes 'c' (constant only), 'ct' (constant and trend), 'ctt' (constant, linear and quadratic trend) or 'n' (no constant); autolag takes 'AIC', 'BIC', 't-stat' or None. The null hypothesis is that there is a unit root; the alternative is that there is none. A small p-value is therefore evidence against a unit root, and a large one means you cannot reject it, which usually leads you to difference the series and test again.
Version note: as of statsmodels 0.15.0 the plain tuple return of adfuller is deprecated and emits a FutureWarning. Passing result_object=True returns an ADFullerResult object with named attributes statistic, pvalue, lags, nobs and critical_values, which is easier to read and will not break when the tuple form is removed.
from statsmodels.tsa.stattools import adfuller
adf = adfuller(y, regression="c", autolag="AIC", result_object=True)
print(adf.statistic, adf.pvalue, adf.lags, adf.nobs)
print(adf.critical_values)
y_diff = y.diff().dropna() # difference once, then test again
Step 5. Fit an ARIMA model
The current statsmodels ARIMA class is statsmodels.tsa.arima.model.ARIMA (also reachable as sm.tsa.arima.ARIMA). Its signature begins ARIMA(endog, exog=None, order=(0, 0, 0), seasonal_order=(0, 0, 0, 0), trend=None, ...). The order argument is (p, d, q): autoregressive terms, differencing, and moving-average terms. The seasonal_order argument is (P, D, Q, s) where s is the seasonal period and must be strictly greater than 1. The trend argument accepts 'n', 'c', 't' or 'ct'. The documented usage is to build the model, call fit(), and print the summary. Seasonal models can also be fitted through statsmodels.tsa.statespace.sarimax.SARIMAX, and exponential smoothing is available as statsmodels.tsa.holtwinters.ExponentialSmoothing.
from statsmodels.tsa.arima.model import ARIMA
mod = ARIMA(y, order=(1, 1, 1))
res = mod.fit()
print(res.summary())
The orders (1, 1, 1) above are placeholders to show the call, not a recommendation: choose p, d and q from your stationarity test and autocorrelation plots, and compare candidates with the information criteria in the summary. The CASRAI guide to ARIMA models for research time series covers order selection and interpretation, and the statsmodels API guide explains the library’s wider structure.
Step 6. Forecast and check the residuals
The fitted results object has forecast([steps, signal_only]) for out-of-sample forecasts, and get_forecast([steps, signal_only]), which the statsmodels documentation describes as returning out-of-sample forecasts together with prediction intervals. Use get_forecast when you need to report uncertainty, which in research reporting is nearly always. Before trusting either, check that the residuals look like noise: plot their autocorrelation, and use a portmanteau test such as the one in the CASRAI guide on the Box-Ljung test.
fc = res.get_forecast(steps=12)
resid = res.resid
plot_acf(resid, lags=24)
Output and how to read it
Each step produces a different kind of output, and each answers one question.
- Decomposition: three components. If the seasonal component is flat or the residual still shows a pattern, the chosen model type or period does not match the data.
- Autocorrelation plot: bars outside the confidence band at a lag mean autocorrelation at that lag is significantly different from zero. A slow decay over many lags is a common sign that the series is not stationary.
- ADF result: compare the statistic with the critical values and read the p-value against your chosen threshold. Remember the direction: the null is a unit root, so rejecting it supports stationarity.
- ARIMA summary: coefficient estimates with standard errors and p-values, plus fit statistics such as AIC and BIC used to compare candidate models fitted to the same series.
- Forecast: point forecasts and, from
get_forecast, prediction intervals. Intervals widen with the forecast horizon; report them, not just the central line.
Troubleshooting
seasonal_decompose asks for a period
This happens when the input is not a pandas object or its index has no frequency. Either set the frequency on the index (for example by resampling to a regular interval first) or pass period explicitly.
A FutureWarning from adfuller
The tuple return is deprecated as of statsmodels 0.15.0. Pass result_object=True and read the named attributes instead.
Odd results from slicing, shifting or resampling
Check that the index is sorted and, if you mix sources, that every series uses the same time zone. Unsorted dates are the one problem the pandas documentation flags explicitly for time series methods.
Missing or unparseable dates
Use errors="coerce" in pd.to_datetime, then count and inspect the resulting NaT rows before dropping them, so that you can report how many observations were excluded and why.
The model fits but forecasts look wrong
Revisit stationarity, the seasonal period and the residual autocorrelation. A model whose residuals still show structure is missing something, and its prediction intervals cannot be trusted.
Free alternatives and complements
statsmodels is not the only free option. The table lists packages whose own documentation describes them as below.
| Package | What its documentation says it is | Use it when |
|---|---|---|
statsmodels (statsmodels.tsa) |
Time series module with ARIMA, SARIMAX, seasonal decomposition, ADF test, autocorrelation functions and exponential smoothing | You want classical statistical models with detailed summaries and tests |
| sktime | “A unified framework for machine learning with time series” with a scikit-learn-style API; BSD-3-Clause licence; supports forecasting, classification, regression, clustering and anomaly detection | You want one interface across many forecasting or classification methods |
| pmdarima | An ARIMA estimator library that “brings R’s beloved auto.arima to Python”; written in Python and Cython with no R code | You want automated ARIMA order search |
Frequently asked questions
How do I start time series analysis in Python?
Install statsmodels and pandas, convert your dates with pd.to_datetime, set and sort a DatetimeIndex, then plot, decompose, test stationarity with adfuller and fit a model with ARIMA, as in the steps above.
Which Python library is used for time series analysis?
pandas handles dates and resampling, and statsmodels provides the statistical time series models and tests. sktime and pmdarima add machine-learning-style interfaces and automated ARIMA search.
Do I need a stationary series before fitting ARIMA?
ARIMA works on a series made stationary by differencing; the d in order=(p, d, q) is the number of differences. The ADF test, whose null hypothesis is a unit root, helps you choose it.
How do I get prediction intervals?
Call get_forecast on the fitted results; the documentation describes it as returning out-of-sample forecasts and prediction intervals, while forecast returns the forecasts alone.
Sources
- statsmodels: Time Series analysis (tsa), stable 0.15.0, read 2026-11-15.
- statsmodels: ARIMA, read 2026-11-15.
- statsmodels: ARIMAResults, read 2026-11-15.
- statsmodels: adfuller, read 2026-11-15.
- statsmodels: seasonal_decompose, read 2026-11-15.
- statsmodels: plot_acf, read 2026-11-15.
- statsmodels: Installing statsmodels, read 2026-11-15.
- pandas user guide: Time series / date functionality, read 2026-11-15.
- sktime documentation, read 2026-11-15.
- pmdarima documentation, read 2026-11-15.
Data: Python time series workflow: task to statsmodels function map
Maps each step of a Python time series workflow to the library function, import path and key parameters documented in the current statsmodels and pandas documentation, compiled from the official reference pages.
Period covered: 2026.
| Task | Function | Import path | Key parameters |
|---|---|---|---|
| Convert dates | pd.to_datetime | pandas | errors='coerce' gives NaT for unparseable entries |
| Decompose | seasonal_decompose | statsmodels.tsa.seasonal | model='additive' or 'multiplicative'; period required if index has no frequency |
| Autocorrelation plot | plot_acf | statsmodels.graphics.tsaplots | lags; alpha=0.05 (keyword-only) |
| Stationarity test | adfuller | statsmodels.tsa.stattools | regression c/ct/ctt/n; autolag AIC/BIC/t-stat/None; result_object=True |
| ARIMA fit | ARIMA | statsmodels.tsa.arima.model | order=(p,d,q); seasonal_order=(P,D,Q,s) with s>1; trend n/c/t/ct |
| Seasonal ARIMA | SARIMAX | statsmodels.tsa.statespace.sarimax | listed in the statsmodels tsa reference |
| Forecast | get_forecast | results object of the fitted model | steps; returns forecasts and prediction intervals |
Sources
- statsmodels tsa reference (0.15.0) (accessed 2026-11-15)
- statsmodels adfuller (accessed 2026-11-15)
- statsmodels seasonal_decompose (accessed 2026-11-15)
- statsmodels ARIMA (accessed 2026-11-15)
- statsmodels plot_acf (accessed 2026-11-15)
- pandas time series user guide (accessed 2026-11-15)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







