Hello Quantopian community,
I want to calculate the Hull Moving Average for 21 periods on the 1 hour chart. The formula is:
- Calculate a Weighted Moving Average with period n / 2 and multiply it by 2
- Calculate a Weighted Moving Average for period n and subtract if from step 1
- Calculate a Weighted Moving Average with period sqrt(n) using the data from step 2
from quantopian.algorithm import calendars
import talib as ta
import pandas as pd
import math
def initialize(context):
context.asset = sid(24) # Stock ID
set_benchmark(sid(24))
for hours_offset in range(1, 8):
schedule_function(hma_mfi_strategy,
date_rules.every_day(),
time_rules.market_open(hours=hours_offset),
calendar=calendars.US_EQUITIES,
half_days=True)
def hma_mfi_strategy(context, data):
moving_average = 21
dataset = data.history(context.asset, 'close', 60 * moving_average, '1m')
close = dataset.resample('60min').last().dropna()
wma_ta = (ta.WMA(close, moving_average / 2 ) * 2) - ta.WMA(close, moving_average) # Step 1, 2
hull_moving_average = pd.DataFrame(ta.WMA(wma_ta, math.sqrt(moving_average))) # step 3
print(hull_moving_average.dropna())
As a result I get a couple of NaN's and 0's.
Two questions:
1. Am I resampling the timeframe for 1hr candles correctly?
2. Where is my mistake in calculating the Hull Moving Average?