How to Build stock comparison line chart with dynamic date range via Python (Plotly & Pandas)?
You might be familiar with Google's interactive stock comparison chart if you are following the stock market. This is a perfect tool to compare the performance and trend across multiple targets. Sometimes you can also leverage this to discover leading/ lagging indicators and relationships so that you can make investment decisions accordingly. However, the users were only provided with very limited time frames ranging from 1D to 5Y or Max so it is really hard to focus on the specific time frame in the past. Take Micron vs Lam Research as an example, it is difficult for users to draw a correlation during 2000 to 2010.
We are going to discuss how to customize the chart by using Plotly, Pandas and yfinance in Google Colab Notebook.
Step 0: Install all required packages.
pip install plotly
pip install pandas
pip install yfinance
Step 1: Import packages.
import pandas as pd
import yfinance as yf
import plotly.express as px
Step 2: Load Stock Ticker, start and end date and select close price.
df = yf.download('Stock Ticker',
start='Start date',
end='End date',
progress=False,
auto_adjust=True)
df = df['Close']
Step 3: Divide all numbers by the number in first row.
df.div(df.iloc[0])
Step 4: Plot it.
fig = px.line(df.div(df.iloc[0]))
fig.show()
As you can see 2005–2006 is showing very different trend than 2006–2007, which can’t be present in Google’s.
2005–2006
2006–2007
Full scripts for 2005–2006.
import pandas as pd
import yfinance as yf
import plotly.express as px
df = yf.download('LRCX MU',
start='2005-01-01',
end='2006-01-01',
progress=False,
auto_adjust=True)
df = df['Close']
df.div(df.iloc[0])
fig = px.line(df.div(df.iloc[0]))
fig.show()
More related articles:
Data Viz
How to Create X-days Moving Average Chart in stock market?
How to Build a Word Collocation Network Graph via Python
Stock Market
How to Import Stock Information for All Tickers in the US and TW Market into SQLite via Python Colab?
How to Calculate PE ratio for ETFs via Python in Colab - QQQ
How to Understand the level of cost (moving average) for each holding of ETF-QQQ?
Thank you! If you want to support Informula, you can buy us a coffee here :)