Search code examples
pythonpandasbinancebinance-api-client

Calculate the difference between column and the previous column in pandas DataFrame


I am pulling live data for BTCUSDT from binance every 1 minute using binance-api, and I want to calculate the percentage change between the current candle close price and the previous candle I have tried the following:

def get_live_data(symbol):
    candles = pd.DataFrame(Client.get_klines(symbol=symbol, interval=Client.KLINE_INTERVAL_1MINUTE,
                                             limit=1,
                                             startTime=None,
                                             endTime=None))
    candles.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close_Time',
                                       'Quote_Volume', 'Trades_Count', 'BUY_VOL', 'BUY_VOL_VAL', 'x']
    candles["Close_Time"] = pd.to_datetime(candles["Close_Time"], unit='ms')
    candles["Date"] = pd.to_datetime(candles["Date"], unit="ms")
    candles["pct_change1M"] = candles.Close

    candles["Open"] = pd.to_numeric(candles["Open"])
    candles["High"] = pd.to_numeric(candles["High"])
    candles["Low"] = pd.to_numeric(candles["Low"])
    candles["Close"] = pd.to_numeric(candles["Close"])
    candles["Volume"] = round(pd.to_numeric(candles["Volume"]))
    candles["Quote_Volume"] = round(pd.to_numeric(candles["Quote_Volume"]))

    candles['pchange1M'] = candles.Close.diff(1).fillna(0)
    candles['pchange1Mpct'] = round((candles['pchange1M']/candles["Close"]) * 100, 2)

    del(candles["Trades_Count"])
    del(candles["BUY_VOL"])
    del(candles["BUY_VOL_VAL"])
    del(candles["x"])

    return candles

symbol = "BTCUSDT"
while True:
    candles = get_live_data(symbol="BTCUSDT")
    print(candles)
    time.sleep(60)

But the columns pchange1M and pchange1Mpct are always zero as follow: (i have deleted the unneeded columns)

Date                  Close     pct_change1M  pchange1Mpct
2021-08-18 16:45:00   45775.01    0.0            0.0

Date                  Close     pct_change1M  pchange1Mpct
2021-08-18 16:46:00   45785.0      0.0             0.0

Could someone please tell what I am missing or what I am doing wrong ?


Solution

  • It looks like you're pulling one row at a time since you have limit=1. So when you diff, there's nothing to diff against. And with fillna(0), you'll end up with diffs of 0.