Skip to content

Commit

Permalink
Merge pull request #5 from iskandergaba/bugfix/incorrect_periods_dete…
Browse files Browse the repository at this point in the history
…cted

Fixed incorrect consideration of certain ACF lag values as period candidates
  • Loading branch information
iskandergaba authored Dec 26, 2023
2 parents 0c74977 + 79f58fa commit da9a6e8
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
19 changes: 10 additions & 9 deletions auto_period_finder/finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,37 +175,38 @@ def __find_periods(
acf_kwargs: Dict[str, Union[int, bool, None]],
) -> list:
periods = []
acf_array = np.array(acf(y, nlags=len(y), **acf_kwargs))
acf_arr = np.array(acf(y, nlags=len(y), **acf_kwargs))
acf_arr_work = acf_arr.copy()

# Eliminate the trivial seasonality period of 1
acf_array[0] = -1
acf_arr_work[0] = -1

while True:
# i is a period candidate: It cannot be greater than half the timeseries length
i = acf_array[: acf_array.size // 2].argmax()
i = acf_arr_work[: acf_arr_work.size // 2].argmax()

# No more periods left or the maximum number of periods has been found
if acf_array[i] == -1 or (
if acf_arr_work[i] == -1 or (
max_period_count is not None and len(periods) == max_period_count
):
return periods

# Check that i and all of its multiples are local maxima
elif all(
[
acf_array[i * j - 1] < acf_array[i * j]
and acf_array[i * j] > acf_array[i * j + 1]
for j in range(1, len(acf_array) // i - 1)
acf_arr[i * j - 1] < acf_arr[i * j]
and acf_arr[i * j] > acf_arr[i * j + 1]
for j in range(1, len(acf_arr) // i - 1)
]
):
# Add to period return list
periods.append(i)
# Ignore i and its multiplies
acf_array[[i * j for j in range(1, len(acf_array) // i)]] = -1
acf_arr_work[[i * j for j in range(1, len(acf_arr_work) // i)]] = -1

# Not a period, ignore it
else:
acf_array[i] = -1
acf_arr_work[i] = -1

@staticmethod
def __seasonality_strength(seasonal, resid):
Expand Down
4 changes: 2 additions & 2 deletions tests/test_finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ def test_find_strongest_period_var_wise_stl_custom():
strongest_period_var = period_finder.fit_find_strongest_var(
decomposer=Decomposer.STL, decomposer_kwargs={"seasonal_deg": 0}
)
assert strongest_period_var == 132
assert strongest_period_var == 180


def test_find_strongest_period_var_wise_moving_averages():
data = co2.load().data.resample("M").mean().ffill()
period_finder = AutoPeriodFinder(data)
strongest_period_var = period_finder.fit_find_strongest_var()
assert strongest_period_var == 132
assert strongest_period_var == 176

0 comments on commit da9a6e8

Please sign in to comment.