morleyc
morleyc

Reputation: 2441

Unix ms timestamp pandas index (plotting polygon.io data with mplfinance)

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()

Upvotes: 0

Views: 913

Answers (1)

Daniel Goldfarb
Daniel Goldfarb

Reputation: 7714

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

Upvotes: 1

Related Questions