如何用Python计算赫尔移动平均线?

MOI*_*OIQ 3 python api indicator moving-average

我很高兴能与大家分享我的问题,并期待向大家学习。我当前的问题是def calculating_hma无法获得正确的结果:

#python27

#inputs 
period = 9
Coin_pair = "USD-BTC"
Unit = thirtyMin''

def getClosingPrices(coin_pair, period, unit):
    historical_data = api.getHistoricalData(coin_pair, period, unit)
    closing_prices = []
    for i in historical_data:
        closing_prices.append(i['C'])
    return closing_prices


def calculate_sma(coin_pair, period, unit):

    total_closing = sum(getClosingPrices(coin_pair, period, unit))
    return (total_closing / period)


def calculate_ema(coin_pair, period, unit):

    closing_prices = getClosingPrices(coin_pair, period, unit)
    previous_EMA = calculate_sma(coin_pair, period, unit)
    constant = (2 / (period + 1))
    current_EMA = (closing_prices[-1] * (2 / (1 + period))) + (previous_EMA * (1 - (2 / (1 + period))))

def calculate_hma(coin_pair, period, unit):
    """
    Hull Moving Average.
    
    Formula:
    HMA = WMA(2*WMA(n/2) - WMA(n)), sqrt(n)
    """
    
    # MY Try of calculation ?
    ma = calculate_sma(coin_pair, period, unit)
    HMA = ma(2*ma(period/2) - ma(period)), sqrt(period)
    
    # my question  ?
    # where to use the unit and pierod and coin_pair in the calculation ?  

    # check inputs above
    return hma

ema = calculate_ema(market, period=9, unit=timeframe)
sma = calculate_sma(market, period=9, unit=timeframe)
hma = calculate_sma(market, period=9, unit=timeframe) ? 

print (ema)
print (sma)
print (hma)
Run Code Online (Sandbox Code Playgroud)

mac*_*13k 6

使用 Pandas 系列可以轻松解决这个问题。整个公式:

HMA = WMA(2*WMA(period/2) - WMA(period)), sqrt(period))
Run Code Online (Sandbox Code Playgroud)

给定一个输入序列 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)
Run Code Online (Sandbox Code Playgroud)

但为了清晰和方便起见,最好定义两个函数:

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)))
Run Code Online (Sandbox Code Playgroud)