User Avatar

Leo E.

4y ago

Math enthusiast

On-Balance Volume Indicator Algorithm in Python

Yesterday, I introduced the idea of On-Balance Volume and showed how to get volume and closing values for the Shopify stock during a five day time period. I also described the basic steps of the algorithm, however I did not present the algorithm. Below is the full algorithm with some dependencies on yesterday's code.

obv_prev = 0 obv = 0 obv_history = [] close_price_prev = None start = True vol_close_lst = zip(volume_nd, close_nd) for vol, close_price in vol_close_lst: if start is True: start = False else: if close_price > close_price_prev: obv = obv_prev + vol elif close_price < close_price_prev: obv = obv_prev - vol else: obv = obv_prev obv_prev = obv obv_history.append(obv) close_price_prev = close_price

One minor modification is that instead of 5 days range for volume and closing price I decided to parametrize it for any number of days that I may care about.

Below this essay I will post graphs showing closing range, volume and OBV changes for the last 12 days, where today will show up as zero in the graph.