Skip to content

Instantly share code, notes, and snippets.

@dharmatech
Created December 30, 2023 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dharmatech/cc6e25047868405c98e41e6c9cde0dea to your computer and use it in GitHub Desktop.
Save dharmatech/cc6e25047868405c98e41e6c9cde0dea to your computer and use it in GitHub Desktop.
import yfinance_download
spx = yfinance_download.update_records('^GSPC', interval='1wk')
ndq = yfinance_download.update_records('^IXIC', interval='1wk')
# ndq = yfinance_download.update_records('^NDX', interval='1wk')
# ----------------------------------------------
df = spx['Close'].to_frame()
df['Close_diff_1'] = df['Close'].diff(1)
df['is_positive'] = df['Close_diff_1'] > 0
spx = df
# ----------------------------------------------
df = ndq['Close'].to_frame()
df['Close_diff_1'] = df['Close'].diff(1)
df['is_positive'] = df['Close_diff_1'] > 0
ndq = df
# ----------------------------------------------
df = pd.merge(spx, ndq, left_index=True, right_index=True, suffixes=('_spx', '_ndq'))
df['is_positive'] = df['is_positive_spx'] & df['is_positive_ndq']
df['switch'] = (df['is_positive'] != df['is_positive'].shift(1))
df['group'] = df['switch'].cumsum()
df['group_is_positive_cumsum'] = df.groupby('group')['is_positive'].cumsum()
df['weeks_in_a_row_up'] = df['group_is_positive_cumsum'].where(df['is_positive'], 0)
tmp = df.groupby('group').tail(1)
tmp[tmp['weeks_in_a_row_up'] >= 6][['Close_spx', 'Close_ndq', 'weeks_in_a_row_up']]
tmp[tmp['weeks_in_a_row_up'] >= 6]['weeks_in_a_row_up']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment