Skip to content Skip to sidebar Skip to footer

Calculating Stocks's On Balance Volume (obv) In Python

I am doing my first project in python. I have a pandas dataframe called df with two columns 'close' and 'volume'. I want to calculate/obtain OBV column based on first two columns.

Solution 1:

I dont know why you are getting the error but here is a solution to get OBV:

np.where(df['close'] > df['close'].shift(1), df['volume'], 
np.where(df['close'] < df['close'].shift(1), -df['volume'], 0)).cumsum()

It is also faster, which is good if you are gonna do many iterations!

Solution 2:

I'm basing this on Olli's answer, but I think it's a slightly cleaner solution:

obv = (np.sign(df['close'].diff()) * df['volume']).fillna(0).cumsum()

Solution 3:

this is another answer maybe help someone:

obv = (df.volume * (~df.close.diff().le(0) * 2 - 1)).cumsum()

Post a Comment for "Calculating Stocks's On Balance Volume (obv) In Python"