Skip to content

Commit e6eb640

Browse files
committed
maths: add autocorrelation function
1 parent 6df8dda commit e6eb640

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

maths/autocorrelation.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
Autocorrelation measures the correlation of a signal with a delayed
3+
copy of itself. It is widely used in time series analysis, signal
4+
processing, and statistics.
5+
6+
Reference: https://en.wikipedia.org/wiki/Autocorrelation
7+
"""
8+
9+
10+
def autocorrelation(data: list[float], lag: int) -> float:
11+
"""
12+
Calculate the autocorrelation of a time series at a given lag.
13+
14+
:param data: A list of numerical values representing the time series.
15+
:param lag: The number of time steps to shift the series.
16+
:return: The autocorrelation coefficient at the given lag.
17+
18+
>>> round(autocorrelation([1, 2, 3, 4, 5], 1), 4)
19+
0.4
20+
>>> round(autocorrelation([1, 2, 3, 4, 5], 0), 4)
21+
1.0
22+
>>> autocorrelation([1, 2, 3], 5)
23+
Traceback (most recent call last):
24+
...
25+
ValueError: Lag must be less than the length of the data.
26+
"""
27+
if lag >= len(data):
28+
raise ValueError("Lag must be less than the length of the data.")
29+
30+
n = len(data)
31+
mean = sum(data) / n
32+
variance = sum((x - mean) ** 2 for x in data) / n
33+
34+
if variance == 0:
35+
raise ValueError("Variance of data is zero, autocorrelation undefined.")
36+
37+
covariance = sum(
38+
(data[i] - mean) * (data[i - lag] - mean)
39+
for i in range(lag, n)
40+
) / n
41+
42+
return covariance / variance
43+
44+
45+
if __name__ == "__main__":
46+
import doctest
47+
doctest.testmod()
48+
data = [1, 2, 3, 4, 5, 4, 3, 2, 1]
49+
for lag in range(5):
50+
print(f"Lag {lag}: {autocorrelation(data, lag):.4f}")

0 commit comments

Comments
 (0)