2
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?

edwrand
  • 21
  • 2
  • Does [How to set datetime xlim in seaborn](https://stackoverflow.com/questions/58057773/how-to-set-datetime-xlim-in-seaborn) work for you? – JohanC Mar 14 '22 at 20:52
  • Or [How do I change the range of the x-axis with datetimes in matplotlib?](https://stackoverflow.com/questions/21423158/how-do-i-change-the-range-of-the-x-axis-with-datetimes-in-matplotlib) – JohanC Mar 14 '22 at 20:53

1 Answers1

1

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

Chris
  • 15,819
  • 3
  • 24
  • 37
  • thank you this is perfect. Another question, if I do this with a large amount of days between start:end. The graph becomes very "cramped" together. How might I expand the size of the graph and apply more space between each x-axis value? – edwrand Mar 14 '22 at 21:37