Skip to content

Instantly share code, notes, and snippets.

@GerardBCN
Created April 26, 2019 15:59
Show Gist options
  • Save GerardBCN/956d439986a1f30c0e6c0807afdf6398 to your computer and use it in GitHub Desktop.
Save GerardBCN/956d439986a1f30c0e6c0807afdf6398 to your computer and use it in GitHub Desktop.
Dollar bar generator
import numpy as np
# expects a numpy array with trades
# each trade is composed of: [time, price, quantity]
def generate_dollarbars(trades, frequency=1000):
times = trades[:,0]
prices = trades[:,1]
volumes = trades[:,2]
ans = np.zeros(shape=(len(prices), 6))
candle_counter = 0
dollars = 0
lasti = 0
for i in range(len(prices)):
dollars += volumes[i]*prices[i]
if dollars >= 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
dollars = 0
return ans[:candle_counter]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment