Loading ...

【原生代码】Pyrhon3实现VWAP成交量加权平均线

Author: 苏慕白, Created: 2021-11-20 21:13:24, Updated:

1. VWAP成交量加权平均线算法:

公式: (price * Volume) / Volume


详细解释: 周期内累积((High+Low+Close) / 3 * Volume) 再除以周期内累积交易量


下面的实现代码周期单位是:天 也就是每天早上8点重置累积的量(TradingView中是这样) 有需求可以自行看代码自行修改重置的时间


2. 代码实现:

impot time

"""字典转数组"""
def GetSrc(r, name):
    if name == 'o+h+l+c':
        src = [ (v['Open'] + v['High'] + v['Low'] + v['Close']) / 4 for v in r ]

    elif name == 'h+l+c':
        src = [ (v['High'] + v['Low'] + v['Close']) / 3 for v in r ]

    elif name == 'h+l':
        src = [ (v['High'] + v['Low']) / 2 for v in r ]

    else:
        src = [ v[name] for v in r ] if name else r

    return src
	

""" 时间戳转换"""
def GetTime(x, style="%H:%M:%S"):
    x = int(str(x)[:10])
    time_local = time.localtime(x)
    dt = time.strftime(style,time_local)
    return dt
	
"""成交量加权平均线"""
def VWAP(r, dayTime='08:00', name='h+l+c',):
    src = GetSrc(r, name)
    emas = [0 for i in range(len(src))]  # 创造一个和cps一样大小的集合

    srcVol,Vol = 0, 0
    for i in range(len(src)):
        if GetTime(r[i]['Time'], "%H:%M") == dayTime: #每天早上八点重置
            Vol = r[i]['Volume']
            srcVol = src[i] * r[i]['Volume']
        else:
            Vol += r[i]['Volume']
            srcVol += src[i] * r[i]['Volume']
        emas[i] = srcVol / Vol
    
    return emas

3. 变量r 结构图如下:

{
	{
		'Time': 0, #时间戳
		'Close': 0,
		'Open': 0,
		'High': 0,
		'Low': 0,
		'Volume': 0, #成交量
	}
}

4. 调用:

vwap = VWAP(r)

结果基本和TradingView一致

原文:https://sumubai.cc/post/37


More