Possible to generate AR(1) process without loops?

Viewed 867

Is it possible to turn the following Python code loop into code without loops in Python?

steps = 10000
rho = 0.9

e = np.random.randn(steps)
y = [0]

# Possible to get rid of this loop?
for i in range(len(e)):
    y.append(rho*y[i] + e[i])

The code is to generate simple autoregressive (order 1) time series where given some starting value, every next value is rho time previous plus some random noise.

https://en.wikipedia.org/wiki/Autoregressive_model

1 Answers

Check out this code :

import numpy as np

steps = 10000
rho = 0.9
np.random.seed(0)
e = np.random.randn(steps)

z = list(np.zeros(steps))
z[:] = map(lambda x, y: rho*z[y] + x, list(e), list(range(steps)))

Method-2 :

m = list(np.zeros(steps))
m[:] = map(lambda x, y: m.append(rho*m[y] + x), list(e), list(range(steps)))
m = m[10000:]
print(m)

Some quick benchmarks from ipython

In [1]: timeit z[:] = map(lambda x, y: rho*z[y] + x, list(e), list(range(steps)))
1.27 ms ± 19.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [2]: timeit m[:] = map(lambda x, y: m.append(rho*m[y] + x), list(e), list(range(steps)))
1.39 ms ± 31.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [3]: timeit for i in range(len(e)): y.append(rho*y[i] + e[i])
8.18 ms ± 270 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Related