Skip to content

Instantly share code, notes, and snippets.

@mostlyinteresting
Last active November 10, 2019 23:02
Show Gist options
  • Save mostlyinteresting/5dc0513a47a27852ff14f9545430dddb to your computer and use it in GitHub Desktop.
Save mostlyinteresting/5dc0513a47a27852ff14f9545430dddb to your computer and use it in GitHub Desktop.
import os
import pandas as pd
import numpy as np
import yfinance as yf
import datetime as dt
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style = 'ticks', context = 'talk')
plt.style.use("dark_background")
pd.options.mode.chained_assignment = None
def barchart(df):
ax = sns.barplot(x = 'Year', y = 'Return', data = df)
vals = ax.get_yticks()
ax.set_yticklabels(['{:,.1%}'.format(x) for x in vals])
def findReplaceDate(x, dates):
diffs = (dates - x).days
diff0 = diffs[ diffs < 0 ].max()
return dates[ np.where(diffs == diff0)[0][0] ]
def singlesDayRet(prices, singlesDays, days, enter = 0):
returns = prices.pct_change(days)
dates = returns.index
datesInd = np.array([ np.where(dates == x)[0][0] + enter + days for x in singlesDays ])
singlesReturns = returns[ returns.index.isin(dates[datesInd]) ]
singlesReturns.columns = ['Return']
singlesReturns['Year'] = singlesReturns.index.year
return singlesReturns
if __name__ == '__main__':
ticker = 'BABA' #can change to any ticker
varName = 'Adj Close'
startDate = dt.datetime(year = 2010, month = 1, day = 1)
today = dt.datetime.now()
startDate = startDate.strftime('%Y-%m-%d')
endDate = today.strftime('%Y-%m-%d')
prices = yf.download(ticker, startDate, endDate)[[varName]]
prices.rename(columns = {varName:ticker}, inplace = True)
minYear = prices.index.min().year
maxYear = prices.index.max().year
if today <= dt.datetime(year = today.year, month = 11, day = 11):
maxYear -= 1
prices = prices [ prices.index.year <= maxYear ]
dates = prices.index
singlesDays = [ dt.datetime(year = x, month = 11, day = 11) for x in range(minYear,maxYear+1)]
singlesDaysAdd = [ x for x in singlesDays if x not in dates ]
replaceDays = [ findReplaceDate(x, dates) for x in singlesDaysAdd ]
prices.rename(index = dict(zip(replaceDays, singlesDaysAdd)), inplace = True)
singlesReturns5_0 = singlesDayRet(prices, singlesDays, days = 5, enter = 0)
barchart(singlesReturns5_0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment