Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speed up WMA by removing the for loop and repeated len() calls #161

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions talipp/indicators/WMA.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import numpy as np
from typing import List, Any

from talipp.indicator_util import has_valid_values
Expand Down Expand Up @@ -38,9 +39,11 @@ def _calculate_new_value(self) -> Any:
if not has_valid_values(self.input_values, self.period):
return None

s = 0.0
for i in range(self.period, 0, -1):
index = len(self.input_values) - self.period + i - 1 # decreases from end of array with increasing i
s += self.input_values[index] * i
# Convert input_values to a NumPy array for vectorized operations
input_values_np = np.array(self.input_values[-self.period:])

return s / self.denom_sum
# Calculate weighted moving average using NumPy vectorized operations
weights = np.arange(1, self.period + 1)
wma = np.sum(input_values_np * weights) / self.denom_sum

return wma
Loading