HomeStatistical ModelAR Model Calculator: Fit AR(p), ADF, PACF, AIC | StatsUnlock

AR Model Calculator: Fit AR(p), ADF, PACF, AIC | StatsUnlock

AR Model Calculator

Fit an autoregressive AR(p) time series model online in one click. This free autoregressive model calculator tests stationarity with the ADF test, picks the order p with AIC and BIC, estimates the coefficients with p-values, checks the residuals with Ljung-Box, plots the ACF and PACF, and forecasts ahead, with an APA-ready write-up.

Time SeriesAutoregressive AR(p)ADF Stationarity TestACF & PACFAIC / BIC Order SelectionForecastFree Online

⚡ 0. Quick Answer

An AR model calculator fits an autoregressive model, where each value of a time series is predicted from its own previous p values plus random noise.

For an AR(1), the coefficient φ₁ says how much of today’s deviation from the mean carries into the next step. The series must be stationary first, which the ADF test checks, and the order p is chosen where AIC or BIC is lowest. An AR model describes memory in a series. It does not explain what causes it.

yₜ = c + φ₁yₜ₋₁ + φ₂yₜ₋₂ + … + φₚyₜ₋ₚ + εₜ

Rule of thumb: fit the model only if the ADF p-value is below 0.05 and every inverse root is below 1. Choose p where the PACF cuts off and AIC is lowest, then accept the model if the Ljung-Box p-value on the residuals is above 0.05. For the worked bird-count data, φ₁ = 0.553, p < 0.001.

Key takeaways

  • The AR model calculator regresses a series on its own lags: AR(1) uses 1 lag, AR(2) uses 2.
  • Run the ADF test first: a p-value below 0.05 rejects a unit root, so the series is stationary enough to model.
  • The PACF cuts off after lag p, and the order with the lowest AIC or BIC confirms the choice.
  • Persistence is the sum of the φ coefficients; a value near 1 means shocks last a long time and warns of a unit root.
  • A Ljung-Box p above 0.05 on the residuals means the model has captured the memory in the data.

📚 1. What Is an AR Model?

An autoregressive (AR) model is a time series model in which the current value is a linear function of its own previous values plus white noise. “Auto” means self, so an AR model is a regression of a series on itself. The order p tells you how many past values are used. AR(1) uses only the last value. AR(2) uses the last two. The general AR(p) uses the last p.

What it measures: the memory of a process. A coefficient φ₁ of 0.8 means a series that drifts slowly, with high values followed by high values for many steps. A coefficient of 0.2 means the series forgets almost at once. A negative coefficient means high values tend to be followed by low ones, a zig-zag. The model also gives the long-run mean the series returns to, how fast it returns, and a forecast with a prediction interval.

A worked one-liner: for 36 monthly waterbird counts at a wetland, the fitted AR(1) is ŷₜ = 22.773 + 0.553 yₜ₋₁. Last month’s count was 51, so next month’s forecast is 22.773 + 0.553 × 51 = 50.98 birds, and the series returns to a long-run mean of 22.773 ÷ (1 − 0.553) = 50.96.

y(t−2)y(t−1)y(t)× φ₂× φ₁shock ε(t)constant cy(t) = c + φ₁y(t−1) + φ₂y(t−2) + ε(t)
An AR(2) model in one picture. Today’s value yₜ is built from a constant c, a share φ₁ of yesterday’s value, a share φ₂ of the value before that, and a fresh random shock εₜ.

Who uses it: ecologists use AR models to measure density dependence in animal counts and to remove autocorrelation before testing a trend. Hydrologists model river flow and water temperature. Economists model unemployment, inflation and sales. Clinicians model daily patient numbers and heart rate. Engineers use AR models in signal processing, where the coefficients describe the spectrum of a signal. Students meet AR(1) first in every time series course because ARIMA, VAR and GARCH are all built on it.

FeatureAR(p) modelMA(q) modelARIMA(p, d, q)
Predicts fromPast values of the seriesPast random shocksBoth, after differencing d times
ACF patternDecays slowly or oscillatesCuts off after lag qMixed
PACF patternCuts off after lag pDecays slowlyMixed
Needs stationarityYesAlways stationaryNo, differencing handles trends
EstimationOrdinary least squares worksNeeds maximum likelihoodNeeds maximum likelihood
Best forSmooth persistence, density dependenceShort one-off shocksTrending or wandering series

🧮 2. Set Up Your Data

Used in the write-up templates. Leave blank for “the study site”.

Type or paste one series per cluster, oldest value first, separated by commas (spaces, tabs and new lines also work). Each cluster is fitted as its own series. Click the name to rename it.

Supports .csv, .txt, .xlsx and .xls. One series per column, oldest value at the top. Headers are detected automatically.

Type one value per cell, oldest at the top. Each column becomes a cluster, and its header is the series name. Empty cells are ignored.


Capped at one third of the series length.

📊 3. Results

Enter or load a time series above, then press Fit AR Model. The ADF stationarity test, the AIC and BIC order table, the coefficients with p-values, residual checks, forecasts, four charts and the auto-filled write-up will appear here.

🧠 4. Interpretation of Results, In Detail

Run the calculator to fill this box with five paragraphs about your own series: stationarity ___, coefficients ___, order choice ___, residual checks ___ and forecast ___. The twelve sub-sections below explain every number in the output.

4.1 Read the output in this order

An AR model output has a natural reading order, and following it stops you drawing conclusions from numbers that are not yet valid. First, check stationarity with the ADF result. Second, check the order: did AIC, BIC and the PACF point to the same p? Third, read the coefficients and their p-values. Fourth, check the residuals with Ljung-Box. Only then read the forecast. A coefficient p-value is meaningless if the series has a unit root, and a forecast is unreliable if the residuals still carry memory, so the order matters.

4.2 What the ADF stationarity test tells you

The augmented Dickey-Fuller test asks whether the series has a unit root, meaning a shock never fades and the series wanders without a fixed mean. The null hypothesis is a unit root. A small p-value, below α, rejects it, so the series is stationary and the AR model is appropriate. A large p-value means you cannot rule out a unit root.

For the worked bird counts, τ = −3.084 against a 5% critical value of −2.949, so p = 0.028 and the series is stationary at the 5% level but not at the 1% level. Note the direction: the test statistic must be more negative than the critical value. A τ of −1.2 is far from rejection. The ADF test has low power in short series, so a p-value of 0.08 in 35 observations is not strong evidence of a unit root; it is weak evidence either way. When in doubt, also fit the differenced series and see whether the conclusions change.

4.3 What the coefficients φ mean

Each φₖ is the effect of the value k steps back on the current value, holding the other lags fixed. In an AR(1), φ₁ is also the lag-1 autocorrelation of the process. A value of 0.553 means that if this month’s count is 10 birds above the long-run mean, next month’s expected count is 5.5 above it, and the month after that 0.553² × 10 = 3.1 above it. The deviation shrinks geometrically.

  • 0 < φ₁ < 1: smooth persistence. The closer to 1, the longer the memory.
  • −1 < φ₁ < 0: a zig-zag. High values tend to be followed by low ones, typical of over-correction or alternate-year cycles such as masting.
  • |φ₁| ≥ 1: not stationary. Shocks never fade or grow without limit.

In AR(2) and higher, individual coefficients can look strange, for example φ₁ = 1.15 and φ₂ = −0.46 in the river temperature data. That is not an error. Read them together through their sum and through the roots described in 4.6.

4.4 The intercept is not the mean

The most common misreading of AR output is to treat the intercept c as the average of the series. It is not. The long-run mean is μ = c ÷ (1 − Σφ). For the bird counts, c = 22.77 but μ = 22.77 ÷ 0.447 = 50.96, which matches the sample mean of 51.03 closely. Some software, including R’s arima(), reports μ and labels it “intercept”, which is why outputs from different programs appear to disagree. This calculator reports both and labels each one.

4.5 Persistence and half-life

The sum of the coefficients, Σφ, is the single best summary of memory. Below about 0.5 the series forgets quickly. Between 0.5 and 0.9 it has moderate memory. Above 0.9 shocks last a long time, and the ADF test will often struggle to reject a unit root. The half-life turns this into time units: the number of steps for a shock to fall to half its size. For an AR(1) it is ln(0.5) ÷ ln(φ₁). The bird counts give 1.17 months, so a flood that pushes counts up is mostly gone within two months. In ecology the same number measures the strength of density dependence: a short half-life means a population is pulled back to carrying capacity quickly.

4.6 Inverse roots and stationarity of the fitted model

The ADF test checks the data. The roots check the fitted model. The characteristic equation 1 − φ₁z − … − φₚzᵖ = 0 has p roots, and the model is stationary when every root lies outside the unit circle, or equivalently when every inverse root |λ| is below 1. The calculator reports the largest inverse root. A value of 0.98 is technically stationary but practically a near unit root, and the forecasts will take a very long time to return to the mean.

When the inverse roots are complex numbers, the series shows a damped pseudo-cycle. The textbook AR(2) with φ₁ = 0.806 and φ₂ = −0.506 has complex roots and a cycle of about 6.5 periods, which you can see as the wave in its ACF. Lynx and hare populations show the same signature, which is why Yule invented the AR(2) to study cycles in 1927.

4.7 How to read AIC, BIC and the PACF together

The PACF at lag k is the correlation between yₜ and yₜ₋ₖ after removing the effect of the lags in between. For a true AR(p), the PACF is clearly non-zero up to lag p and then drops inside the ±1.96 ÷ √n bands. That is the classic Box-Jenkins rule for identifying p.

AIC and BIC formalise the same idea. Both reward a better fit and penalise each extra coefficient; BIC penalises more, by ln(n) per parameter instead of 2. AIC therefore tends to choose slightly larger models, which is good for forecasting, and BIC tends to choose the true order in large samples, which is good for explanation. When AIC, BIC and the PACF agree, as they do for the bird counts at p = 1, you can be confident. When they disagree, report the BIC model as the main result and the AIC model as a sensitivity check. Differences in AIC smaller than 2 mean the two models are practically equivalent.

4.8 Residual diagnostics: Ljung-Box and normality

If the model is adequate, the residuals should be white noise: no autocorrelation left. The Ljung-Box test pools the residual autocorrelations over several lags into one Q statistic, with degrees of freedom reduced by p because the coefficients were estimated from the same data. A p-value above α means no evidence of leftover memory. For the bird counts Q(7) = 6.634 on 6 df, p = 0.356, so AR(1) is enough.

A failed Ljung-Box test is the most useful warning in the output. It usually means the order is too low, a seasonal pattern is present (a spike at lag 12 in monthly data), or the series needs an MA term. Normality of residuals, tested with Jarque-Bera, matters less. The coefficients remain consistent without it, but prediction intervals assume normal errors, so a clear failure means the intervals are approximate.

4.9 R², σ² and how good the model really is

R² here is the share of variation in the next value explained by past values. For the bird counts it is 0.306. That sounds modest, but in time series it is typical: most month-to-month change is fresh noise that no model can predict. Compare σ = 4.05 with the series SD of 4.72. The AR model narrows the uncertainty about the next value by about 14%. Use σ² and AIC to compare models fitted to the same series, not R² across different series.

4.10 What the forecast can and cannot do

A stationary AR forecast moves toward the long-run mean, and its prediction interval widens quickly and then stops widening. After a few half-lives the forecast is simply the mean. That is a feature, not a weakness: it honestly says the past contains no more information. For the bird counts, the one-step forecast is 50.98 with a 95% interval of 43.05 to 58.92, and by six months ahead the interval is 41.44 to 60.49, almost the width of the raw data. An AR model cannot forecast a change in regime, a new trend or a shock that has not happened yet.

