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.
⚡ 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.
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.
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.
| Feature | AR(p) model | MA(q) model | ARIMA(p, d, q) |
|---|---|---|---|
| Predicts from | Past values of the series | Past random shocks | Both, after differencing d times |
| ACF pattern | Decays slowly or oscillates | Cuts off after lag q | Mixed |
| PACF pattern | Cuts off after lag p | Decays slowly | Mixed |
| Needs stationarity | Yes | Always stationary | No, differencing handles trends |
| Estimation | Ordinary least squares works | Needs maximum likelihood | Needs maximum likelihood |
| Best for | Smooth persistence, density dependence | Short one-off shocks | Trending or wandering series |
🧮 2. Set Up Your Data
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.
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.
📊 3. Results
🧠 4. Interpretation of Results, In Detail
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 see | What it means | What to do |
|---|---|---|
| ADF p < 0.05, Ljung-Box p > 0.05, AIC = BIC order | Clean, well-specified model | Report it with the templates in Section 5 |
| ADF p > 0.10, Σφ near 1 | Unit root likely | Set Differencing to First difference and refit |
| Ljung-Box p < 0.05 | Memory left in residuals | Raise p, check lag 12 for seasonality, or try ARMA |
| AIC and BIC disagree | Weak evidence for the extra lags | Report BIC model, show AIC model as sensitivity |
| Selected order is 0 | No usable memory, white noise | Report the mean and SD; the series is unpredictable from its past |
| φ₁ significant but R² below 0.1 | Real but small memory | Report 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.
📌 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.
📌 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.
📌 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.
📌 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.
📌 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
🔀 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.
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
- 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. - 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
=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 want | Excel function | Note |
|---|---|---|
| φ₁ 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 ToolPak | Data → Data Analysis → Regression | Enable it first: File → Options → Add-ins → Analysis ToolPak |
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.
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.
=A2Row 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)φ₁ = 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)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)τ = −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)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.
=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
| Situation | What happens | Fix |
|---|---|---|
| Data entered newest first | The lag column points forward in time; φ looks similar but forecasts are wrong | Sort 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 counts | Choose p from the common-sample AIC table, as in Section 10 |
statsmodels AutoReg | Divides SSR by nₑ, not nₑ − p − 1, and reports z-tests, so SEs are a little smaller | Use sm.OLS on the lag matrix, as in Section 11 |
| AIC values differ by 2 | statsmodels 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 data | Use the constant-only regression in Section 10, or statsmodels adfuller(regression="c") |
| CORREL instead of ACF | CORREL standardises each half separately | Use the textbook formula in card 5 of Section 6 |
| Blank or text cells | SLOPE silently drops the row, breaking the time order | Fill gaps before fitting; never leave holes in a time series |
| Tool | Fit AR(1) | ADF test | PACF |
|---|---|---|---|
| Excel | =SLOPE(A3:A37,B3:B37) | (φ − 1) ÷ SE, lag 0 only | Not built in |
| R | lm(y[-1] ~ y[-n]) | Manual lm on diff(y), Section 10 | pacf(y) |
| Python | sm.OLS(y[1:], X).fit() | adfuller(y, regression="c") | pacf(y, method="ldb") |
| SPSS | Analyze → Forecasting → Create Traditional Models → ARIMA(1,0,0), exact ML | ||
| Stata | regress y L.y, dfuller y, pac y | ||
9.5 Charting the result in Excel
- Select A1:A37 and choose Insert → Line with Markers.
- 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. - For the forecast, extend the time axis with six empty rows and add the forecast and its interval as extra series.
- Label the horizontal axis in real time units, such as months, and the vertical axis with the measured variable and units.
- 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 shows | Why | Fix |
|---|---|---|
#N/A from SLOPE | The two ranges have different lengths | Both ranges must start on row 3 and end on row 37 |
#DIV/0! | The lag column is empty or constant | Check that B3 holds =A2 and was filled down |
#VALUE! from LINEST | Text or a blank inside the range | Remove units and fill gaps |
#NUM! from LN | φ₁ is negative or zero, so the half-life formula fails | Use =LN(0.5)/LN(ABS(B2)) and note the zig-zag pattern |
| Only one number from LINEST | Entered as a normal formula in an old Excel version | Select a 5 × 2 block and press Ctrl + Shift + Enter, or use INDEX as shown |
| φ₁ above 1 | The series trends or has a unit root | Difference 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.
Rscript. Change only the y <- c(...) line to use your own data, oldest value first.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 function | What 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
| Problem | Cause | Fix |
|---|---|---|
Intercept from arima() is 51.06, not 22.77 | arima reports the mean μ and calls it intercept | Multiply by (1 − Σφ) to get c |
ar(y) picks a different order | ar() ranks orders by its own variance-based AIC; with method = "ols" it picks p = 5 here | Use the common-sample AIC and BIC table built with embed() in the script |
adf.test() gives τ = −1.24, not −3.08 | tseries adds a trend term and 3 lags, which costs a lot of power in 36 points | Use the constant-only test for a series with no trend, and state the specification you used |
| Ljung-Box p differs from this page | fitdf missing or a different lag | Box.test(res, lag = 7, type = "Ljung-Box", fitdf = 1) |
Error: non-stationary AR part | arima with a unit-root series | Use order = c(p, 1, 0) |
| NA in the results | Missing values in y | Fill gaps; do not just delete them |
embed rows look reversed | embed puts yₜ in column 1 and older lags to the right | That is correct; column k + 1 is lag k |
10.5 Useful one-liners
| Task | Code |
|---|---|
| Exact ML AR(1) | arima(y, order = c(1, 0, 0), method = "ML") |
| Automatic order | ar(y, method = "ols", order.max = 6, aic = TRUE) |
| Yule-Walker AR(2) | ar.yw(y, order.max = 2, aic = FALSE) |
| Forecast with arima | predict(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 frame | lapply(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.
y = np.array([...]) line to use your own data, oldest value first.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 function | What 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 + 2 | AIC 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
| Problem | Cause | Fix |
|---|---|---|
| SEs smaller than R | Using AutoReg, which divides SSR by nₑ | Use sm.OLS on the lag matrix |
| AIC is 2 lower than R | statsmodels counts p + 1 parameters | Compute -2*llf + 2*(p+2); the ranking is unchanged |
| PACF differs in the third decimal | Default method "ywadjusted" | Pass method="ldb" |
FutureWarning from adfuller | Return type is changing in newer statsmodels | Index the result as shown, or pass result_object=True |
LinAlgError: Singular matrix | Constant series or too few rows for the order | Lower max_p; you need n well above 3p |
nan everywhere | A missing value in y | y = y[~np.isnan(y)], but fill gaps if they break the time spacing |
| Forecast does not match ARIMA | ARIMA uses exact likelihood | Both are valid; state which you used |
11.5 Useful one-liners
| Task | Code |
|---|---|
| Quick AR fit | AutoReg(y, lags=1, trend="c").fit().summary() |
| Automatic order | ar_select_order(y, maxlag=6, ic="bic").ar_lags |
| Exact ML AR(1) | ARIMA(y, order=(1, 0, 0)).fit().params |
| Yule-Walker | sm.regression.yule_walker(y, order=2, method="mle") |
| KPSS test as a cross-check | sm.tsa.kpss(y, regression="c") |
| Fit every column | {c: AutoReg(df[c].dropna(), 1).fit().params for c in df} |
python ar_model.py; in Jupyter, add plt.show() after savefig.📋 12. Reference Tables
12.1 Identify the model from the ACF and PACF
| Model | ACF | PACF |
|---|---|---|
| AR(p) | Decays gradually, smoothly or as a damped wave | Cuts off after lag p |
| MA(q) | Cuts off after lag q | Decays gradually |
| ARMA(p, q) | Decays after lag q | Decays after lag p |
| White noise | All lags inside the bands | All lags inside the bands |
| Random walk / unit root | Very slow linear decay from near 1 | One spike near 1 at lag 1 |
| Seasonal AR | Peaks 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 regression | 1% | 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 n | 20 | 30 | 36 | 50 | 100 | 200 | 500 |
|---|---|---|---|---|---|---|---|
| ±1.96 ÷ √n | 0.438 | 0.358 | 0.327 | 0.277 | 0.196 | 0.139 | 0.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 steps | Plain reading |
|---|---|---|---|
| 0.1 | 0.30 | 0.000 | Practically white noise |
| 0.3 | 0.58 | 0.002 | Weak, short memory |
| 0.5 | 1.00 | 0.031 | Moderate memory |
| 0.7 | 1.94 | 0.168 | Clear persistence |
| 0.8 | 3.11 | 0.328 | Strong persistence |
| 0.9 | 6.58 | 0.590 | Long memory, ADF often weak |
| 0.95 | 13.51 | 0.774 | Near unit root |
| 0.99 | 68.97 | 0.951 | Indistinguishable 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 − p | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|
| Critical Q | 3.841 | 5.991 | 7.815 | 9.488 | 11.070 | 12.592 | 14.067 | 15.507 | 16.919 | 18.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
| Goal | Minimum n | Comfortable n | Why |
|---|---|---|---|
| AR(1) coefficient | 20 | 50 | SE of φ₁ is about √[(1 − φ²) ÷ n] |
| AR(2) or AR(3) | 30 | 80 | Each lag removes a row and adds a parameter |
| Reliable order choice | 50 | 100 | AIC and BIC are unstable in short series |
| ADF test with useful power | 50 | 100 or more | Low power: near unit roots are rarely rejected below 50 |
| Seasonal AR in monthly data | 48 | 120 | At 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 model | Support for the other model |
|---|---|
| 0 to 2 | Substantial, practically as good |
| 4 to 7 | Considerably less |
| Above 10 | Essentially 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.
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?
| Statistic | Value | Note |
|---|---|---|
| ADF τ (lag 0) | −3.084 | p = 0.028, stationary at 5% |
| AIC / BIC order | 1 / 1 | PACF lag 1 = 0.553 |
| c | 22.773 | SE 7.425 |
| φ₁ | 0.553 | SE 0.145, t(33) = 3.82, p < .001 |
| Long-run mean μ | 50.96 | Half-life 1.17 months |
| R² | 0.306 | σ² = 16.395 |
| Ljung-Box Q(7) | 6.634 | df 6, p = 0.356 |
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.”
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?
| Statistic | Value | Note |
|---|---|---|
| ADF τ (lag 1) | −6.496 | p < .001 |
| φ₁ | 0.806 | SE 0.114, p < .001 |
| φ₂ | −0.506 | SE 0.113, p < .001 |
| Inverse roots | 0.403 ± 0.587i | Modulus 0.712, complex |
| R² | 0.478 | σ² = 21.70 |
| Ljung-Box p | 0.608 | White noise |
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.”
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?
| Statistic | Value | Note |
|---|---|---|
| ADF τ (lag 0) | −2.324 | p = 0.164, 5% critical −2.939 |
| φ₁ | 0.750 | SE 0.108, 95% CI 0.532 to 0.968 |
| Half-life | 2.41 quarters | If stationary |
| Long-run mean | 5.32% | Sample mean 5.34% |
| Ljung-Box p | 0.508 | White noise |
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.”
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?
| Statistic | Value | Note |
|---|---|---|
| AIC / BIC order | 0 / 0 | No lags preferred |
| φ₁ (AR(1) shown) | 0.146 | SE 0.157, p = 0.358 |
| 95% CI for φ₁ | −0.172 to 0.464 | Includes 0 |
| R² | 0.022 | Almost nothing explained |
| Mean (SD) | 57.8 (2.6) bpm | The honest summary |
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.”
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?
| Statistic | Value | Note |
|---|---|---|
| ADF τ (lag 0) | −3.129 | p = 0.025 |
| φ₁ | 0.442 | SE 0.178, t(27) = 2.48 |
| 95% CI | 0.076 to 0.808 | Weak to strong memory |
| Half-life | 0.85 weeks | Very uncertain |
| PACF band | ±0.358 | Only large spikes detectable |
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.”
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.
| Statistic | Value | Note |
|---|---|---|
| ADF τ | −5.069 | p < .001 |
| φ₁ | 0.326 | SE 0.133, p = 0.018 |
| R² | 0.110 | 11% explained |
| σ vs SD | 8.94 vs 9.45 | Uncertainty cut by 5% |
| Next-week forecast | 117.2 | 95% PI 99.7 to 134.7 |
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.”
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.
| Statistic | Value | Note |
|---|---|---|
| ADF τ on prices | −1.159 | p = 0.691, unit root not rejected |
| φ₁ on prices | 0.974 | SE 0.022, half-life 26 days |
| R² on prices | 0.976 | Spurious: the level just tracks itself |
| ADF τ on daily changes | −6.764 | p < .001, changes are stationary |
| φ₁ on changes | −0.067 | p = 0.672, order 0 chosen |
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.”
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?
| Statistic | Site A, north slope | Site B, valley floor |
|---|---|---|
| ADF τ | −3.879, p = 0.002 | −4.813, p < .001 |
| φ₁ (SE) | 0.514 (0.125) | 0.341 (0.137) |
| p for φ₁ | < .001 | 0.016 |
| Half-life | 1.04 years | 0.64 years |
| Long-run index | 0.945 | 1.107 |
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.
- 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.
- Keep the spacing equal. A missing survey shifts every later lag. Plan replacement visits so no step is skipped.
- 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.
- Record the date with every value and keep the data in time order, oldest first, ready to paste into the AR model calculator.
- 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.
- 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.
- Note known interventions such as floods, policy changes or equipment changes. They belong in the model as events, not in the noise.
- Log covariates such as rainfall or temperature in parallel columns, so an ARIMAX or distributed-lag model is possible later.
- Check units and transformations. Counts with a wide range often behave better on a log scale; decide this in the protocol, not after fitting.
- Pre-register the AR model settings: maximum order, AIC or BIC, ADF specification and the differencing rule.
| Month | Site A count | Site B count |
|---|---|---|
| 2023-01 | 52 | 61 |
| 2023-02 | 48 | 58 |
| 2023-03 | 55 | 63 |
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:
- Ecology: density dependence in annual population counts, where φ₁ below 1 means regulation.
- Hydrology: daily river temperature or flow, usually AR(1) or AR(2).
- Dendrochronology: prewhitening ring-width chronologies before climate correlation.
- Economics: persistence of unemployment or inflation.
- 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
- 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.
- Equal spacing and correct order. Check the dates. Gaps or reversed order make the lags meaningless and bias φ₁ toward zero.
- 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.
- 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.
- 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.
- Normal errors, for intervals only. Check with Jarque-Bera. Coefficients stay consistent, but heavy tails make the 95% intervals cover less than 95%.
- 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
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
StatsUnlock. (2026). AR model calculator [Interactive statistical tool]. https://statsunlock.com/ar-model-calculator/@misc{statsunlock_ar_2026, title={AR Model Calculator}, author={{StatsUnlock}}, year={2026}, note={Interactive statistical tool}, url={https://statsunlock.com/ar-model-calculator/}}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
An AR model is a regression on lags. Add outside predictors here, with coefficients, R² and VIF.
Open the tool →Fit a curved trend first, then model the detrended residuals with an AR model.
Open the tool →Check whether your AR residuals are normal before trusting the prediction intervals.
Open the tool →Build 90, 95 and 99% intervals around a mean when your series turns out to be white noise.
Open the tool →Compare the series SD with the AR residual σ to see how much the model narrows uncertainty.
Open the tool →Compare the sample mean with the AR long-run mean c ÷ (1 − Σφ).
Open the tool →Spot outliers and level shifts in each series before fitting an autoregressive model.
Open the tool →Plan how many observations you need for a target precision before starting a monitoring series.
Open the tool →📖 22. Glossary of Terms
| Term | Plain-English meaning |
|---|---|
| ACF | Autocorrelation function: the correlation of a series with itself at each lag. |
| ADF test | Augmented Dickey-Fuller test: checks whether a series has a unit root. A small p-value means stationary. |
| AIC | Akaike 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. |
| ARIMA | Autoregressive integrated moving average: AR and MA terms fitted after differencing. |
| BIC | Bayesian information criterion: like AIC but with a penalty of ln(n) per parameter, so it prefers smaller models. |
| Differencing | Replacing each value with its change from the previous value, to remove a trend or unit root. |
| Half-life | Number of time steps for a shock to fall to half its size. |
| Impulse response | How a single shock today echoes through future values, given by the ψ weights. |
| Inverse root | A root of the AR polynomial turned inside out. All must be below 1 in size for a stationary model. |
| Lag | A value from k steps earlier. Lag 1 of this month is last month. |
| Ljung-Box test | A test of whether several residual autocorrelations are jointly zero. |
| Long-run mean | The level a stationary AR series returns to, c ÷ (1 − Σφ). |
| MA model | Moving average model: the current value depends on past random shocks rather than past values. |
| PACF | Partial autocorrelation function: the correlation at lag k after removing the effect of shorter lags. |
| Persistence | How long deviations last, measured by the sum of the φ coefficients. |
| Prewhitening | Removing AR memory from a series before correlating it with another series. |
| Residual | The observed value minus the one-step fitted value. |
| Stationary series | A series whose mean, variance and autocorrelation do not change over time. |
| Unit root | A sum of AR coefficients equal to 1. Shocks never fade and the series has no fixed mean. |
| White noise | A sequence of uncorrelated random values with zero mean and constant variance. |
| Yule-Walker equations | Equations 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.
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- Schwarz, G. (1978). Estimating the dimension of a model. The Annals of Statistics, 6(2), 461–464. https://doi.org/10.1214/aos/1176344136
- 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
- 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
- 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
- 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
