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

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

### 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)
``````

More