4.11 Common mistakes this calculator prevents

  • Fitting a random walk. The ADF check and the root check warn you before you report a meaningless φ near 1.
  • Comparing AIC across different samples. Orders 0 to the maximum are all fitted to the same rows, so AIC values are comparable.
  • Reading the intercept as the mean. Both are reported and labelled.
  • Ignoring leftover autocorrelation. Ljung-Box uses the correct degrees of freedom, lags minus p.
  • Over-fitting. A non-significant highest lag is flagged.
  • Data entered newest first. The note under every box reminds you that the oldest value comes first.

4.12 Practical judgement, a decision guide

What you seeWhat it meansWhat to do
ADF p < 0.05, Ljung-Box p > 0.05, AIC = BIC orderClean, well-specified modelReport it with the templates in Section 5
ADF p > 0.10, Σφ near 1Unit root likelySet Differencing to First difference and refit
Ljung-Box p < 0.05Memory left in residualsRaise p, check lag 12 for seasonality, or try ARMA
AIC and BIC disagreeWeak evidence for the extra lagsReport BIC model, show AIC model as sensitivity
Selected order is 0No usable memory, white noiseReport the mean and SD; the series is unpredictable from its past
φ₁ significant but R² below 0.1Real but small memoryReport it, but do not oversell the forecast

✍ 5. How to Write Your Results in Research

When reporting AR model results in APA format, a reader needs five things: how stationarity was checked, how the order was chosen, the coefficients with their uncertainty, the residual diagnostics, and the software. The five templates below fill themselves from your results.

▶ Run the analysis above to auto-fill all five examples with your results.

Example 1, APA 7th Edition Results Paragraph
An augmented Dickey-Fuller test indicated that the series was stationary (ADF τ = ___, p = ___). An AR(___) model selected by AIC gave φ₁ = ___, SE = ___, t(___) = ___, p = ___. The Ljung-Box test showed Q(___) = ___, p = ___.
📌 Key conventions for this style
  • Report the test, its statistic, degrees of freedom where they exist, and an exact p-value to two or three decimals; write p < .001 for anything smaller.
  • APA drops the leading zero for p but keeps it for coefficients that can exceed 1.
  • State how the order was chosen (AIC, BIC or PACF) and the range of orders compared.
  • Italicise statistical symbols such as t, p and Q in the final manuscript.
Example 2, Thesis or Dissertation Methods and Results
The series (n = ___, M = ___, SD = ___) was analysed with an autoregressive model. Stationarity was assessed with the ADF test (τ = ___, p = ___). AIC favoured p = ___ and BIC favoured p = ___. The final AR(___) model was ___.
📌 Key conventions for this style
  • Give the full fitted equation so an examiner can reproduce a forecast by hand.
  • Report the long-run mean separately from the intercept and say which is which.
  • Put the AIC and BIC table for all candidate orders in an appendix.
  • Name the estimation method (conditional least squares, Yule-Walker or exact maximum likelihood), because they give slightly different numbers.
Example 3, Plain-Language Summary
We tracked ___ for ___ months. About ___% of an unusually high or low value carries over to the next month, and a sudden change fades to half its size in about ___ months.
📌 Key conventions for this style
  • Translate φ₁ into “how much carries over” and the half-life into time units.
  • No symbols, no p-values, no model names beyond “a forecasting model”.
  • Always give the forecast as a range, never as a single number.
  • Say plainly that the model describes a pattern, not its cause.
Example 4, Structured Abstract or Conference Poster
Objective: ___. Methods: ___ observations; ADF test; AR order by AIC/BIC. Results: ADF τ = ___; AR(___), φ₁ = ___ (95% CI ___ to ___). Conclusion: ___.
📌 Key conventions for this style
  • Keep to one line per heading; posters are read from two metres away.
  • Use the confidence interval for φ₁ instead of the SE; it is easier to read.
  • Put chart 1 (observed, fitted and forecast) beside the abstract.
  • Stay under 250 words for most conference abstracts.
Example 5, Replication or Pre-Registration
Pre-registered analysis plan. Data: ___, one value per ___, oldest first. Stationarity: ADF with a constant, lag by AIC, α = ___. Order: AR(p) for p = 0 to ___ on a common sample. Diagnostics: Ljung-Box on ___ lags.
📌 Key conventions for this style
  • Fix the maximum order, the criterion and the ADF lag rule before seeing the data.
  • State the rule for differencing in advance, so the decision is not data-driven after the fact.
  • Give the missing-value rule. AR models need equally spaced time points, so gaps must be handled explicitly.
  • Report the observed numbers to three or more decimals so a replication can be compared exactly.

5.1 Methods wording

Say what the series is, its time step, its length, and that it was ordered oldest first with no gaps. Then name the stationarity test and its settings (constant only or constant and trend, lag rule), the range of orders compared, the criterion that decided, and the estimation method. A sentence such as “Orders 0 to 6 were compared on a common estimation sample and the order minimising AIC was retained” is enough for most journals.

5.2 The results sentence

Lead with the stationarity result, then the chosen order, then the coefficients with SE or confidence interval and p, then the residual check. Always include n. For the worked example: “The series was stationary (ADF τ = −3.08, p = .028). AIC and BIC both selected AR(1), φ₁ = 0.55, SE = 0.14, t(33) = 3.82, p < .001, with white-noise residuals, Q(6) = 6.63, p = .356.”

5.3 Tables and figures

A results table needs one row per coefficient with estimate, SE, t, p and confidence interval, plus rows for σ², AIC, BIC and n. The standard figure is chart 1, the observed series with the fitted line and forecast band. Reviewers often ask for the ACF and PACF as a second panel, which is chart 2. Label the time axis in real units, not “index”.

5.4 The discussion sentence

Interpret the persistence in the language of the field. An ecologist writes that counts showed moderate density dependence with a half-life of 1.2 months. An economist writes that shocks to unemployment were persistent. Avoid causal claims: autocorrelation shows memory, not mechanism.

5.5 Reporting checklist

  • ✓ n, time step and date range
  • ✓ ADF statistic, lag length, p-value, and whether a trend term was used
  • ✓ Orders compared, criterion used, and the order chosen
  • ✓ Every coefficient with SE or confidence interval and p
  • ✓ Long-run mean and residual variance
  • ✓ Ljung-Box statistic, lags, df and p
  • ✓ Estimation method and software with version

∑ 6. Formulas Used

①
The AR(p) Model
yₜ = c + φ₁yₜ₋₁ + φ₂yₜ₋₂ + … + φₚyₜ₋ₚ + εₜ,   εₜ ~ WN(0, σ²)
yₜValue of the series at time t, in the units of the data
cIntercept, in data units. Not the mean of the series
φₖAutoregressive coefficient for lag k, unitless
pOrder, the number of lags used
εₜ, σ²White-noise shock and its variance, in squared data units
ExampleBird counts: ŷₜ = 22.773 + 0.553yₜ₋₁
②
Conditional Least Squares Estimate
β̂ = (XᵀX)⁻¹ Xᵀy  ·  SE(β̂ⱼ) = √[σ̂² (XᵀX)⁻¹ⱼⱼ]  ·  σ̂² = SSR ÷ (nₑ − p − 1)
XDesign matrix: a column of 1s and the p lagged columns
β̂Estimated (c, φ₁, …, φₚ)
nₑUsable rows, n − p, because the first p values have no full set of lags
SSRSum of squared residuals, in squared data units
Testt = β̂ ÷ SE on nₑ − p − 1 df; bird data t(33) = 3.818
③
Yule-Walker Equations
ρₖ = φ₁ρₖ₋₁ + φ₂ρₖ₋₂ + … + φₚρₖ₋ₚ,   k = 1 … p  ·  σ² = γ₀(1 − Σφₖρₖ)
ρₖAutocorrelation at lag k, unitless, between −1 and 1
γ₀Variance of the series, sample autocovariance with denominator n
Use forA quick, always-stationary estimate; R’s ar() default
NoteFor AR(1) it reduces to φ̂₁ = r₁, the lag-1 autocorrelation
④
Augmented Dickey-Fuller Test
Δyₜ = α + γyₜ₋₁ + Σᵢ₌₁ᵏ δᵢΔyₜ₋ᵢ + eₜ  ·  τ = γ̂ ÷ SE(γ̂)
γEquals Σφ − 1. Zero under the unit-root null
kLagged differences, chosen by AIC up to ⌈12(n/100)¼⌉
τTest statistic. Compare with MacKinnon critical values, not the t table
RuleReject the unit root when τ is below the critical value (5%: about −2.95 for n = 35)
ExampleWith k = 0, τ = (φ̂₁ − 1) ÷ SE = (0.5532 − 1) ÷ 0.1449 = −3.084
⑤
ACF, PACF and Order Selection
rₖ = Σ(yₜ − ȳ)(yₜ₋ₖ − ȳ) ÷ Σ(yₜ − ȳ)²  ·  AIC = −2ℓ + 2(p + 2)  ·  BIC = −2ℓ + ln(nₑ)(p + 2)
rₖSample autocorrelation at lag k; the PACF comes from these by Durbin-Levinson
ℓGaussian log-likelihood, −(nₑ/2)[ln(2π) + ln(SSR/nₑ) + 1]
p + 2Parameters counted: intercept, p coefficients and σ², as R AIC() does
Bands±1.96 ÷ √n; bird data ±0.327
RuleAll orders use the same rows, so AIC values are comparable
⑥
Stationarity, Long-Run Mean and Half-Life
1 − φ₁z − … − φₚzᵖ = 0, all |z| > 1  ·  μ = c ÷ (1 − Σφ)  ·  h₁/₂ = ln 0.5 ÷ ln φ₁
zRoots of the characteristic polynomial; inverse roots |λ| = 1 ÷ |z| must be below 1
μLong-run mean, in data units; bird data 50.96
h₁/₂Half-life in time steps, AR(1) only; bird data 1.17 months
RangeAR(1) stationary when −1 < φ₁ < 1
⑦
Residual Checks and Forecast
Q = n(n + 2) Σₖ₌₁ᵐ rₖ² ÷ (n − k) ~ χ²(m − p)  ·  ŷₙ₊ₕ ± z₁₋ₐ/₂ σ√(Σⱼ₌₀ʰ⁻¹ ψⱼ²)
QLjung-Box statistic on the residual autocorrelations rₖ
mLags tested, min(10, n ÷ 5) but at least p + 1; df = m − p
ψⱼImpulse-response weights; for AR(1), ψⱼ = φ₁ʲ
RuleLjung-Box p above α means the residuals are white noise
ExampleQ(7) = 6.634, df 6, p = 0.356; forecast 50.98, 95% PI 43.05 to 58.92

🔀 7. AR Model Calculation Flowchart, Step by Step

This flowchart shows how to fit an AR model step by step, from a raw column of values to a checked model and a forecast. Every box uses the same worked example as the Excel, R and Python sections: 36 monthly waterbird counts from a wetland survey.

