3 回答
TA贡献1826条经验 获得超6个赞
使用 Pandas 系列可以轻松解决这个问题。整个公式:
HMA = WMA(2*WMA(period/2) - WMA(period)), sqrt(period))
给定一个输入序列 s 和一个句点可以打包成一行:
import pandas as pd
import numpy as np
HMA = s.rolling(period//2).apply(lambda x: ((np.arange(period//2) + 1)*x).sum()/(np.arange(period//2) + 1).sum(), raw=True).multiply(2).sub(
s.rolling(period).apply(lambda x: ((np.arange(period) + 1)*x).sum()/(np.arange(period) + 1).sum(), raw=True)
).rolling(int(np.sqrt(period))).apply(lambda x: ((np.arange(int(np.sqrt(period))) + 1)*x).sum()/(np.arange(int(np.sqrt(period))) + 1).sum(), raw=True)
但为了清晰和方便起见,最好定义两个函数:
def WMA(s, period):
return s.rolling(period).apply(lambda x: ((np.arange(period)+1)*x).sum()/(np.arange(period)+1).sum(), raw=True)
def HMA(s, period):
return WMA(WMA(s, period//2).multiply(2).sub(WMA(s, period)), int(np.sqrt(period)))
TA贡献1811条经验 获得超4个赞
移动平均线通常用 的签名来定义ma(series) -> series
。我认为您的困惑很大一部分根源在于 WMA 被定义为返回一个系列,而不是您所期望的单个值。
这是单点 HMA 的 python 实现:
def weighted_moving_average(series: List[float], lookback: Optional[int] = None) -> float:
if not lookback:
lookback = len(series)
if len(series) == 0:
return 0
assert 0 < lookback <= len(series)
wma = 0
lookback_offset = len(series) - lookback
for index in range(lookback + lookback_offset - 1, lookback_offset - 1, -1):
weight = index - lookback_offset + 1
wma += series[index] * weight
return wma / ((lookback ** 2 + lookback) / 2)
def hull_moving_average(series: List[float], lookback: int) -> float:
assert lookback > 0
hma_series = []
for k in range(int(lookback ** 0.5), -1, -1):
s = series[:-k or None]
wma_half = weighted_moving_average(s, min(lookback // 2, len(s)))
wma_full = weighted_moving_average(s, min(lookback, len(s)))
hma_series.append(wma_half * 2 - wma_full)
return weighted_moving_average(hma_series)
TA贡献1802条经验 获得超4个赞
解决了
def calculate_hma(coin_pair, period, unit):
HMA = ((calculate_wma(coin_pair, int(period / 2), unit) * 2 - calculate_wma(coin_pair, period, unit)) + (
calculate_wma(coin_pair, int(math.sqrt(period)), unit))) / 2
添加回答
举报