Skip to content

Instantly share code, notes, and snippets.

@dharmatech
Created December 30, 2023 11:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dharmatech/9c6ccf3a735201106bc8bee550af3e2e to your computer and use it in GitHub Desktop.
Save dharmatech/9c6ccf3a735201106bc8bee550af3e2e to your computer and use it in GitHub Desktop.
import yfinance_download
from bokeh.plotting import figure, show
import bokeh.models
import bokeh.palettes
import bokeh.transform
df = yfinance_download.update_records('^GSPC', interval='1d')
# add column that shows the day of the year
df['day_of_year'] = df.index.dayofyear
# df.sort_values('day_of_year')
# add column for first open of the year
df['first_open_of_year'] = df.groupby(df.index.year)['Open'].transform('first')
# df[df.index.year == 2023]
df['year_roi'] = (df['Close'] / df['first_open_of_year'] - 1) * 100
# ----------------------------------------------------------------------
p = figure(title='S&P 500 Yearly ROI', x_axis_label='Day of Year', y_axis_label='%', x_axis_type='linear', sizing_mode='stretch_both')
p.line(x='day_of_year', y='year_roi', source=df[df.index.year == 2020], line_width=2, legend_label='2020', line_color='red')
p.line(x='day_of_year', y='year_roi', source=df[df.index.year == 2021], line_width=2, legend_label='2021', line_color='green')
p.line(x='day_of_year', y='year_roi', source=df[df.index.year == 2022], line_width=2, legend_label='2022', line_color='blue')
p.line(x='day_of_year', y='year_roi', source=df[df.index.year == 2023], line_width=2, legend_label='2023', line_color='orange')
p.xaxis.formatter = bokeh.models.NumeralTickFormatter(format='0')
p.yaxis.formatter = bokeh.models.NumeralTickFormatter(format='0')
p.add_tools(bokeh.models.HoverTool(
tooltips=[
('Day of Year', '@day_of_year'),
('%', '@year_roi{0.00}')
],
mode='vline'))
# add legend with toggle
p.legend.location = 'top_left'
p.legend.click_policy = 'hide'
show(p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment