I am trying to plot a simple Candlestick chart from OHLCV data retrieved by yfinance.
This is my code:
import yfinance as yf
import pandas as pd
import plotly.graph_objects as go
from datetime import datetime
tf = '1d' # Time frame (daily)
asset = 'AAPL' # Asset ticker (e.g., Apple)
start = '2019-01-01' # Start date
end = datetime.now().strftime('%Y-%m-%d') # End date is current date
df = yf.download(asset, start=start, end=end, interval=tf)
df['pct_chg'] = df['Close'].pct_change() * 100
df.index.name = 'timestamp'
# now plot the chart
hover_text = [f"Open: {open}<br>Close: {close}<br>Pct: {pct_chg:.2f}%" for open, close, pct_chg in zip(df['Open'], df['Close'], df['pct_chg'])]
# Create a candlestick chart using Plotly
fig = go.Figure(data=[go.Candlestick(
x=df.index,
open=df['Open'],
high=df['High'],
low=df['Low'],
close=df['Close'],
hovertext=hover_text,
hoverinfo='text'
)])
# Update layout
fig.update_layout(
title='Candlestick chart',
xaxis_title='Date',
yaxis_title='Price',
xaxis_rangeslider_visible=False,
template='plotly_dark')
# Show the plot
fig.show()
Data is correctly downloaded. However the graph does not show any candle.
Actually Pandas will use MultiIndexing if you put data downloaded from yahoo finance into a dataframe.
display(df) gives:
To remove the Ticker column multi-index which is not needed, just drop it:
df.columns = df.columns.droplevel(1)
Then you get a regular dataframe and can plot it the way you did it: