0

I am pulling data from polygon.io and it returns time as a Unix Msec timestamp as below, afterwhich I am having trouble converting this to a index that is useable by mplfinance that is expecting TypeError: Expect data.index as DatetimeIndex.

data

I have the following code, where I have the placeholder function from_unixtime which i have yet to define:

import mplfinance as mpf
import pandas as pd
from polygon import RESTClient

def main():
    key = "keyhere"

    with RESTClient(key) as client:
        start = "2019-01-01"
        end = "2019-02-01"
        resp = client.stocks_equities_aggregates("AAPL", 1, "minute", start, end, unadjusted=False)
        df = pd.DataFrame(resp.results)
        df.index = [from_unixtime(ts) for ts in df['t']]
        df.index.name = 'Timestamp'
      
        # mpf expects a dataframe containing Open, High, Low, and Close data with a Pandas TimetimeIndex
        df.columns = ['Volume', 'Volume Weighted', 'Open', 'Close', 'High', 'Low', 'Time', 'Num Items']
        mpf.plot(df, type='candlestick', no_xgaps = True)

if __name__ == '__main__':
    main()
morleyc
  • 2,169
  • 10
  • 48
  • 108

1 Answers1

1

Try replacing

df.index = [from_unixtime(ts) for ts in df['t']]

with

df.index = pd.DatetimeIndex( pd.to_datetime(df['t'],unit='s') )

lmk

Daniel Goldfarb
  • 6,937
  • 5
  • 29
  • 61
  • Many thanks Daniel, since the data is in ms, i had to divide by 1000 (as unit is in second, and ms not supported), i think this works! `df.index = pd.DatetimeIndex( pd.to_datetime(df['t']/1000,unit='s') )` – morleyc Dec 24 '21 at 21:06
  • alternatively `unit='ms'` worked for me – Alter Dec 09 '22 at 23:33