def BollingerBands(price): from math import sqrt MA = lambda p, n: sum(p[-n:])/len(p[-n:]) ma = obs.aggregate(price, lambda p: MA(p, 20), window=20, name="MA20") std_dev = obs.aggregate([price, ma], lambda x: sqrt(sum([(v[1]-v[0])**2 for v in x])/len(x)), name="MA20sd", window=20) STDhi = indicator([ma, std_dev], lambda (m, s): m + 2*s, name="bollingerHI") STDmi = indicator(ma, name="bollingerMI") STDlo = indicator([ma, std_dev], lambda (m, s): m - 2*s, name="bollingerLO") return [STDhi, STDmi, STDlo]
def MACD(price): EWMA = lambda alpha: (lambda p: reduce(lambda x, y: x + (y-x)*alpha, p, 0)) ewma12 = obs.aggregate(price, EWMA(2./13), window=12, name="EWMA12") ewma26 = obs.aggregate(price, EWMA(2./27), window=26, name="EWMA26") macd_signal = obs.aggregate([ewma12, ewma26], lambda (x, y): x-y, name="MACDsignal") macd_line = obs.OnEveryDt(1, macd_signal) signal_line = indicator(macd_signal, EWMA(2./10), window=9, name="signal_line") MACD = [macd_line, signal_line] return MACD
def indicator(sources, f=(lambda x: x), window=1, name=None): return obs.OnEveryDt(1, obs.aggregate(sources, f, window, name))