Start or result Data step Calculation step Yes or no check
Start Raw time series 36 monthly bird counts, oldest first: 52, 48, 55, 61, 47, …, 45, 51
CheckAre the time steps equal, with no gaps or missing months?
YesCarry on. All 36 months are present and evenly spaced.
No, stopFill or model the gaps first. Deleting a month shifts every lag.
1
Run the ADF unit-root test Δyₜ = α + γyₜ₋₁ + eₜ, τ = γ̂ ÷ SE AIC picks 0 lags: τ = −3.084, 5% critical −2.949, p = 0.028
CheckIs the ADF p-value below 0.05?
YesStationary. Model the series as it is. Here p = 0.028.
NoDifference once, Δyₜ = yₜ − yₜ₋₁, and test again.
2
Plot the ACF and PACF bands ±1.96 ÷ √36 = ±0.327 PACF lag 1 = 0.553 (outside), lag 2 = 0.037 (inside): suggests p = 1
3
Compare AIC and BIC for p = 0 to 6 same 30 rows for every order AIC: 180.67, 163.38, 165.32, …; BIC lowest also at p = 1 (167.58)
4
Build the lag column pair yₜ with yₜ₋₁ 35 usable pairs: (48, 52), (55, 48), (61, 55), …, (51, 45)
5
Regress yₜ on its lag β̂ = (XᵀX)⁻¹Xᵀy c = 22.773, φ₁ = 0.5532 (SE 0.1449, t(33) = 3.818, p = 0.00056)
6
Derive the mean, persistence and fit μ = c ÷ (1 − φ₁), σ² = SSR ÷ 33 μ = 50.96, half-life 1.17 months, σ² = 16.395, R² = 0.306
CheckAre the residuals white noise (Ljung-Box p above 0.05)?
YesQ(7) = 6.634 on 6 df, p = 0.356. Accept AR(1).
No, stopRaise p or add a seasonal or MA term, then refit.
7
Forecast the next value ŷₙ₊₁ = c + φ₁yₙ ± 1.96σ 22.773 + 0.5532 × 51 = 50.98, 95% PI 43.05 to 58.92
Result AR(1): ŷₜ = 22.773 + 0.553yₜ₋₁, n = 36 Stationary, p = 0.028φ₁ significantWhite-noise residuals Rule used: ADF p < 0.05, lowest AIC and BIC, Ljung-Box p > 0.05.

Check any box yourself: the Excel sheet in Section 9, the R script in Section 10 and the Python script in Section 11 all return φ₁ = 0.5532, c = 22.7732, ADF τ = −3.0840 and a one-step forecast of 50.9842 for this dataset.

📝 8. How to Use This AR Model Calculator

  1. Enter your time series. The default tab takes comma-separated values, exactly as the placeholder shows: 52, 48, 55, 61, 47, .... Put the oldest value first. Spaces, tabs and new lines also work, so a column pasted from Excel is fine.
  2. Name each series. The name above every box is editable. Type something meaningful, such as Site A, north slope, and it appears in the results, charts and write-up.
  3. Add more series if you need them. Press Add cluster to fit several series side by side. Each one gets its own model, and a comparison table appears at the top of the results.
  4. Or upload a file. On the Upload tab choose a CSV or Excel file, then click the columns you want. Every column you click becomes its own cluster, named after its header.
  5. Try a sample dataset. Ten built-in series cover the cases that matter: a clean AR(1), an AR(2), a near unit root, white noise, a short series and a random walk that fails the ADF test.
  6. Choose the order. Leave it on Auto, lowest AIC, switch to BIC for a more cautious model, or fix p yourself. Set the largest order to compare.
  7. Set differencing and the method. Use First difference if the series trends or fails the ADF test. Keep conditional least squares to match R and Python regression output.
  8. Press Fit AR Model. Nothing is computed until you do, and any change to the inputs clears the results so you never read stale numbers.
  9. Read the checks first. Look at the ADF result, the order table and the Ljung-Box test before the coefficients. Warnings appear in an amber box when a check fails.
  10. Export and report. Section 5 fills five write-up styles with your numbers. Download a text report or a print-ready PDF with the four charts.

📈 9. How to Fit an AR Model in Excel

Excel has no AR function, but an AR(1) is just a regression of the series on its own lag, so SLOPE, INTERCEPT and LINEST do the whole job. The awkward parts are building the lag column correctly, getting the p-value, and the stationarity test, which Excel cannot give a p-value for. This section works through all of it on the 36 bird counts, with the spreadsheet shown at each stage.

The whole thing in one line: with the series in A2:A37, put =A2 in B3 and fill down to B37. Then =SLOPE(A3:A37,B3:B37) is φ₁ = 0.5532 and =INTERCEPT(A3:A37,B3:B37) is c = 22.7732.

9.1 The functions you need

You wantExcel functionNote
φ₁ for AR(1)=SLOPE(A3:A37,B3:B37)y first, lag second. Reversing them gives a different number
Intercept c=INTERCEPT(A3:A37,B3:B37)Not the mean of the series
Standard error of φ₁=INDEX(LINEST(A3:A37,B3:B37,TRUE,TRUE),2,1)Row 2 of LINEST holds the SEs
p-value of φ₁=T.DIST.2T(ABS(t),df)df = pairs minus 2 for AR(1)
Residual SD σ=STEYX(A3:A37,B3:B37)Uses SSR ÷ (nₑ − 2)
R²=RSQ(A3:A37,B3:B37)Share of next-step variation explained
Lag-k autocorrelation=CORREL(A2:A36,A3:A37)Close to, but not identical with, the textbook ACF
AR(2) or higher=LINEST(A4:A37,B4:C37,TRUE,TRUE)Lag 1 in B, lag 2 in C, rows aligned
Analysis ToolPakData → Data Analysis → RegressionEnable it first: File → Options → Add-ins → Analysis ToolPak
The LINEST column-order trap. For AR(2) and above, LINEST returns the coefficients in reverse order of the X columns: the first value is the coefficient of the last column (lag 2), not lag 1. Read the output from right to left, or check it against this calculator before you report it.

9.2 Step by step

1 Put the series in one column, oldest first

Type a header in A1 and the 36 counts in A2:A37, January of the first year at the top. The order matters: an AR model reads time from top to bottom.

Xbirds.xlsx - ExcelA2fx52A1Count252.0348.0455.0561.0647.0749.0855.0958.0

The 36 counts sit in A2:A37. Only the first eight rows are shown here.

2 Build the lag-1 column

In B3 type =A2 and fill down to B37. Each row now pairs a month with the month before it. B2 stays empty because January of the first year has no previous month.

=A2
Xbirds.xlsx - ExcelB3fx=A2AB1CountLag 1252.0348.052.0455.048.0561.055.0647.061.0749.047.0855.049.0958.055.0

Row 3 pairs 48 with the lag 52. The regression uses rows 3 to 37, giving 35 pairs.

3 Estimate φ₁ and c on a Fit sheet

On a second sheet named Fit, put labels in column A and formulas in column B that point back to the Data sheet.

=SLOPE(Data!A3:A37,Data!B3:B37)=INTERCEPT(Data!A3:A37,Data!B3:B37)=RSQ(Data!A3:A37,Data!B3:B37)
Xbirds.xlsx [Fit] - ExcelB2fx=SLOPE(Data!A3:A37,Data!B3:B37)AB1StatisticValue2phi1 (SLOPE)0.55323Intercept c22.77324R squared0.30645SE of phi10.1449

φ₁ = 0.5532 in B2, c = 22.7732 in B3 and R² = 0.3064 in B4.

4 Get the standard error, t and p-value

LINEST with its last argument TRUE returns the regression statistics; INDEX picks the SE of the slope out of row 2. The p-value then comes from the t distribution with nₑ − 2 = 33 degrees of freedom.

=INDEX(LINEST(Data!A3:A37,Data!B3:B37,TRUE,TRUE),2,1)=B2/B5=T.DIST.2T(ABS(B6),B7)
Xbirds.xlsx [Fit] - ExcelB8fx=T.DIST.2T(ABS(B6),B7)AB1StatisticValue2phi1 (SLOPE)0.55323Intercept c22.77324R squared0.30645SE of phi10.14496t statistic3.81787df338p-value0.00069sigma (STEYX)4.0491

SE = 0.1449 in B5, t = 3.8178 in B6, df = 33 in B7 and p = 0.0006 in B8.

5 The ADF statistic, by hand

When the ADF test uses zero lagged differences, as AIC chose for this series, its statistic is simply (φ̂₁ − 1) ÷ SE. Compare it with the MacKinnon critical value, not with the t table.

=(B2-1)/B5=STEYX(Data!A3:A37,Data!B3:B37)
Xbirds.xlsx [Fit] - ExcelB10fx=(B2-1)/B5AB1StatisticValue2phi1 (SLOPE)0.55323Intercept c22.77324R squared0.30645SE of phi10.14496t statistic3.81787df338p-value0.00069sigma (STEYX)4.049110ADF tau-3.084011Forecast t+150.9842

τ = −3.0840 in B10 is below the 5% critical value of −2.9485, so the unit root is rejected. σ = 4.0491 in B9.

6 Forecast, long-run mean and half-life

The one-step forecast plugs the last observation, Data!A37 = 51, into the fitted equation.

=B3+B2*Data!A37=B3/(1-B2)=LN(0.5)/LN(B2)
Xbirds.xlsx [Fit] - ExcelB11fx=B3+B2*Data!A37AB1StatisticValue2phi1 (SLOPE)0.55323Intercept c22.77324R squared0.30645SE of phi10.14496t statistic3.81787df338p-value0.00069sigma (STEYX)4.049110ADF tau-3.084011Forecast t+150.984212Long-run mean50.964613Half-life1.1706

Forecast 50.9842 in B11, long-run mean 50.9646 in B12, half-life 1.1706 months in B13.

9.3 The awkward cases

The ADF p-value. Excel can compute τ but has no Dickey-Fuller distribution. Use the critical values in table 12.2, or the MacKinnon approximation: for τ = −3.084, =NORM.S.DIST(2.1659+1.4412*B10+0.038269*B10^2,TRUE) returns 0.0278, which matches R and Python. That formula is valid for τ up to −1.61 and for the constant-only test.

ADF with lagged differences. If AIC picks k > 0 lags, build Δy in one column and its lags in the next k columns, then use LINEST on Δy with yₜ₋₁ and the lagged differences. τ is the yₜ₋₁ coefficient divided by its SE. The (φ − 1) ÷ SE shortcut no longer holds.

AR(2). Add =A2 in C4 filled down for lag 2, then =LINEST(A4:A37,B4:C37,TRUE,TRUE) as a 5 × 3 array. The rows lose one more observation, so nₑ = 34 and df = 31.

AIC in Excel. With SSR = =INDEX(LINEST(...,TRUE,TRUE),5,2) and nₑ rows, AIC = =n*LN(2*PI())+n*LN(SSR/n)+n+2*(p+2). Compare orders only on the same rows: start every regression at row pₘₐₓ + 2.

Quick ACF check: =CORREL(A2:A36,A3:A37) gives 0.5535, a hair above the textbook ACF of 0.5532, because CORREL uses separate means and variances for each half. The calculator uses the textbook definition, as R and Python do.

9.4 Why your Excel answer might differ from R or Python

SituationWhat happensFix
Data entered newest firstThe lag column points forward in time; φ looks similar but forecasts are wrongSort by date, oldest at the top
R arima() instead of lm()Exact maximum likelihood, so φ₁ = 0.539 instead of 0.553, and the “intercept” it prints, 51.06, is the mean μUse lm() on lagged data to match this page, or compare μ
R ar()Uses its own variance-based AIC; with method = "ols" it picks p = 5 for the bird countsChoose p from the common-sample AIC table, as in Section 10
statsmodels AutoRegDivides SSR by nₑ, not nₑ − p − 1, and reports z-tests, so SEs are a little smallerUse sm.OLS on the lag matrix, as in Section 11
AIC values differ by 2statsmodels OLS counts p + 1 parameters; R and this page count p + 2 including σ²Only differences between orders matter; the chosen p is the same
tseries adf.test()Includes a trend term and uses lag ⌊(n − 1)¹/³⌋ = 3, giving τ = −1.24 and no rejection for the same dataUse the constant-only regression in Section 10, or statsmodels adfuller(regression="c")
CORREL instead of ACFCORREL standardises each half separatelyUse the textbook formula in card 5 of Section 6
Blank or text cellsSLOPE silently drops the row, breaking the time orderFill gaps before fitting; never leave holes in a time series
ToolFit AR(1)ADF testPACF
Excel=SLOPE(A3:A37,B3:B37)(φ − 1) ÷ SE, lag 0 onlyNot built in
Rlm(y[-1] ~ y[-n])Manual lm on diff(y), Section 10pacf(y)
Pythonsm.OLS(y[1:], X).fit()adfuller(y, regression="c")pacf(y, method="ldb")
SPSSAnalyze → Forecasting → Create Traditional Models → ARIMA(1,0,0), exact ML
Stataregress y L.y, dfuller y, pac y

9.5 Charting the result in Excel

  1. Select A1:A37 and choose Insert → Line with Markers.
  2. Add the fitted values: in C3 type =Fit!$B$3+Fit!$B$2*B3, fill down, and add C1:C37 as a second series with a dashed line.
  3. For the forecast, extend the time axis with six empty rows and add the forecast and its interval as extra series.
  4. Label the horizontal axis in real time units, such as months, and the vertical axis with the measured variable and units.
  5. Remove gridlines and use one colour for observed data and another for fitted values, so the figure survives black-and-white printing.

Chart 1 in Section 3 draws the observed series, fitted line and forecast band automatically, which is usually quicker than rebuilding it in Excel.

9.6 Excel errors you will probably hit

Excel showsWhyFix
#N/A from SLOPEThe two ranges have different lengthsBoth ranges must start on row 3 and end on row 37
#DIV/0!The lag column is empty or constantCheck that B3 holds =A2 and was filled down
#VALUE! from LINESTText or a blank inside the rangeRemove units and fill gaps
#NUM! from LNφ₁ is negative or zero, so the half-life formula failsUse =LN(0.5)/LN(ABS(B2)) and note the zig-zag pattern
Only one number from LINESTEntered as a normal formula in an old Excel versionSelect a 5 × 2 block and press Ctrl + Shift + Enter, or use INDEX as shown
φ₁ above 1The series trends or has a unit rootDifference the series and refit; do not report an explosive AR

📈 10. How to Fit an AR Model in R

R can fit an AR model in one line with arima(y, order = c(1, 0, 0)), but that hides the stationarity test, the order choice and the residual check you need to report. The script below does all of it in base R: the ADF test with a MacKinnon p-value, AIC and BIC for orders 0 to 6 on a common sample, the AR fit by least squares, the Ljung-Box test, a forecast with prediction intervals, and one publication-ready figure at 300 dpi.

Copy the whole block. It runs top to bottom in RStudio, VS Code or plain Rscript. Change only the y <- c(...) line to use your own data, oldest value first.
stats, built in: lm, embed, pacf, acf, Box.test, ARMAtoMAgraphics and grDevices, built in: plot, png

10.1 The complete script

R, base only, saves ar_model_plot.png

# ============================================================
# AR model in R: ADF test, PACF, AIC/BIC order choice,
# AR(p) fit, residual checks and a forecast, with one figure
# StatsUnlock - https://statsunlock.com/ar-model-calculator/
# Base R only (stats + graphics). Nothing to install.
# ============================================================

# ---- 1. Your data (one value per time step, oldest first) ----
# Or read a CSV:
#   y <- read.csv("data.csv")$count
#   y <- y[!is.na(y)]          # drop missing values first
y <- c(52, 48, 55, 61, 47, 49, 55, 58, 54, 52, 50, 53,
       52, 55, 47, 55, 54, 56, 54, 52, 54, 56, 54, 53,
       55, 51, 46, 50, 48, 43, 43, 45, 43, 41, 45, 51)
n     <- length(y)
max_p <- 6        # largest order to try
h     <- 6        # forecast horizon

# ---- 2. ADF unit-root test (constant, lag 0) ---------------
dy   <- diff(y)
ylag <- y[-n]
adf  <- lm(dy ~ ylag)
tau  <- coef(summary(adf))["ylag", "t value"]
# MacKinnon (1994, 2010) p-value and 5% critical value, constant only
mackinnon_p <- function(t) {
  if (t > 2.74) return(1); if (t < -18.83) return(0)
  b <- if (t <= -1.61) c(2.1659, 1.4412, 0.038269) else c(1.7339, 0.93202, -0.12745, -0.010368)
  pnorm(sum(b * t^(seq_along(b) - 1)))
}
nobs   <- length(dy)
crit5  <- -2.86154 - 2.8903 / nobs - 4.234 / nobs^2 - 40.04 / nobs^3
adf_p  <- mackinnon_p(tau)

# ---- 3. Choose the order p by AIC and BIC (same sample) -----
E   <- embed(y, max_p + 1)            # column 1 = y_t, column k+1 = y_(t-k)
ics <- t(sapply(0:max_p, function(p) {
  f <- if (p == 0) lm(E[, 1] ~ 1) else lm(E[, 1] ~ E[, 2:(p + 1), drop = FALSE])
  c(p = p, AIC = AIC(f), BIC = BIC(f))
}))
p <- ics[which.min(ics[, "AIC"]), "p"]

# ---- 4. Fit AR(p) by conditional least squares --------------
Ep  <- embed(y, p + 1)
fit <- lm(Ep[, 1] ~ Ep[, 2:(p + 1), drop = FALSE])
co  <- coef(fit); se <- coef(summary(fit))[, 2]; pv <- coef(summary(fit))[, 4]
phi <- co[-1]; c0 <- co[1]
s2  <- summary(fit)$sigma^2           # residual variance, SSR / (n - p - 1)
mu  <- c0 / (1 - sum(phi))            # long-run mean of the process
roots <- Mod(polyroot(c(1, -phi)))    # stationary if every root > 1

# ---- 5. Residual checks -------------------------------------
res <- resid(fit)
m   <- max(p + 1, min(10, floor(length(res) / 5)))
lb  <- Box.test(res, lag = m, type = "Ljung-Box", fitdf = p)

# ---- 6. Forecast h steps ahead ------------------------------
path <- y; fc <- numeric(h)
for (k in 1:h) {
  fc[k] <- c0 + sum(phi * rev(tail(path, p)))
  path  <- c(path, fc[k])
}
psi <- c(1, ARMAtoMA(ar = phi, lag.max = h - 1))
fse <- sqrt(s2 * cumsum(psi^2))
lo  <- fc - qnorm(0.975) * fse; hi <- fc + qnorm(0.975) * fse

# ---- 7. Print the summary -----------------------------------
cat(sprintf("n = %d, mean = %.4f, SD = %.4f\n", n, mean(y), sd(y)))
cat(sprintf("ADF tau = %.4f, p = %.4f (5%% critical value %.4f)\n", tau, adf_p, crit5))
print(round(ics, 4))
cat(sprintf("Chosen order by AIC: p = %d\n", p))
for (j in seq_along(co)) cat(sprintf("%-10s %9.4f  SE %.4f  p %.5f\n",
  c("intercept", paste0("phi", seq_along(phi)))[j], co[j], se[j], pv[j]))
cat(sprintf("sigma^2 = %.4f, R^2 = %.4f, mu = %.4f\n", s2, summary(fit)$r.squared, mu))
cat(sprintf("Smallest root modulus = %.4f\n", min(roots)))
cat(sprintf("Ljung-Box Q(%d) = %.4f, df = %d, p = %.4f\n", m, lb$statistic, lb$parameter, lb$p.value))
cat(sprintf("Forecast t+1 = %.4f  [%.4f, %.4f]\n", fc[1], lo[1], hi[1]))
verdict <- if (adf_p < 0.05 && min(roots) > 1 && lb$p.value > 0.05) {
  sprintf("The series is stationary, AR(%d) fits, and the residuals look like white noise. phi1 = %.3f, so about %.0f%% of a shock carries into the next step.", p, phi[1], 100 * phi[1])
} else "Check the warnings: the series may be non-stationary or the residuals still autocorrelated."
cat("Verdict:", verdict, "\n")

# ---- 8. One publication-ready figure (300 dpi) --------------
png("ar_model_plot.png", width = 2400, height = 1800, res = 300)
par(mfrow = c(2, 2), mar = c(4.2, 4.2, 3.6, 1), oma = c(0, 0, 0.6, 0))
plot(y, type = "o", pch = 16, cex = 0.6, xlim = c(1, n + h), ylim = range(y, lo, hi),
     xlab = "Time", ylab = "Value", main = "Observed, fitted and forecast")
lines((p + 1):n, fitted(fit), col = "#2563eb", lwd = 2, lty = 2)
polygon(c(n + 1:h, rev(n + 1:h)), c(lo, rev(hi)), col = "#bbf7d055", border = NA)
lines(n + 1:h, fc, col = "#16a34a", lwd = 2)
pacf(y, main = "PACF of the series")
plot(ics[, "p"], ics[, "AIC"], type = "b", pch = 16, col = "#9333ea", xlab = "Order p",
     ylab = "Information criterion", ylim = range(ics[, 2:3]), main = "AIC and BIC by order")
lines(ics[, "p"], ics[, "BIC"], type = "b", pch = 17, col = "#ea580c")
legend("topright", c("AIC", "BIC"), col = c("#9333ea", "#ea580c"), pch = c(16, 17), bty = "n")
acf(res, main = "Residual ACF")
dev.off()

Output for the bird counts: ADF τ = −3.0840, p = 0.0278; AIC lowest at p = 1 (163.3808); φ₁ = 0.5532, SE 0.1449, p = 0.00056; σ² = 16.3950; Ljung-Box Q(7) = 6.6340, df = 6, p = 0.3560; forecast 50.9842 [43.0481, 58.9202].

10.2 What each part does

Line or functionWhat it does and why
diff(y), lm(dy ~ ylag)The ADF regression with a constant and no lagged differences. Add embed(dy, k + 1) columns if your series needs lags
mackinnon_p()MacKinnon’s response-surface p-value for the constant-only test, the same coefficients statsmodels uses
embed(y, max_p + 1)Builds yₜ and its lags in one matrix with the same rows for every order, which makes the AIC values comparable
AIC(f), BIC(f)Count p + 2 parameters including σ², matching this calculator
lm(Ep[, 1] ~ Ep[, 2:(p + 1)])Conditional least squares fit. Use arima() instead for exact maximum likelihood; the numbers differ slightly
polyroot(c(1, -phi))Roots of the characteristic polynomial. All moduli above 1 means stationary
Box.test(..., fitdf = p)Ljung-Box with p degrees of freedom removed. Forgetting fitdf is the most common R mistake here
ARMAtoMA()Impulse-response weights ψ, used for the forecast standard errors
png(..., res = 300)Saves one 2 × 2 figure at journal resolution

10.3 What the figure shows

The top-left panel is the observed series with the fitted line and a six-month forecast band that quickly widens and then flattens, the signature of a stationary AR(1). The top-right PACF has one spike at lag 1 outside the dashed bands, which is the AR(1) fingerprint. The bottom-left panel shows AIC and BIC both dropping sharply at p = 1 and rising after it. The bottom-right residual ACF has every bar inside the bands, so no memory is left.

10.4 Common R problems and fixes

ProblemCauseFix
Intercept from arima() is 51.06, not 22.77arima reports the mean μ and calls it interceptMultiply by (1 − Σφ) to get c
ar(y) picks a different orderar() ranks orders by its own variance-based AIC; with method = "ols" it picks p = 5 hereUse the common-sample AIC and BIC table built with embed() in the script
adf.test() gives τ = −1.24, not −3.08tseries adds a trend term and 3 lags, which costs a lot of power in 36 pointsUse the constant-only test for a series with no trend, and state the specification you used
Ljung-Box p differs from this pagefitdf missing or a different lagBox.test(res, lag = 7, type = "Ljung-Box", fitdf = 1)
Error: non-stationary AR partarima with a unit-root seriesUse order = c(p, 1, 0)
NA in the resultsMissing values in yFill gaps; do not just delete them
embed rows look reversedembed puts yₜ in column 1 and older lags to the rightThat is correct; column k + 1 is lag k

10.5 Useful one-liners

TaskCode
Exact ML AR(1)arima(y, order = c(1, 0, 0), method = "ML")
Automatic orderar(y, method = "ols", order.max = 6, aic = TRUE)
Yule-Walker AR(2)ar.yw(y, order.max = 2, aic = FALSE)
Forecast with arimapredict(arima(y, c(1, 0, 0)), n.ahead = 6)
ADF with trend (urca)urca::ur.df(y, type = "trend", selectlags = "AIC")
Fit every column of a data framelapply(df, function(s) arima(na.omit(s), c(1, 0, 0)))

📈 11. How to Fit an AR Model in Python

Python’s statsmodels has everything an AR analysis needs: adfuller for the stationarity test, pacf for the order, OLS for the fit and acorr_ljungbox for the residuals. The script reproduces this calculator’s numbers exactly, prints a plain-English verdict and saves one 300 dpi figure.

Copy the whole block. It runs top to bottom in a terminal, VS Code or Jupyter. Change only the y = np.array([...]) line to use your own data, oldest value first.
numpy: arrays and the lag matrixstatsmodels: OLS, adfuller, pacf, acf, Ljung-Boxscipy: the normal quantile for intervalsmatplotlib: the figure

Install once with pip install numpy scipy statsmodels matplotlib.

11.1 The complete script

Python 3, saves ar_model_plot.png

# ============================================================
# AR model in Python: ADF test, PACF, AIC/BIC order choice,
# AR(p) fit, residual checks and a forecast, with one figure
# StatsUnlock - https://statsunlock.com/ar-model-calculator/
# pip install numpy scipy statsmodels matplotlib
# ============================================================
import numpy as np
import statsmodels.api as sm
from scipy import stats
from statsmodels.tsa.stattools import adfuller, pacf, acf
from statsmodels.stats.diagnostic import acorr_ljungbox
import matplotlib.pyplot as plt

np.random.seed(42)  # nothing random below, kept for reproducibility

# ---- 1. Your data (one value per time step, oldest first) ----
# Or read a CSV:
#   import pandas as pd
#   y = pd.read_csv("data.csv")["count"].dropna().to_numpy(dtype=float)
y = np.array([52, 48, 55, 61, 47, 49, 55, 58, 54, 52, 50, 53,
              52, 55, 47, 55, 54, 56, 54, 52, 54, 56, 54, 53,
              55, 51, 46, 50, 48, 43, 43, 45, 43, 41, 45, 51], dtype=float)
y = y[~np.isnan(y)]
n, max_p, h = len(y), 6, 6

# ---- 2. ADF unit-root test (constant, lag chosen by AIC) ----
import warnings
with warnings.catch_warnings():
    warnings.simplefilter("ignore", FutureWarning)   # newer statsmodels return-type notice
    a = adfuller(y, regression="c", autolag="AIC")
adf_stat, adf_p, adf_lag, crit = a[0], a[1], a[2], a[4]

# ---- 3. Lagged design and order choice on a common sample ----
def lag_design(series, p, start):
    cols = [np.ones(len(series) - start)]
    cols += [series[start - k:len(series) - k] for k in range(1, p + 1)]
    return np.column_stack(cols), series[start:]

rows = []
for p in range(max_p + 1):
    X, target = lag_design(y, p, max_p)
    f = sm.OLS(target, X).fit()
    k = p + 2                       # coefficients + error variance, as R's AIC()
    rows.append((p, -2 * f.llf + 2 * k, -2 * f.llf + np.log(f.nobs) * k))
ics = np.array(rows)
p = int(ics[np.argmin(ics[:, 1]), 0])

# ---- 4. Fit AR(p) by conditional least squares ---------------
X, target = lag_design(y, p, p)
fit = sm.OLS(target, X).fit()
c0, phi = fit.params[0], fit.params[1:]
s2 = fit.scale                      # SSR / (n - p - 1)
mu = c0 / (1 - phi.sum())
roots = np.abs(np.roots(np.r_[1, -phi]))   # inverse roots, need all < 1

# ---- 5. Residual checks --------------------------------------
res = fit.resid
m = max(p + 1, min(10, len(res) // 5))
lb = acorr_ljungbox(res, lags=[m], model_df=p)

# ---- 6. Forecast h steps ahead -------------------------------
path = list(y); fc = []
for _ in range(h):
    nxt = c0 + sum(phi[i] * path[-1 - i] for i in range(p))
    fc.append(nxt); path.append(nxt)
fc = np.array(fc)
psi = [1.0]
for j in range(1, h):
    psi.append(sum(phi[i - 1] * psi[j - i] for i in range(1, min(p, j) + 1)))
fse = np.sqrt(s2 * np.cumsum(np.square(psi)))
z = stats.norm.ppf(0.975)
lo, hi = fc - z * fse, fc + z * fse

# ---- 7. Print the summary ------------------------------------
print(f"n = {n}, mean = {y.mean():.4f}, SD = {y.std(ddof=1):.4f}")
print(f"ADF tau = {adf_stat:.4f}, p = {adf_p:.4f}, lag = {adf_lag}, 5% critical = {crit['5%']:.4f}")
for row in ics:
    print(f"p = {int(row[0])}  AIC = {row[1]:.4f}  BIC = {row[2]:.4f}")
print(f"Chosen order by AIC: p = {p}")
names = ["intercept"] + [f"phi{i}" for i in range(1, p + 1)]
for nm, b, se, pv in zip(names, fit.params, fit.bse, fit.pvalues):
    print(f"{nm:10s} {b:9.4f}  SE {se:.4f}  p {pv:.5f}")
print(f"sigma^2 = {s2:.4f}, R^2 = {fit.rsquared:.4f}, mu = {mu:.4f}")
print(f"Largest inverse root = {roots.max():.4f} (stationary if below 1)")
print(f"Ljung-Box Q({m}) = {lb['lb_stat'].iloc[0]:.4f}, df = {m - p}, p = {lb['lb_pvalue'].iloc[0]:.4f}")
print(f"Forecast t+1 = {fc[0]:.4f}  [{lo[0]:.4f}, {hi[0]:.4f}]")
if adf_p < 0.05 and roots.max() < 1 and lb["lb_pvalue"].iloc[0] > 0.05:
    print(f"Verdict: the series is stationary, AR({p}) fits and the residuals look like white noise. "
          f"phi1 = {phi[0]:.3f}, so about {100 * phi[0]:.0f}% of a shock carries into the next step.")
else:
    print("Verdict: check the warnings, the series may be non-stationary or the residuals autocorrelated.")

# ---- 8. One publication-ready figure (300 dpi) ---------------
L = min(int(10 * np.log10(n)), n - 1)
fig, ax = plt.subplots(2, 2, figsize=(10, 7.5))
t = np.arange(1, n + 1); tf = np.arange(n + 1, n + h + 1)
ax[0, 0].plot(t, y, "o-", color="black", ms=3, lw=1, label="Observed")
ax[0, 0].plot(t[p:], fit.fittedvalues, "--", color="#2563eb", lw=2, label="Fitted")
ax[0, 0].fill_between(tf, lo, hi, color="#bbf7d0", alpha=.6)
ax[0, 0].plot(tf, fc, color="#16a34a", lw=2, label="Forecast")
ax[0, 0].set_title("Observed, fitted and forecast"); ax[0, 0].legend(frameon=False, fontsize=8)
band = 1.96 / np.sqrt(n)
ax[0, 1].bar(range(1, L + 1), pacf(y, nlags=L, method="ldb")[1:], color="#2563eb")
ax[0, 1].axhline(band, ls="--", color="#ea580c"); ax[0, 1].axhline(-band, ls="--", color="#ea580c")
ax[0, 1].set_title("PACF of the series"); ax[0, 1].set_xlabel("Lag")
ax[1, 0].plot(ics[:, 0], ics[:, 1], "o-", color="#9333ea", label="AIC")
ax[1, 0].plot(ics[:, 0], ics[:, 2], "^-", color="#ea580c", label="BIC")
ax[1, 0].set_title("AIC and BIC by order"); ax[1, 0].set_xlabel("Order p"); ax[1, 0].legend(frameon=False)
rb = 1.96 / np.sqrt(len(res)); Lr = min(L, len(res) - 1)
ax[1, 1].bar(range(1, Lr + 1), acf(res, nlags=Lr)[1:], color="#0d9488")
ax[1, 1].axhline(rb, ls="--", color="#ea580c"); ax[1, 1].axhline(-rb, ls="--", color="#ea580c")
ax[1, 1].set_title("Residual ACF"); ax[1, 1].set_xlabel("Lag")
fig.tight_layout()
fig.savefig("ar_model_plot.png", dpi=300, bbox_inches="tight")

Output for the bird counts matches R to four decimals: τ = −3.0840, p = 0.0278, lag 0; φ₁ = 0.5532 (SE 0.1449, p = 0.00056); σ² = 16.3950; Ljung-Box p = 0.3560; forecast 50.9842.

11.2 What each part does

Line or functionWhat it does and why
adfuller(y, regression="c", autolag="AIC")ADF with a constant and the lag chosen by AIC up to ⌈12(n/100)¼⌉. Returns τ, p, lags and critical values
lag_design(series, p, start)Builds the intercept and lag columns starting at row start, so every order uses the same rows
-2 * f.llf + 2 * k with k = p + 2AIC counted the same way as R and this page. statsmodels’ own f.aic uses p + 1 and is 2 lower
sm.OLS(target, X).fit()Conditional least squares. AutoReg gives the same φ but slightly smaller SEs because it divides by nₑ
np.roots(np.r_[1, -phi])Inverse roots. All below 1 means stationary
acorr_ljungbox(res, lags=[m], model_df=p)Ljung-Box with p df removed. Without model_df the p-value is too high
pacf(y, method="ldb")Durbin-Levinson on the standard ACF, the same as R’s pacf(). The default "ywadjusted" differs slightly
fig.savefig(..., dpi=300)Saves the 2 × 2 figure at journal resolution

11.3 What the figure shows

The same four panels as the R figure: the series with fitted values and the forecast band, the PACF with one significant spike at lag 1, AIC and BIC both lowest at p = 1, and a residual ACF with no bars outside the bands. If you change the data and a residual bar crosses the band at lag 12 in monthly data, you are looking at seasonality, not AR memory.

11.4 Common Python problems and fixes

ProblemCauseFix
SEs smaller than RUsing AutoReg, which divides SSR by nₑUse sm.OLS on the lag matrix
AIC is 2 lower than Rstatsmodels counts p + 1 parametersCompute -2*llf + 2*(p+2); the ranking is unchanged
PACF differs in the third decimalDefault method "ywadjusted"Pass method="ldb"
FutureWarning from adfullerReturn type is changing in newer statsmodelsIndex the result as shown, or pass result_object=True
LinAlgError: Singular matrixConstant series or too few rows for the orderLower max_p; you need n well above 3p
nan everywhereA missing value in yy = y[~np.isnan(y)], but fill gaps if they break the time spacing
Forecast does not match ARIMAARIMA uses exact likelihoodBoth are valid; state which you used

11.5 Useful one-liners

TaskCode
Quick AR fitAutoReg(y, lags=1, trend="c").fit().summary()
Automatic orderar_select_order(y, maxlag=6, ic="bic").ar_lags
Exact ML AR(1)ARIMA(y, order=(1, 0, 0)).fit().params
Yule-Walkersm.regression.yule_walker(y, order=2, method="mle")
KPSS test as a cross-checksm.tsa.kpss(y, regression="c")
Fit every column{c: AutoReg(df[c].dropna(), 1).fit().params for c in df}
R and Python agree exactly. Both scripts on this page use conditional least squares, count p + 2 parameters in AIC, run the constant-only ADF test and remove p degrees of freedom from Ljung-Box. On the bird counts they print identical numbers to four decimals, and so does this calculator. Run in a terminal with python ar_model.py; in Jupyter, add plt.show() after savefig.

📋 12. Reference Tables

12.1 Identify the model from the ACF and PACF

ModelACFPACF
AR(p)Decays gradually, smoothly or as a damped waveCuts off after lag p
MA(q)Cuts off after lag qDecays gradually
ARMA(p, q)Decays after lag qDecays after lag p
White noiseAll lags inside the bandsAll lags inside the bands
Random walk / unit rootVery slow linear decay from near 1One spike near 1 at lag 1
Seasonal ARPeaks at the season, 12, 24, …Spike at lag 12 in monthly data

What to conclude: a PACF that cuts off is the AR fingerprint. If both functions decay, consider ARMA. Source: Box and Jenkins identification rules, as summarised by Durbin (1960).

12.2 ADF critical values, constant only (MacKinnon)

Observations in the regression1%5%10%
25−3.724−2.986−2.633
30−3.670−2.964−2.621
50−3.568−2.921−2.599
100−3.498−2.891−2.582
250−3.457−2.873−2.573
500−3.443−2.867−2.570
Infinite−3.430−2.862−2.567

What to conclude: reject the unit root when τ is more negative than the value in the row nearest your sample. These are far below the familiar −1.96, which is why an ordinary t table must never be used. Source: MacKinnon (1994) response surfaces, as used by statsmodels.

12.3 Significance bands for the ACF and PACF

Series length n20303650100200500
±1.96 ÷ √n0.4380.3580.3270.2770.1960.1390.088

What to conclude: in a short series only large autocorrelations can be detected. With 30 values, a true PACF of 0.3 usually falls inside the bands and is missed.

12.4 Persistence, half-life and memory for AR(1)

φ₁Half-life (steps)Share of a shock left after 5 stepsPlain reading
0.10.300.000Practically white noise
0.30.580.002Weak, short memory
0.51.000.031Moderate memory
0.71.940.168Clear persistence
0.83.110.328Strong persistence
0.96.580.590Long memory, ADF often weak
0.9513.510.774Near unit root
0.9968.970.951Indistinguishable from a random walk in short data

What to conclude: half-life = ln 0.5 ÷ ln φ₁. Above φ₁ = 0.9 the series behaves like a random walk over any realistic study length.

12.5 Ljung-Box critical values, χ² at α = 0.05

df = m − p12345678910
Critical Q3.8415.9917.8159.48811.07012.59214.06715.50716.91918.307

What to conclude: a Q above the critical value means residual autocorrelation remains. The bird-count Q of 6.634 on 6 df is well below 12.592. Source: Ljung and Box (1978).

12.6 Sample size guide

GoalMinimum nComfortable nWhy
AR(1) coefficient2050SE of φ₁ is about √[(1 − φ²) ÷ n]
AR(2) or AR(3)3080Each lag removes a row and adds a parameter
Reliable order choice50100AIC and BIC are unstable in short series
ADF test with useful power50100 or moreLow power: near unit roots are rarely rejected below 50
Seasonal AR in monthly data48120At least four full seasons

What to conclude: below about 30 values, treat the order and the ADF verdict as provisional. Source: Schwert (1989) on unit-root test power; Hurvich and Tsai (1989) on small-sample order selection.

12.7 Comparing models with AIC differences

ΔAIC from the best modelSupport for the other model
0 to 2Substantial, practically as good
4 to 7Considerably less
Above 10Essentially none

What to conclude: for the bird counts AR(2) is 1.94 AIC units worse than AR(1), so it is not clearly worse, but it adds a non-significant coefficient. Keep the simpler model. Source: Burnham and Anderson (2004).

📈 13. Example Results

Eight worked AR model examples, each from one of the built-in sample datasets, so you can load the same data above and reproduce every number.

1
TEXTBOOK CASE

Monthly waterbird counts at a wetland

A clean AR(1): stationary, one PACF spike, white-noise residuals.

Volunteers counted waterbirds on the same transect every month for three years, 36 counts. Does this month’s count help predict next month’s?

n = 36AR(1)φ₁ = 0.553ADF p = 0.028LB p = 0.356
StatisticValueNote
ADF τ (lag 0)−3.084p = 0.028, stationary at 5%
AIC / BIC order1 / 1PACF lag 1 = 0.553
c22.773SE 7.425
φ₁0.553SE 0.145, t(33) = 3.82, p < .001
Long-run mean μ50.96Half-life 1.17 months
R²0.306σ² = 16.395
Ljung-Box Q(7)6.634df 6, p = 0.356
3945515763159131721252933mean 51.0
The counts wander around about 51 birds. Highs follow highs and lows follow lows, and each run lasts a month or two before the series returns to its mean.

What it means: about 55% of a month’s deviation from the mean carries into the next month. The memory is real but short: a disturbance halves in just over a month. AR(1) is enough because no autocorrelation is left in the residuals.

How to write it: “Bird counts were stationary (ADF τ = −3.08, p = .028) and followed an AR(1) process, φ₁ = 0.55, SE = 0.14, t(33) = 3.82, p < .001; residuals were white noise, Q(6) = 6.63, p = .356.”

2
CLEARLY SIGNIFICANT

Textbook AR(2) with a pseudo-cycle

Two strong coefficients of opposite sign and complex roots.

Sixty values simulated from φ₁ = 0.75 and φ₂ = −0.5, the kind of process Yule used for sunspots. Can the calculator recover it?

n = 60AR(2)φ₁ = 0.806φ₂ = −0.506cycle 6.5
StatisticValueNote
ADF τ (lag 1)−6.496p < .001
φ₁0.806SE 0.114, p < .001
φ₂−0.506SE 0.113, p < .001
Inverse roots0.403 ± 0.587iModulus 0.712, complex
R²0.478σ² = 21.70
Ljung-Box p0.608White noise
35455464731815222936435057mean 50.9
Peaks and troughs alternate roughly every six or seven steps. Complex roots in an AR(2) produce exactly this damped wave.

What it means: both true coefficients sit inside their 95% confidence intervals (0.577 to 1.035 and −0.733 to −0.280). The negative φ₂ is what creates the cycle: a high value pushes the next one up but the one after that down. The implied period, 2π ÷ arccos(φ₁ ÷ 2√−φ₂), is 6.5 steps.

How to write it: “An AR(2) model was selected by AIC and BIC, φ₁ = 0.81, SE = 0.11, p < .001, and φ₂ = −0.51, SE = 0.11, p < .001, implying a damped cycle of about 6.5 periods.”

3
BORDERLINE

Quarterly unemployment rate

A strong coefficient, but the ADF test cannot reject a unit root.

Ten years of quarterly unemployment, 40 values between 4.5% and 6.0%. Is unemployment mean-reverting?

n = 40AR(1)φ₁ = 0.750ADF p = 0.164borderline
StatisticValueNote
ADF τ (lag 0)−2.324p = 0.164, 5% critical −2.939
φ₁0.750SE 0.108, 95% CI 0.532 to 0.968
Half-life2.41 quartersIf stationary
Long-run mean5.32%Sample mean 5.34%
Ljung-Box p0.508White noise
4.384.815.255.696.1216111621263136mean 5.32
Long slow swings above and below about 5.3%. With only 40 quarters the ADF test cannot tell this apart from a random walk.

What it means: φ₁ is clearly significant, but significance against zero is not the issue. The question is whether φ₁ is below 1, and the ADF test says the data cannot show that. The confidence interval reaches 0.968, close to 1. This is the classic low-power situation; more data, a KPSS cross-check, or a differenced model are the honest responses.

How to write it: “Unemployment was highly persistent, φ₁ = 0.75, 95% CI [0.53, 0.97], but the ADF test did not reject a unit root (τ = −2.32, p = .164), so mean reversion could not be established.”

4
NULL RESULT

Athlete resting heart rate

No usable memory: AIC and BIC both choose order zero.

An athlete recorded resting heart rate every morning for 42 days. Does yesterday’s reading predict today’s?

n = 42AIC p = 0φ₁ = 0.146p = 0.358white noise
StatisticValueNote
AIC / BIC order0 / 0No lags preferred
φ₁ (AR(1) shown)0.146SE 0.157, p = 0.358
95% CI for φ₁−0.172 to 0.464Includes 0
R²0.022Almost nothing explained
Mean (SD)57.8 (2.6) bpmThe honest summary
51545760631611162126313641mean 57.8
Day-to-day readings jump around 58 bpm with no runs of highs or lows, the look of white noise.

What it means: past readings carry no reliable information about the next one. The best forecast is simply the mean, 57.8 bpm. A null AR result is a real finding: it says each day’s reading is an independent draw around a stable baseline, which also means ordinary statistics (t-tests, means with SE) are safe for this series.

How to write it: “Resting heart rate showed no autocorrelation; AIC and BIC selected AR(0), and the lag-1 coefficient was not significant, φ₁ = 0.15, SE = 0.16, p = .358.”

5
SMALL SAMPLE

Weekly class quiz average

Significant, but only 30 weeks, so the interval is wide.

A teacher recorded the class average on a weekly quiz for 30 weeks. Do good weeks follow good weeks?

n = 30AR(1)φ₁ = 0.442p = 0.020CI 0.08 to 0.81
StatisticValueNote
ADF τ (lag 0)−3.129p = 0.025
φ₁0.442SE 0.178, t(27) = 2.48
95% CI0.076 to 0.808Weak to strong memory
Half-life0.85 weeksVery uncertain
PACF band±0.358Only large spikes detectable
596571778314710131619222528mean 70.9
A dip in the middle weeks, then recovery. Thirty points show some persistence but cannot pin down how much.

What it means: the p-value is below 0.05, but the confidence interval runs from almost no memory to strong memory. With 30 values the order choice is fragile and the ADF test has little power. Report the interval prominently and collect more weeks before drawing conclusions about teaching effects.

How to write it: “Quiz averages showed modest persistence, φ₁ = 0.44, 95% CI [0.08, 0.81], p = .020, n = 30; the short series limits precision.”

6
SIGNIFICANT BUT TRIVIAL

Weekly hospital admissions

p = 0.018, yet the model explains only 11% and barely beats the mean.

A district hospital wants to forecast next week’s admissions from 52 weeks of data.

n = 52AIC: 1, BIC: 0φ₁ = 0.326R² = 0.110small gain
StatisticValueNote
ADF τ−5.069p < .001
φ₁0.326SE 0.133, p = 0.018
R²0.11011% explained
σ vs SD8.94 vs 9.45Uncertainty cut by 5%
Next-week forecast117.295% PI 99.7 to 134.7
941061181301421713192531374349mean 115.3
Admissions scatter widely around 116 a week. The faint persistence is real but small compared with week-to-week noise.

What it means: the coefficient is statistically significant, but BIC prefers no AR term at all, and the forecast interval is almost as wide as the raw spread of the data. For staffing decisions, the mean plus seasonal and calendar effects will matter far more than last week’s count.

How to write it: “Admissions showed weak autocorrelation, φ₁ = 0.33, p = .018, R² = .11; BIC favoured a constant-mean model, so the practical forecasting gain was small.”

7
ASSUMPTION FAILURE

Share price random walk

φ₁ = 0.974 and R² = 0.976 look impressive, and are meaningless.

Fifty daily closing prices of a share. An analyst fits AR(1) and reports a near-perfect fit.

n = 50φ₁ = 0.974ADF p = 0.691unit rootdifference it
StatisticValueNote
ADF τ on prices−1.159p = 0.691, unit root not rejected
φ₁ on prices0.974SE 0.022, half-life 26 days
R² on prices0.976Spurious: the level just tracks itself
ADF τ on daily changes−6.764p < .001, changes are stationary
φ₁ on changes−0.067p = 0.672, order 0 chosen
687786941031713192531374349
The price drifts from 100 down to about 72 with no level to return to. Its daily changes, not the price, are what an AR model can describe.

What it means: a high R² on a non-stationary level is a warning, not a result. The ADF test fails, so the t-test on φ₁ is invalid. After first differencing, the changes are stationary and show no memory at all, which is the definition of a random walk: tomorrow’s best forecast is today’s price.

How to write it: “Prices contained a unit root (ADF τ = −1.16, p = .691). Daily changes were stationary (τ = −6.76, p < .001) and showed no autocorrelation, consistent with a random walk.”

8
APPLIED FIELD

Tree-ring width at two forest sites

Two clusters, two AR(1) models, different memory.

Ring-width index chronologies of 50 years from a north-slope plot and a valley-floor plot. Does growth carry over between years, and does it differ by site?

n = 50 eachSite A φ₁ = 0.514Site B φ₁ = 0.341both stationaryAR(1)
StatisticSite A, north slopeSite B, valley floor
ADF τ−3.879, p = 0.002−4.813, p < .001
φ₁ (SE)0.514 (0.125)0.341 (0.137)
p for φ₁< .0010.016
Half-life1.04 years0.64 years
Long-run index0.9451.107
0.650.861.071.291.501713192531374349Site A, north slopeSite B, valley floor
Both chronologies fluctuate around a stable index. Site A has longer runs of narrow or wide rings.

What it means: on the north slope, about half of one year’s growth anomaly carries into the next, a typical carry-over effect from stored reserves. The valley site recovers faster. Dendrochronologists remove this AR(1) memory, a step called prewhitening, before correlating rings with climate, because otherwise the carry-over inflates the correlation.

How to write it: “Both chronologies were stationary and followed AR(1) processes; first-order autocorrelation was stronger at the north-slope site (φ₁ = 0.51, SE = 0.13) than at the valley site (φ₁ = 0.34, SE = 0.14).”

🧪 14. Data Collection Protocol

Study design: an AR model assumes one variable measured repeatedly on the same unit at equally spaced times, with the same method every time, long enough to see the memory you want to estimate.

  1. Fix the time step before you start the AR model study. Monthly, weekly or daily: choose the step that matches the process. Memory measured in months says nothing about memory in days.
  2. Keep the spacing equal. A missing survey shifts every later lag. Plan replacement visits so no step is skipped.
  3. Hold the method constant. Same transect, same observer effort, same instrument, same time of day. A change in method creates a step change that the AR model misreads as persistence.
  4. Record the date with every value and keep the data in time order, oldest first, ready to paste into the AR model calculator.
  5. Plan the length. Aim for 50 or more time points for a reliable order choice and ADF test, and at least four full cycles if seasonality is likely.
  6. Decide how gaps will be handled before you see the data: interpolation for one missing step, a state-space model for many. Never delete a missing step silently.
  7. Note known interventions such as floods, policy changes or equipment changes. They belong in the model as events, not in the noise.
  8. Log covariates such as rainfall or temperature in parallel columns, so an ARIMAX or distributed-lag model is possible later.
  9. Check units and transformations. Counts with a wide range often behave better on a log scale; decide this in the protocol, not after fitting.
  10. Pre-register the AR model settings: maximum order, AIC or BIC, ADF specification and the differencing rule.
MonthSite A countSite B count
2023-015261
2023-024858
2023-035563

One row per time step, one column per series, oldest at the top. Upload this layout and click the count columns: each becomes its own cluster. The date column is for your records; the calculator only needs the order.

Minimum sample: 30 time points for an AR(1) estimate, 50 for a dependable order choice and ADF test, and 100 for AR(3) or higher.

Pre-registration: state the maximum order, the selection criterion, the ADF lag rule and α, and what you will do if the unit root is not rejected. Choosing the specification after seeing which one gives a significant coefficient inflates false positives.

Common collection mistakes:

  • Irregular spacing, such as surveys whenever the weather allowed.
  • Changing survey effort or observers part way through.
  • Pasting data newest first from a report table.
  • Aggregating to a coarser step (monthly to yearly) and losing most of the points.
  • Recording missing visits as zero, which creates false crashes in the series.

🎯 15. When to Use This AR Model Calculator

This free AR model calculator is designed for one equally spaced series at a time, where the question is how strongly the past predicts the present.

Use an AR model when:

  • ✓ The series is stationary, or becomes stationary after one difference.
  • ✓ The PACF cuts off after a few lags.
  • ✓ You want to measure persistence, density dependence or carry-over.
  • ✓ You need a short-term forecast with a prediction interval.
  • ✓ You need to remove autocorrelation (prewhiten) before another analysis.

Use something else when:

  • ✗ The ACF cuts off and the PACF decays, which points to an MA or ARMA model.
  • ✗ There is a strong seasonal pattern, which needs SARIMA or seasonal dummies.
  • ✗ The variance changes over time, as in financial returns, which needs GARCH.
  • ✗ Several series influence each other, which needs a VAR model.
  • ✗ An outside driver explains the series, which needs ARIMAX or regression with AR errors.
  • ✗ Time points are unequally spaced, which needs a continuous-time or state-space model.

Real-world examples:

  1. Ecology: density dependence in annual population counts, where φ₁ below 1 means regulation.
  2. Hydrology: daily river temperature or flow, usually AR(1) or AR(2).
  3. Dendrochronology: prewhitening ring-width chronologies before climate correlation.
  4. Economics: persistence of unemployment or inflation.
  5. Health: serial correlation in daily symptom scores or admissions.

Decision tree: is the series equally spaced? If not, use a state-space model. Is it stationary (ADF p < 0.05)? If not, difference it. Does the PACF cut off? If yes, AR(p). If the ACF cuts off instead, MA(q). If both decay, ARMA. Is there a 12-month spike? Add a seasonal term.

🔧 16. Troubleshooting and Common Errors

“Needs at least 12 values”

Cause: the series is too short to estimate lags and test stationarity. Fix: collect more time points. Below 12 any AR estimate is mostly noise.

The ADF test says non-stationary but the plot looks flat

Cause: low power in a short or highly persistent series. Fix: fit the differenced series too, or check with a KPSS test; report both if they disagree.

φ₁ is above 1, or the largest inverse root is 1 or more

Cause: a trend or a unit root. Fix: set Differencing to First difference. Never report an explosive AR model for observed data.

Ljung-Box p is below 0.05

Cause: the order is too low, or there is seasonality or an MA component. Fix: raise p, look for a spike at the seasonal lag in chart 4, and consider ARMA or SARIMA.

AIC and BIC choose different orders

Cause: the extra lags give a small improvement. Fix: report the BIC model, show the AIC model as a sensitivity check, and look at whether the extra coefficient is significant.

The order chosen is 0

Cause: no detectable memory; the series is white noise. Fix: nothing is wrong. Report the mean and SD. The AR(1) shown is there only to display how weak the memory is.

My coefficients differ from R arima() or SPSS

Cause: they use exact maximum likelihood and report the mean as the intercept. Fix: compare φ values, which differ only slightly, and convert their intercept with c = μ(1 − Σφ). Section 9.4 lists every known difference.

The forecast is almost a flat line

Cause: a stationary AR forecast converges to the mean within a few half-lives. Fix: this is correct behaviour. For trending series use differencing or a model with a trend.

Uploaded columns do not appear

Cause: the column holds text, units or commas as thousands separators. Fix: keep numbers only, use a full stop for decimals, and save as .csv or .xlsx.

Results disappeared after I edited something

Cause: any change to the data or settings clears the results so stale numbers are never shown. Fix: press Fit AR Model again.

⚖ 17. Assumptions and Limitations

Assumptions

  1. Stationarity. Constant mean, variance and autocorrelation over time. Check with the ADF test and the inverse roots. If it fails, φ is biased toward 1 in apparent strength and the t-tests reject far too often, the classic spurious regression problem.
  2. Equal spacing and correct order. Check the dates. Gaps or reversed order make the lags meaningless and bias φ₁ toward zero.
  3. Linearity. The effect of the past is a straight-line function. Check the residual plot. Thresholds or regime switches are averaged away, so φ understates the memory in one regime and overstates it in the other.
  4. White-noise errors. Uncorrelated shocks with constant variance. Check with Ljung-Box. Leftover autocorrelation makes the standard errors too small, so p-values are too optimistic.
  5. Constant variance. Check whether the spread of residuals grows over time. Volatility clustering leaves φ unbiased but makes prediction intervals too narrow in volatile periods and too wide in calm ones.
  6. Normal errors, for intervals only. Check with Jarque-Bera. Coefficients stay consistent, but heavy tails make the 95% intervals cover less than 95%.
  7. Enough data for the order. Check that n is well above 3p. With too few points AIC over-fits and the coefficient estimates are biased toward zero, by roughly (1 + 3φ) ÷ n in an AR(1).

Limitations

  • Only autoregressive terms are fitted. Series with moving-average structure need ARMA or ARIMA software.
  • No seasonal terms. Use SARIMA or add seasonal dummies in a regression.
  • No outside predictors. Use ARIMAX or regression with AR errors.
  • Conditional least squares drops the first p observations. In very short series exact maximum likelihood, as in R arima(), is slightly more efficient.
  • The ADF test uses a constant only. For a series with a clear deterministic trend, use a trend specification in R or Python.
  • One series at a time. Clusters are fitted independently; joint dynamics need a VAR model.
  • Autocorrelation is not causation. The model describes memory, not mechanism.

🏁 18. Conclusion

Run the analysis above and this box will summarise your own result in four parts: what was found (AR(___), φ₁ = ___, ADF p = ___), what it means in practice, cautions, and next steps.

An AR model calculator answers a simple question with real consequences: how much does the past of a series tell you about its next value? The arithmetic is a regression of the series on its own lags, but the value lies in the checks around it. A coefficient means nothing until the series has passed a stationarity test, the order has been justified by the PACF and an information criterion, and the residuals have been shown to be white noise.

The worked bird counts show the full path. The ADF test rejected a unit root at the 5% level (τ = −3.08, p = 0.028). The PACF had one clear spike, and AIC and BIC both chose p = 1. The fitted AR(1), ŷₜ = 22.77 + 0.553yₜ₋₁, says that just over half of any month’s anomaly carries into the next month and that disturbances halve in about 1.2 months. The Ljung-Box test confirmed that nothing was left in the residuals, and the forecast settled to the long-run mean of 51 birds within a few months.

The examples show where the method bends and breaks. A near unit root, as in the unemployment series, defeats the ADF test in short samples. A random walk produces a spectacular but spurious R². A significant coefficient can still be practically trivial, as in the hospital data, and a null result can be the most useful finding of all, as in the heart-rate series. Each of these is caught by a specific line in the output, which is why the checks come before the coefficients.

For research, report the stationarity test, the order and how it was chosen, every coefficient with its uncertainty, the residual check and the software. For practice, translate φ into a half-life and the forecast into an interval. And remember the boundary of the method: an AR model measures memory, not the cause of it.

Paste your series into the calculator above, read the checks before the coefficients, and use the templates in Section 5 to write it up. Whenever a new time series lands on your desk, start with this AR model calculator.

❓ 19. Frequently Asked Questions

Q1. What is an AR model in time series?

An AR (autoregressive) model predicts each value of a time series from a weighted sum of its own previous p values plus random noise. AR(1) uses one past value, AR(2) uses two. The weights, called φ coefficients, measure how much memory the series has.

Q2. What does AR(1) mean?

AR(1) is an autoregressive model of order 1: yₜ = c + φ₁yₜ₋₁ + εₜ. Only the immediately previous value is used. It is stationary when φ₁ is between −1 and 1, and φ₁ equals the lag-1 autocorrelation of the process.

Q3. How do you fit an AR model step by step?

Check the series is equally spaced, run the ADF test for stationarity, difference if needed, plot the PACF to suggest p, compare AIC and BIC across orders, regress the series on its p lags, check the residuals with Ljung-Box, and forecast. Section 7 shows every step with numbers.

Q4. How do I choose the order p of an AR model?

Use the PACF, which cuts off after lag p for a true AR(p), and confirm with the order that minimises AIC or BIC on a common sample. BIC is more conservative. If they disagree, prefer the smaller model unless the extra lag is significant and improves the residual checks.

Q5. What is the difference between ACF and PACF?

The ACF is the correlation between the series and itself k steps back, including indirect effects through the lags in between. The PACF removes those indirect effects. For an AR model the ACF decays gradually while the PACF cuts off sharply after lag p.

Q6. Does an AR model require stationary data?

Yes. The coefficients, their p-values and the forecasts assume a constant mean and variance. If the ADF test cannot reject a unit root, difference the series once and fit the AR model to the changes, which is an ARIMA(p, 1, 0).

Q7. How do I interpret the ADF test p-value?

The ADF null hypothesis is a unit root (non-stationary). A p-value below 0.05 rejects it, so the series is stationary. A p-value above 0.05 means non-stationarity cannot be ruled out, though in short series this often reflects low power rather than a true unit root.

Q8. How do I interpret AR model coefficients?

A φ₁ of 0.55 means 55% of the current deviation from the mean carries into the next step. Positive values give smooth persistence, negative values a zig-zag. The sum of all φ measures overall persistence, and values near 1 mean very long memory.

Q9. Should I use AIC or BIC to select the AR order?

AIC tends to choose slightly larger models and is better for forecasting. BIC penalises extra parameters more, by ln(n) instead of 2, and tends to find the true order in large samples. Report which you used; when they agree the choice is robust.

Q10. What are the Yule-Walker equations?

They link the autocorrelations of an AR(p) process to its coefficients: ρₖ = φ₁ρₖ₋₁ + … + φₚρₖ₋ₚ for k = 1 to p. Solving them with sample autocorrelations gives the Yule-Walker estimates, which are always stationary and are R’s ar() default.

Q11. Is least squares or Yule-Walker better for AR estimation?

Conditional least squares has less bias in short or highly persistent series and matches regression output in R and Python. Yule-Walker is quick and always stationary but can be biased toward zero when roots are near 1. In long series the two agree closely.

Q12. How do I check if my AR model is adequate?

Plot the residual ACF and run the Ljung-Box test. If no bars cross the bands and the Ljung-Box p-value is above 0.05, the model has captured the memory. Also check that the highest-order coefficient is significant and every inverse root is below 1.

Q13. What is the Ljung-Box test?

It tests whether a group of autocorrelations are jointly zero. On AR residuals, Q = n(n + 2)Σrₖ² ÷ (n − k) is compared with a chi-square on m − p degrees of freedom. A p-value above 0.05 means the residuals behave like white noise.

Q14. How many observations do I need for an AR model?

At least 30 for a usable AR(1) estimate, 50 for a dependable order choice and ADF test, and 100 or more for higher orders or seasonal models. Short series give wide confidence intervals and an ADF test with little power.

Q15. How do you forecast with an AR model?

Plug the latest p values into the fitted equation to get the next value, then feed that forecast back in for later steps. Prediction intervals widen with the horizon using the impulse-response weights, and a stationary forecast converges to the long-run mean.

Q16. What is the difference between AR, MA and ARIMA models?

AR models use past values, MA models use past random shocks, and ARMA combines both. ARIMA adds differencing (the I) to handle non-stationary series. An AR(1) is the same as ARIMA(1, 0, 0), and a random walk is ARIMA(0, 1, 0).

Q17. How do I fit an AR model in Excel?

Put the series in column A, create a lag column B with =A2 in B3 filled down, then use =SLOPE(A3:A37,B3:B37) for φ₁ and =INTERCEPT(A3:A37,B3:B37) for c. LINEST gives the standard error. Section 9 shows each step with spreadsheet screenshots.

Q18. How do I fit an AR model in R?

Use lm(y[-1] ~ y[-n]) for a least-squares AR(1), or arima(y, order = c(1, 0, 0)) for exact maximum likelihood. pacf(y) shows the order and Box.test(resid, type = "Ljung-Box", fitdf = p) checks the residuals. Section 10 has a complete script.

Q19. How do I fit an AR model in Python?

With statsmodels: adfuller(y) for stationarity, pacf(y) for the order, AutoReg(y, lags=1).fit() or OLS on a lag matrix for the fit, and acorr_ljungbox for the residuals. Section 11 has a complete script that matches this calculator exactly.

Q20. How do I report AR model results in APA style?

Report the ADF statistic and p-value, the order and how it was chosen, each coefficient with SE, t and p, the residual variance, and the Ljung-Box result. For example: AR(1), φ₁ = 0.55, SE = 0.14, t(33) = 3.82, p < .001; Q(6) = 6.63, p = .356.

📑 20. Cite This Tool

APA 7th edition
StatsUnlock. (2026). AR model calculator [Interactive statistical tool]. https://statsunlock.com/ar-model-calculator/
BibTeX
@misc{statsunlock_ar_2026, title={AR Model Calculator}, author={{StatsUnlock}}, year={2026}, note={Interactive statistical tool}, url={https://statsunlock.com/ar-model-calculator/}}
Methods wording
Temporal dependence was modelled with an autoregressive AR(p) model using the StatsUnlock AR Model Calculator (2026). Stationarity was tested with the augmented Dickey-Fuller test with a constant and lag length chosen by AIC. The order was selected by AIC among AR(0) to AR(6) fitted to a common sample, coefficients were estimated by conditional least squares, and residual autocorrelation was assessed with the Ljung-Box test.

🔗 21. Related Tools

📖 22. Glossary of Terms

TermPlain-English meaning
ACFAutocorrelation function: the correlation of a series with itself at each lag.
ADF testAugmented Dickey-Fuller test: checks whether a series has a unit root. A small p-value means stationary.
AICAkaike information criterion: model fit penalised by 2 per parameter. Lower is better.
AR(p)Autoregressive model of order p: the current value predicted from the last p values.
ARIMAAutoregressive integrated moving average: AR and MA terms fitted after differencing.
BICBayesian information criterion: like AIC but with a penalty of ln(n) per parameter, so it prefers smaller models.
DifferencingReplacing each value with its change from the previous value, to remove a trend or unit root.
Half-lifeNumber of time steps for a shock to fall to half its size.
Impulse responseHow a single shock today echoes through future values, given by the ψ weights.
Inverse rootA root of the AR polynomial turned inside out. All must be below 1 in size for a stationary model.
LagA value from k steps earlier. Lag 1 of this month is last month.
Ljung-Box testA test of whether several residual autocorrelations are jointly zero.
Long-run meanThe level a stationary AR series returns to, c ÷ (1 − Σφ).
MA modelMoving average model: the current value depends on past random shocks rather than past values.
PACFPartial autocorrelation function: the correlation at lag k after removing the effect of shorter lags.
PersistenceHow long deviations last, measured by the sum of the φ coefficients.
PrewhiteningRemoving AR memory from a series before correlating it with another series.
ResidualThe observed value minus the one-step fitted value.
Stationary seriesA series whose mean, variance and autocorrelation do not change over time.
Unit rootA sum of AR coefficients equal to 1. Shocks never fade and the series has no fixed mean.
White noiseA sequence of uncorrelated random values with zero mean and constant variance.
Yule-Walker equationsEquations linking AR coefficients to autocorrelations, used to estimate the coefficients.

📚 23. References

The following peer-reviewed references support the methods used in this AR model calculator: autoregressive estimation, unit-root testing, order selection, residual diagnostics and ecological applications.

  1. Akaike, H. (1974). A new look at the statistical model identification. IEEE Transactions on Automatic Control, 19(6), 716–723. https://doi.org/10.1109/TAC.1974.1100705
  2. Box, G. E. P., & Pierce, D. A. (1970). Distribution of residual autocorrelations in autoregressive-integrated moving average time series models. Journal of the American Statistical Association, 65(332), 1509–1526. https://doi.org/10.1080/01621459.1970.10481180
  3. Burnham, K. P., & Anderson, D. R. (2004). Multimodel inference: Understanding AIC and BIC in model selection. Sociological Methods & Research, 33(2), 261–304. https://doi.org/10.1177/0049124104268644
  4. Dennis, B., & Taper, M. L. (1994). Density dependence in time series observations of natural populations: Estimation and testing. Ecological Monographs, 64(2), 205–224. https://doi.org/10.2307/2937041
  5. Dickey, D. A., & Fuller, W. A. (1979). Distribution of the estimators for autoregressive time series with a unit root. Journal of the American Statistical Association, 74(366a), 427–431. https://doi.org/10.1080/01621459.1979.10482531
  6. Durbin, J. (1960). The fitting of time-series models. Review of the International Statistical Institute, 28(3), 233–244. https://doi.org/10.2307/1401322
  7. Hurvich, C. M., & Tsai, C.-L. (1989). Regression and time series model selection in small samples. Biometrika, 76(2), 297–307. https://doi.org/10.1093/biomet/76.2.297
  8. Hyndman, R. J., & Khandakar, Y. (2008). Automatic time series forecasting: The forecast package for R. Journal of Statistical Software, 27(3), 1–22. https://doi.org/10.18637/jss.v027.i03
  9. Ives, A. R., Dennis, B., Cottingham, K. L., & Carpenter, S. R. (2003). Estimating community stability and ecological interactions from time-series data. Ecological Monographs, 73(2), 301–330. https://doi.org/10.1890/0012-9615(2003)073[0301:ECSAEI]2.0.CO;2
  10. Jarque, C. M., & Bera, A. K. (1980). Efficient tests for normality, homoscedasticity and serial independence of regression residuals. Economics Letters, 6(3), 255–259. https://doi.org/10.1016/0165-1765(80)90024-5
  11. Kwiatkowski, D., Phillips, P. C. B., Schmidt, P., & Shin, Y. (1992). Testing the null hypothesis of stationarity against the alternative of a unit root. Journal of Econometrics, 54(1–3), 159–178. https://doi.org/10.1016/0304-4076(92)90104-Y
  12. Ljung, G. M., & Box, G. E. P. (1978). On a measure of lack of fit in time series models. Biometrika, 65(2), 297–303. https://doi.org/10.1093/biomet/65.2.297
  13. MacKinnon, J. G. (1994). Approximate asymptotic distribution functions for unit-root and cointegration tests. Journal of Business & Economic Statistics, 12(2), 167–176. https://doi.org/10.1080/07350015.1994.10510005
  14. Ng, S., & Perron, P. (2001). Lag length selection and the construction of unit root tests with good size and power. Econometrica, 69(6), 1519–1554. https://doi.org/10.1111/1468-0262.00256
  15. Said, S. E., & Dickey, D. A. (1984). Testing for unit roots in autoregressive-moving average models of unknown order. Biometrika, 71(3), 599–607. https://doi.org/10.1093/biomet/71.3.599
  16. Schwarz, G. (1978). Estimating the dimension of a model. The Annals of Statistics, 6(2), 461–464. https://doi.org/10.1214/aos/1176344136
  17. Schwert, G. W. (1989). Tests for unit roots: A Monte Carlo investigation. Journal of Business & Economic Statistics, 7(2), 147–159. https://doi.org/10.1080/07350015.1989.10509723
  18. Shibata, R. (1976). Selection of the order of an autoregressive model by Akaike’s information criterion. Biometrika, 63(1), 117–126. https://doi.org/10.1093/biomet/63.1.117
  19. Walker, G. (1931). On periodicity in series of related terms. Proceedings of the Royal Society of London, Series A, 131(818), 518–532. https://doi.org/10.1098/rspa.1931.0069
  20. Yule, G. U. (1927). On a method of investigating periodicities in disturbed series, with special reference to Wolfer’s sunspot numbers. Philosophical Transactions of the Royal Society of London, Series A, 226, 267–298. https://doi.org/10.1098/rsta.1927.0007

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Statistical Models

Important Plots & Charts

Calculators and Converters