Upload correlation.py (#33)
Browse files- Upload correlation.py (aaea341736fae4aa54ccf7c880733f4c9873b7da)
Co-authored-by: Peter <phope@users.noreply.huggingface.co>
- correlation.py +31 -0
correlation.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import numpy as np
|
3 |
+
import datetime as dt
|
4 |
+
import pandas_datareader as pdr
|
5 |
+
|
6 |
+
# Read in Stock csv data and convert to have each Ticker as a column.
|
7 |
+
df = pd.read_csv('us-shareprices-daily.csv', sep=';')
|
8 |
+
stocks = df.pivot(index="Date", columns="Ticker", values="Adj. Close")
|
9 |
+
logRet = np.log(stocks/stocks.shift())
|
10 |
+
|
11 |
+
# Calculate the Correlation Coefficient for all Stocks
|
12 |
+
stocksCorr = logRet.corr()
|
13 |
+
|
14 |
+
# Output to csv
|
15 |
+
stocksCorr.to_csv (r'correlation_matrix.csv', index = None, header=True)
|
16 |
+
|
17 |
+
# Enter path of SimFin Data to convert to format for Calculations
|
18 |
+
def convert_simFin(path):
|
19 |
+
df = pd.read_csv(path, sep=';')
|
20 |
+
stocks = df.pivot(index="Date", columns="Ticker", values="Adj. Close")
|
21 |
+
return stocks
|
22 |
+
|
23 |
+
# Calculate Log returns of the Formatted Stocks
|
24 |
+
def log_of_returns(stocks):
|
25 |
+
log_returns = np.log(stocks/stocks.shift())
|
26 |
+
return log_returns
|
27 |
+
|
28 |
+
# Enter Log returns of Stocks to Calculate the Correlation Matrix.
|
29 |
+
def correlation_matrix(lr):
|
30 |
+
return lr.corr()
|
31 |
+
|