Skip to content

Instantly share code, notes, and snippets.

@stephenmm
Last active October 4, 2018 14:36
Show Gist options
  • Save stephenmm/e502fed5a09e6bbe0a59a14f7fc2724a to your computer and use it in GitHub Desktop.
Save stephenmm/e502fed5a09e6bbe0a59a14f7fc2724a to your computer and use it in GitHub Desktop.
Very simple example of working with python dataframes and matplotlib to observe some useful info.
import matplotlib.pyplot as plt
import pandas, os, re
import fix_yahoo_finance as yf # Might need to "> pip install fix_yahoo_finance"
stocks=["SPY","QQQ"] # Array of stocks to plot
bgn_date='2014-06-12' # Set the date range
end_date='2018-09-28'
fig,ax = plt.subplots()
for stock in stocks:
file="./%s_%s_%s.json"%( stock, re.sub('\W+','_',bgn_date), re.sub('\W+','_',end_date) )
if os.path.exists(file):
df=pandas.read_json(file) # Read in local copy
else:
df=yf.download(stock,bgn_date,end_date) # If never downloaded do it now
df.to_json(file) # and save a local copy
pcnt_chg=df.Close/df['Close'].iloc[0] # create a % change from first day closing ('Close') value
pcnt_chg.plot(ax=ax) # Add each stock % change to the plot (dataframes have instance of pyplot in them already)
ax.grid() # Turn on a grid
plt.show() # show the final plot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment