【原生代码】Pyrhon3实现VWAP成交量加权平均线
温馨提示:本文最后更新于2021年11月20日 20:46,若内容或图片失效,请在下方留言或联系博主。
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一致