Last active
November 13, 2020 15:49
-
-
Save yanniskatsaros/28f935422ef96b33442919cc88f79154 to your computer and use it in GitHub Desktop.
Exponential Smoothing on a Random Walk
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 typing import Iterable | |
import numpy as np | |
import matplotlib.pyplot as plt | |
import seaborn as sns | |
from numpy import ndarray | |
def generate_random_walk(size: int) -> ndarray: | |
draw = np.random.random(size) | |
steps = np.where(draw > 0.5, 1, -1) | |
return np.cumsum(steps) | |
# taken/inspired from: https://stackoverflow.com/a/42926270/12160601 | |
def exponential_smoothing(arr: ndarray, window: int) -> ndarray: | |
a = 2 / (window + 1.0) | |
n = len(arr) | |
powers = (1 - a) ** np.arange(n + 1) | |
scale = 1 / powers[:-1] | |
offset = arr[0] * powers[1:] | |
pw0 = a * (1 - a) ** (n - 1) | |
mult = arr * pw0 * scale | |
return offset + np.cumsum(mult) * scale[::-1] | |
def plot_trends(trends: Iterable[ndarray], labels: Iterable[str], **kwargs): | |
fig, ax = plt.subplots(figsize=(8, 5)) | |
styles = { | |
'linewidth': 2, | |
} | |
ax.axhline(0, linestyle='--', color='black') | |
for t, l in zip(trends, labels): | |
n = len(t) | |
ax.plot(np.arange(n), t, label=l, **styles) | |
xlabel = kwargs.get('xlabel', 'X') | |
ylabel = kwargs.get('ylabel', 'Y') | |
title = kwargs.get('title', 'Trends') | |
ax.legend() | |
ax.grid(linestyle=':') | |
ax.set_xlabel(xlabel) | |
ax.set_ylabel(ylabel) | |
ax.set_title(title) | |
sns.despine() | |
fig.tight_layout() | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some example usage (assuming the imports from above have been called)