Skip to content

Instantly share code, notes, and snippets.

@euikook
Last active May 31, 2021 07:27
Show Gist options
  • Save euikook/302430b2a5108a1f5ee18b4e6c97ed3f to your computer and use it in GitHub Desktop.
Save euikook/302430b2a5108a1f5ee18b4e6c97ed3f to your computer and use it in GitHub Desktop.
moving-average
import numpy as np
def do_cma(s):
return s.expanding().mean()
def do_sma(s, N=15):
return s.rolling(N, min_periods=1).mean()
def do_ema(s, N=15):
return s.ewm(alpha=2/(N+1)).mean()
w = lambda x: np.arange(1, len(x) + 1)
def do_wma(s, N=15):
# w = np.arange(1, N + 1)
return s.rolling(N, min_periods=2).apply(lambda x: np.dot(x, w(x))/w(x).sum(), raw=True)
import numpy as np
import pandas as pd
import matplotlib.dates as mdates
from avgutils import do_cma, do_sma, do_ema, do_wma
from matplotlib import rcParams
rcParams['font.family'] = 'monospace'
rcParams['font.sans-serif'] = ['Tahoma']
import matplotlib.pyplot as plt
N = 15
from matplotlib.ticker import (MultipleLocator, AutoMinorLocator)
all_frames = pd.read_csv('data.csv')
df = all_frames.tail(365)
# df = all_frames
date = pd.to_datetime(df.Date)
high = df.High
low = df.Low
price = df.Close
cma = do_cma(price)
sma = do_sma(price, N=N)
ema = do_ema(price, N=N)
wma = do_wma(price, N=N)
ax = pd.DataFrame({
'Date': date,
'Price': price,
'CMA': cma,
'SMA': sma,
'WMA': wma,
'EMA': ema
}).plot(x='Date', kind='line', figsize=(16, 9))
fmt_month = mdates.MonthLocator()
ax.xaxis.set_minor_locator(fmt_month)
# Text in the x axis will be displayed in 'YYYY-mm' format.
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
plt.legend(labels=[
'Closing Price',
'Cumulative Moving Average',
'Simple Moving Average',
'Weighted Moving Average',
'Exponential Moving Average',
], fontsize=12)
plt.xlim(date.iat[0], date.iat[-1])
plt.title(f'Moving Average(N={N})', fontsize=14)
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig('all.svg', format='svg')
import numpy as np
import pandas as pd
from matplotlib import rcParams
rcParams['font.family'] = 'monospace'
rcParams['font.sans-serif'] = ['Tahoma']
import matplotlib.pyplot as plt
from matplotlib.ticker import (MultipleLocator, AutoMinorLocator)
# smoothing factor and number of data points
N = 15
ALPHA = 2/(N+1)
NUM_X = N * 4
# simple moving average
sma = [0 if i > N else 1/N for i in range(NUM_X)]
# weighted moving average
wma = [0 if i > N else (N - i)/(N * (N + 1) / 2) for i in range(NUM_X)]
# exponential moving average alpha=2/(N+1)
ema = [ALPHA*(1-ALPHA)**i for i in range(NUM_X)]
# store the values in a data frame
pd.DataFrame({'sma': sma, 'wma': wma, 'ema': ema}).plot(kind='bar', figsize=(16,9))
plt.xticks(np.arange(0, NUM_X, 5), rotation=0)
plt.yticks(fontsize=10)
plt.legend(labels=[
'SMA',
'WMA',
'EMA, α=2/(N+1)'
], fontsize=12)
# title and labels
plt.title(f'Weights of Moving Average(N={N})', fontsize=14)
plt.ylabel('Weights', fontsize=12)
plt.xlabel('n-th Most Recent Smple', fontsize=12)
plt.tight_layout()
# plt.savefig('weight.svg', format='svg')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment