Skip to content

Instantly share code, notes, and snippets.

@jxm262
Created July 7, 2020 18:47
Show Gist options
  • Save jxm262/449aed7f3ce0919e57a1f0ad8c18a9d9 to your computer and use it in GitHub Desktop.
Save jxm262/449aed7f3ce0919e57a1f0ad8c18a9d9 to your computer and use it in GitHub Desktop.
TT VWAP in Python
We can make this file beautiful and searchable if this error is corrected: No commas found in this CSV file in line 0.
Date Open High Low Close Volume
2020-05-06 18:15:00-04:00 2832 2838.5 2832 2838 3750
2020-05-06 18:30:00-04:00 2838 2838.5 2826 2827.75 6864
2020-05-06 18:45:00-04:00 2827.75 2830.5 2827 2829.5 2937
2020-05-06 19:00:00-04:00 2829.5 2830.5 2823 2826.5 4619
2020-05-06 19:15:00-04:00 2826.75 2829.5 2825.25 2827.75 3610
2020-05-06 19:30:00-04:00 2827.75 2829.5 2825.5 2826.75 2460
2020-05-06 19:45:00-04:00 2826.75 2830.75 2826.25 2830.5 2531
2020-05-06 20:00:00-04:00 2830.5 2833.5 2830.25 2833.5 2361
import pandas as pd
import mplfinance as mpf
import math
df = pd.read_csv('./data.csv', sep=',', quotechar='"')
df.set_index(['Date'], inplace=True)
df.index = pd.to_datetime(df.index)
df.index.name = 'Date'
# from here = https://www.tradingtechnologies.com/xtrader-help/x-study/technical-indicator-definitions/volume-weighted-average-price-vwap/
df['VWAP'] = (df.Volume * (df.High + df.Low) / 2).cumsum() / df.Volume.cumsum()
df['VWAP_MEAN_DIFF'] = ((df.High + df.Low) / 2) - df.VWAP
df['SQ_DIFF'] = df.VWAP_MEAN_DIFF.apply(lambda x: math.pow(x, 2))
df['SQ_DIFF_MEAN'] = df.SQ_DIFF.expanding().mean()
df['STDEV_TT'] = df.SQ_DIFF_MEAN.apply(math.sqrt)
stdev_multiple_1 = 1.28
stdev_multiple_2 = 2.01
stdev_multiple_3 = 2.51
df['STDEV_1'] = df.VWAP + stdev_multiple_1 * df['STDEV_TT']
df['STDEV_N1'] = df.VWAP - stdev_multiple_1 * df['STDEV_TT']
addplot = [
mpf.make_addplot(df['VWAP']),
mpf.make_addplot(df['STDEV_1']),
mpf.make_addplot(df['STDEV_N1']),
]
mpf.plot(df, type='candle', addplot=addplot)
@jxm262
Copy link
Author

jxm262 commented Jul 7, 2020

@jxm262
Copy link
Author

jxm262 commented Jul 7, 2020

Blue = VWAP
Orange = VWAP + 1 dev
Green = VWAP - 1 dev

image

@jxm262
Copy link
Author

jxm262 commented Jul 7, 2020

TradingView (using VWAP-Stdev-Bands-v2-Mod-UPDATE indicator). Note, slight difference since they weight the price by volume in the variance function

image

@hhashim1
Copy link

Do you have a numpy version of vwap with bands?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment