How do I change the date range displayed for my lineplot

Viewed 218
import yfinance as yf
import numpy as np
import pandas as pd
import seaborn as sns

SP = yf.Ticker("^GSPC").history(period='1y')
Gold = yf.Ticker("GC=F").history(period='1y')
Oil = yf.Ticker("CL=F").history(period='1y')

SP['Percent Change'] = SP['Close'].pct_change()*100
Gold['Percent Change'] = Gold['Close'].pct_change()*100
Oil['Percent Change'] = Oil['Close'].pct_change()*100

sns.lineplot(data=SP, x='Date', y=SP['Percent Change'])
sns.lineplot(data=Gold, x='Date', y=Gold['Percent Change'])
sns.lineplot(data=Oil, x='Date', y=Oil['Percent Change'])

When I use xlim(0,12) my graph starts showing data back from 1970. What would I use to restrict my X-axis values to specific date ranges I want?

1 Answers

I would take advantage of datetime index slicing df[start:end] which should be faster than plotting all the data and then changing the xlim:

import yfinance as yf
import numpy as np
import pandas as pd
import seaborn as sns

start = '2022-02-01'
end = '2022-04-01'

SP = yf.Ticker("^GSPC").history(period='1y')
Gold = yf.Ticker("GC=F").history(period='1y')
Oil = yf.Ticker("CL=F").history(period='1y')

SP['Percent Change'] = SP['Close'].pct_change()*100
Gold['Percent Change'] = Gold['Close'].pct_change()*100
Oil['Percent Change'] = Oil['Close'].pct_change()*100

sns.lineplot(data=SP.loc[start:end], x='Date', y='Percent Change')
sns.lineplot(data=Gold.loc[start:end], x='Date', y='Percent Change')
sns.lineplot(data=Oil.loc[start:end], x='Date', y='Percent Change')

Output

enter image description here

Related