Skip to content

Instantly share code, notes, and snippets.

@yuyasugano
Created September 24, 2020 12:24
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 yuyasugano/31b021df282aee423ddfb0a1a5428882 to your computer and use it in GitHub Desktop.
Save yuyasugano/31b021df282aee423ddfb0a1a5428882 to your computer and use it in GitHub Desktop.
Pandas corr correlation for financial data
# calculate daily percent change and 21 days correlations with DawJones
df_ = df.pct_change().rolling(21)
correlation_change = rolling_pct_change.copy()
correlation_change['Apple'] = df_['DawJones'].corr(df['Apple'].pct_change().fillna(0))
correlation_change['Amazon'] = df_['DawJones'].corr(df['Amazon'].pct_change().fillna(0))
correlation_change['Facebook'] = df_['DawJones'].corr(df['Facebook'].pct_change().fillna(0))
correlation_change['US Bond'] = df_['DawJones'].corr(df['US Bond'].pct_change().fillna(0))
correlation_change.drop('DawJones', axis=1, inplace=True) # DawJones was the key, do remove this column
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment