Last active
June 21, 2021 13:25
-
-
Save romanbsd/54f50aed880abe6d0c0adb6f655bd489 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import deque | |
import numpy as np | |
class SMA: | |
def __init__(self, window: int) -> None: | |
"""Calculates a running mean and standard deviation | |
Args: | |
window (int): Window length | |
""" | |
self.N = window | |
self._q = deque(maxlen=window) | |
self.E = 0 | |
self.variance = 0 | |
def __repr__(self) -> str: | |
return "<SMA N=%d E=%.3f std=%.3f>" % (self.N, self.E, self.std) | |
def reset(self): | |
self.E = 0 | |
self.variance = 0 | |
self._q.clear() | |
def add(self, value): | |
if len(self._q) == 0: | |
self.E = value | |
for _ in range(self.N): | |
self._q.append(value) | |
x0 = self._q.popleft() | |
self._q.append(value) | |
prevE = self.E | |
self.E = self.E + (value - x0) / self.N | |
self.variance += (value - x0) * (value - self.E + x0 - prevE) / (self.N - 1) | |
return self.E | |
@property | |
def std(self): | |
return np.sqrt(self.variance) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment