Created
June 15, 2021 20:35
-
-
Save joocer/534fc622ab0f83236d7a62288c892178 to your computer and use it in GitHub Desktop.
python bollinger bands without pandas
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 matplotlib import pyplot as plt # type:ignore | |
from mabel.data.formats import dictset | |
import numpy as np # type:ignore | |
def bollinger_bands(series, length=20, sigmas=2): | |
index = 0 | |
window = series[0:length] | |
num_vals = len(window) | |
if num_vals < length: | |
msg = 'window size {} exceeds total number of values {}' | |
raise ValueError(msg.format(length, num_vals)) | |
while index < len(series): | |
avg = np.mean(window) | |
sigma = np.std(window) | |
yield {"low":avg - (sigma * sigmas), "avg": avg, "hi": avg + (sigma * sigmas)} | |
index += 1 | |
window = series[index:length+index] | |
def plot_bollinger_bands(series, length=20, sigmas=2): | |
plt.figure(figsize=(20, 6)) | |
data = list(bollinger_bands(series, length=length, sigmas=sigmas)) | |
l = dictset.extract_column(data, "low") | |
a = dictset.extract_column(data, "avg") | |
u = dictset.extract_column(data, "hi") | |
plt.plot(a) | |
plt.plot(u) | |
plt.plot(l) | |
plt.plot(series) | |
return plt | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment