Search code examples
pythonplotlyyfinance

How to create candlestick chart with data that came from yahoo finance?


I'm using yfinance and plotly libraries (python 2.7) to get Euro/USD data, and then create a candlestick chart.

This is my code to download data from yahoo finance:

import yfinance as yf

data = yf.download(tickers='EURUSD=X', period='1d', interval='30m')

sample output:

data.tail(10)


                               Open         High    Low Close   Adj Close     Volume
                 Datetime                       
2022-02-25 17:30:00+00:00   1.125239    1.125239    1.124101    1.124354    1.124354    0
2022-02-25 18:00:00+00:00   1.124480    1.125873    1.124480    1.125492    1.125492    0
2022-02-25 18:30:00+00:00   1.125619    1.126507    1.125619    1.126126    1.126126    0
2022-02-25 19:00:00+00:00   1.125999    1.126507    1.125492    1.126253    1.126253    0
2022-02-25 19:30:00+00:00   1.126634    1.126888    1.125366    1.126634    1.126634    0
2022-02-25 20:00:00+00:00   1.126888    1.127015    1.126126    1.126634    1.126634    0
2022-02-25 20:30:00+00:00   1.126507    1.127650    1.126507    1.127015    1.127015    0
2022-02-25 21:00:00+00:00   1.127142    1.127523    1.126761    1.127523    1.127523    0
2022-02-25 21:30:00+00:00   1.127650    1.127777    1.127396    1.127777    1.127777    0
2022-02-25 22:00:00+00:00   1.127142    1.127142    1.127142    1.127142    1.127142    0

My goal is to plot a candlestick style chart, I tried this code in order to create a chart:

date_time = data.select_dtypes(['datetime64'])
fig = go.Figure(data=[go.Candlestick(x=date_time,
                                     open=data['Open'],
                                     high=data['High'],
                                     low=data['Low'],
                                     close=data['Close'])])

fig.show()

The popup window showing nothing(a blank window):

Resulting figure

What am I doing wrong? and how can I do this?


Solution

  • as per @r-beginners comment. data.index.select_dtypes(['datetime64']) there are no columns of type date time. You want to use the index values for xaxis, hence whole line is not needed and just use index for xaxis.

    import yfinance as yf
    import plotly.graph_objects as go
    
    data = yf.download(tickers='EURUSD=X', period='1d', interval='30m')
    
    fig = go.Figure(data=[go.Candlestick(x=data.index,
                                         open=data['Open'],
                                         high=data['High'],
                                         low=data['Low'],
                                         close=data['Close'])])
    
    fig.show()