Skip to content

Instantly share code, notes, and snippets.

@alexanu
Forked from GerardBCN/volumebar_generator.py
Created January 12, 2020 16:22
Show Gist options
  • Save alexanu/35035e1e2917ef5ccd6597425b040c52 to your computer and use it in GitHub Desktop.
Save alexanu/35035e1e2917ef5ccd6597425b040c52 to your computer and use it in GitHub Desktop.
Volume bar generator
import numpy as np
# expects a numpy array with trades
# each trade is composed of: [time, price, quantity]
def generate_volumebars(trades, frequency=10):
times = trades[:,0]
prices = trades[:,1]
volumes = trades[:,2]
ans = np.zeros(shape=(len(prices), 6))
candle_counter = 0
vol = 0
lasti = 0
for i in range(len(prices)):
vol += volumes[i]
if vol >= frequency:
ans[candle_counter][0] = times[i] # time
ans[candle_counter][1] = prices[lasti] # open
ans[candle_counter][2] = np.max(prices[lasti:i+1]) # high
ans[candle_counter][3] = np.min(prices[lasti:i+1]) # low
ans[candle_counter][4] = prices[i] # close
ans[candle_counter][5] = np.sum(volumes[lasti:i+1]) # volume
candle_counter += 1
lasti = i+1
vol = 0
return ans[:candle_counter]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment