Reputation: 107
Basically I get bitcoin market data from coingecko API. I want to resample that ticker data to hourly OHLC (Open High Low Close) so I can run some chart analyses.
I converted the data from from RangeIndex to DatetimeIndex and then tried to resample...
import pandas as pd
import json
import requests
API_URL = 'https://api.coingecko.com/api/v3'
r = requests.get(API_URL + '/coins/bitcoin/market_chart?vs_currency=usd&days=1&interval=hourly')
data = r.json()
df = pd.DataFrame(data)
df.index = pd.to_datetime(df.index)
ohlc = df.index.resample('1h').ohlc()
So now I am getting an error:
"AttributeError: 'DatetimeIndex' object has no attribute 'resample'"
Upvotes: 0
Views: 2790
Reputation: 5601
GroupBy.ohlc() should be a groupby
object.
df = pd.DataFrame(data['prices'], columns = ['dateTime', 'price'])
df['date'] = pd.to_datetime(df['dateTime'], unit='ms')
# method1
df.set_index('date')['price'].resample('1h').ohlc()
# method2
df['hr'] = df['date'].dt.strftime('%Y-%m-%d %H:00')
df.groupby('hr')['price'].ohlc()
result:
open high low close
hr
2021-02-01 01:00 32835.839519 33438.836060 32835.839519 33389.974454
2021-02-01 02:00 33400.422170 33663.000232 33260.343246 33569.816646
2021-02-01 03:00 33581.206956 33633.454861 33437.081539 33466.178320
2021-02-01 04:00 33473.881292 33680.926267 33473.881292 33512.310031
2021-02-01 05:00 33496.550836 33692.662741 33442.771302 33692.295982
2021-02-01 06:00 33674.363254 33931.304243 33372.640454 33372.640454
2021-02-01 07:00 33466.277250 33718.499099 33410.173005 33543.580113
2021-02-01 08:00 33691.622420 34155.668712 33577.491467 34155.668712
2021-02-01 09:00 34541.989582 34541.989582 34246.591606 34255.313422
2021-02-01 10:00 34254.311054 34318.042807 34009.930110 34043.516502
2021-02-01 11:00 34102.209535 34181.236131 33960.033182 34181.236131
2021-02-01 12:00 34196.688991 34196.688991 33677.872302 33677.872302
2021-02-01 13:00 33658.073761 33831.043558 33616.263612 33616.263612
2021-02-01 14:00 33506.144521 33698.288934 33298.355558 33458.379708
2021-02-01 15:00 33449.472954 33540.119075 33137.424801 33137.424801
2021-02-01 16:00 33129.661923 33444.487621 33129.661923 33444.487621
2021-02-01 17:00 33427.510914 33966.758995 33328.452664 33966.758995
2021-02-01 18:00 33883.647812 33883.647812 33692.664177 33753.657270
2021-02-01 19:00 33568.840250 33904.003721 33568.840250 33817.161851
2021-02-01 20:00 33716.826906 33857.417730 33663.339958 33757.230256
2021-02-01 21:00 33608.964863 33692.950108 33508.713475 33553.086495
2021-02-01 22:00 33475.494546 33629.985564 33423.225607 33423.225607
2021-02-01 23:00 33396.069559 33614.188165 33361.882597 33405.990357
2021-02-02 00:00 33423.242711 33912.467287 33423.242711 33626.927090
2021-02-02 01:00 33578.032588 33578.032588 33470.631802 33470.631802
Upvotes: 1