3

I have been trying to get python coded pandas logic output exactly same as the trading view chart output for "OBV - On Balcance Volume"

some of the Pine Script Reference for OBV:

study(title="On Balance Volume", shorttitle="OBV")
src = close
obv = cum(change(src) > 0 ? volume : change(src) < 0 ? -volume : 0*volume)
plot(obv, color=blue, title="Price_OBV")

Calculation method given in Tradingview Wiki Page

On Balance Volume has one of the more straightforward calculations in technical analysis. It is simply addition or subtraction based on a few conditions.

  1. If Current Closing Price is greater than the Prior Closing Price then: Previous OBV + Current Volume = Current OBV

  2. If Current Closing Price is less than the Prior Closing Price then: Previous OBV - Current Volume = Current OBV

  3. If Current Closing Price is equal to the Prior Closing Price then: Previous OBV = Current OBV

Python code that i tried:

def on_balance_volume(close_data, volume):
    """
    On Balance Volume.
    Formula:
    start = 1
    if CLOSEt > CLOSEt-1
        obv = obvt-1 + volumet
    elif CLOSEt < CLOSEt-1
        obv = obvt-1 - volumet
    elif CLOSEt == CLOSTt-1
        obv = obvt-1
    """
    catch_errors.check_for_input_len_diff(close_data, volume)
    obv = np.zeros(len(volume))
    obv[0] = 0
    for idx in range(0, len(obv)):
        if (close_data[idx] - close_data[idx-1]) > 0:
            obv[idx] = obv[idx-1] + volume[idx]
        elif (close_data[idx] - close_data[idx-1])<0:
            obv[idx] = obv[idx-1] - volume[idx]
#        elif close_data[idx] == close_data[idx-1]:
#            obv[idx] = obv[idx-1]
    return obv


df['obv']=on_balance_volume(df['close'],df['volume'])

Note : I verified the volume input that is matching exactly what is shown in tradingview.

you can use this data source for verifying the output (Generate your key to get the data) DateLink

What is the change i need to do to get the exact TV chart OBV value in python code.

Marx Babu
  • 750
  • 3
  • 11
  • 34

0 Answers0