Skip to content

Instantly share code, notes, and snippets.

@yanniskatsaros
Last active November 13, 2020 15:49
Show Gist options
  • Save yanniskatsaros/28f935422ef96b33442919cc88f79154 to your computer and use it in GitHub Desktop.
Save yanniskatsaros/28f935422ef96b33442919cc88f79154 to your computer and use it in GitHub Desktop.
Exponential Smoothing on a Random Walk
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()
@yanniskatsaros
Copy link
Author

yanniskatsaros commented Nov 13, 2020

Some example usage (assuming the imports from above have been called)

# matplotlib plot style defaults
sns.set(style='white', font_scale=1.3)

walk = generate_random_walk(5000)
walk_smooth = exponential_smoothing(walk, window=20)

config = {
    'xlabel': 'Steps',
    'ylabel': 'Units',
    'title': 'Random Walk\n(with Exponential Smoothing)',
}
plot_trends([walk, walk_smooth], ['Random Walk', 'Exponential Smoothing'], **config)

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment