<jupyter_start><jupyter_text>The MIT License (MIT)Copyright © 2021 <NAME>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.  Initialise<jupyter_code>import warnings
import math
warnings.filterwarnings(action='ignore', category=FutureWarning)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import pyplot
import pandas_datareader as web
from datetime import datetime
from dateutil.relativedelta import relativedelta
import seaborn as sns
import statistics as stat
s = datetime(2015, 11, 1)
mid = datetime(2018, 11, 1)
e = datetime(2021, 6, 28)
temp = pd.read_csv("constituents_csv.csv")
list1 = temp.Symbol
list1 = list1[:-5]
list1
def data(names):
    
    #yahoo download
    data = web.DataReader(names, 'yahoo', start=s, end=e)['Adj Close']

    return data
#df12 = data(list1)
#df12.to_csv("s&p500.csv")<jupyter_output><empty_output><jupyter_text>Filter  Data load and check if established<=2015<jupyter_code>temp = pd.read_csv("s&p500.csv")
temp = temp.dropna(axis='columns')
temp.set_index('Date',inplace = True, drop = True)
df12 = temp.loc[:mid.strftime('%Y-%m-%d'),:]
df122 = temp.loc[mid.strftime('%Y-%m-%d'):,:]
names = list(df12.columns)[1:]
df12
df13 = pd.DataFrame()
for i in names:
    df13[i] = df12[i].pct_change()
df13.drop(list(df13.index)[0],inplace=True)

df132 = pd.DataFrame()
for i in names:
    df132[i] = df122[i].pct_change()
df132.drop(list(df132.index)[0],inplace=True)<jupyter_output><empty_output><jupyter_text>Variance<jupyter_code>cut = 350
variances = []
df14 = df13.abs().copy()
for i in names:
    variances.append(stat.variance(list(df14.loc[:,i])))
variances = pd.Series(variances,index = names)
variances = variances.sort_values()
variances = variances.reset_index()
variances = variances.reset_index()
variances = variances.set_index('index')
variances = variances.sort_values('level_0')
variances = variances.iloc[:cut,:]
best = list(variances.index)
variances
bestv = best
# for i in best:
#     print(variances.loc[variances['Symbol'] == i])
vols = variances.copy()
vols[0] = (vols[0]*250).apply(np.sqrt)
vols<jupyter_output><empty_output><jupyter_text>Correlation<jupyter_code>corr = df13[best].corr(method='pearson')
for k in range(cut-10):
    
    corrs = pd.Series({i:corr[i].sum()/len(corr[i]) for i in best})
    max1 = corrs.idxmax()
    corr.drop(max1,axis = 0,inplace = True)
    corr.drop(max1,axis = 1,inplace = True)
    print(corr.shape,len(best))
    best.remove(max1)

corrs = pd.Series({i:corr[i].sum()/len(corr[i]) for i in best})
corrs = corrs.sort_values()
corrs
def heatmap(data,names):
    fig, ax = plt.subplots(figsize=(20,20))     
    corr = data[names].corr(method='pearson')
    mask = np.zeros_like(corr)
    mask[np.triu_indices_from(mask)] = True

    with sns.plotting_context("notebook",font_scale=1.3): # cbar_kws = {'anchor': ''
        plot =sns.heatmap(corr,fmt = '.2f',annot=True,ax=ax,mask=mask,vmin=-1, vmax=1,cmap="mako", cbar_kws = dict(use_gridspec=False,location="left")).set_title('Key Correlations between cryptocurrencies:')
        plt.show()
        plt.clf()
heatmap(df13,best)
corr = df13[best].corr(method='pearson')
corrs = pd.Series({i:corr[i].sum()/len(corr[i]) for i in best})
corrs = corrs.sort_values()
rec = [1/i for i in variances.loc[best,0]]
weights = [(i/sum(rec))*250000 for i in rec]
weights = pd.Series(data = weights, index = best)

quantity = {}
for i in best:
    
    quantity[i] = round(weights[i]/df12.loc[list(df12.index)[-1],i])
    
sum(corrs)/len(corrs), best, sum([math.sqrt(i*250) for i in variances.loc[best,0]])/len(variances.loc[best,0]), weights, quantity
x = 'PG'
print(math.sqrt(stat.variance(list(df14.loc[:,x]))*250))
cols = list(df13.columns)
cols.remove(x)
corr = [df13[x].corr(df13.loc[:,i],method='pearson') for i in bestv]
sum(corr)/len(corr)
#corrs = pd.Series({i:corr[i].sum()/len(corr[i]) for i in best})
x = 'EBAY'
print(math.sqrt(stat.variance(list(df14.loc[:,x]))*250))
cols = list(df13.columns)
cols.remove(x)
corr = [df13[x].corr(df13.loc[:,i],method='pearson') for i in bestv]
sum(corr)/len(corr)
#corrs = pd.Series({i:corr[i].sum()/len(corr[i]) for i in best})
best<jupyter_output><empty_output><jupyter_text>Jackknife<jupyter_code>index = list(df13.index)
dfc = pd.DataFrame()
dfv = pd.DataFrame()

for i in range(df13.shape[0]):
    print(i)
    temp = df13.copy()
    temp = temp.drop(index[i])
    
    corrs = temp.corr(method = 'pearson')
    corrs2 = []
    for j in range(len(best)-1):
        for k in range(j+1,len(best)):
            corrs2.append(corrs.iloc[k,j])

    variance = [stat.variance(temp[i]) for i in best]
    dfc[i] = corrs2
    dfv[i] = variance
    
# serc = [dfc.iloc[i,:] for i in range(len(best))]
# serv = [dfv.iloc[i,:] for i in range(len(best))]

# serc,serv

print(dfc)
print(dfv)
    
    
dfv
serc = [math.sqrt(stat.variance(dfc.iloc[i,:])*250) for i in range(dfc.shape[0])]
dfv = dfv*250
dfv = dfv.apply(np.sqrt)
serv = [math.sqrt(stat.variance(dfv.iloc[i,:])*250) for i in range(dfv.shape[0])]
serc,serv
sum(serc)/len(serc),sum(serv)/len(serv)
math.sqrt(variances.loc[best[0],0]*250)-math.sqrt(variances.loc[best[5],0]*250)
dfv.head()
math.sqrt(variances.loc[best[0],0]*250)-math.sqrt(variances.loc[best[1],0]*250)<jupyter_output><empty_output><jupyter_text>Check<jupyter_code>bests = [['SO', 'ED', 'MCD', 'EVRG', 'DIS', 'LMT', 'PSA', 'MDT', 'PBCT', 'TJX'],
         ['SO', 'EVRG', 'EXR', 'CBOE', 'CHRW', 'RE', 'IQV', 'SLB', 'AXP', 'STZ'],
         ['SO', 'EVRG', 'CBOE', 'RE', 'HUM', 'ISRG', 'MKTX', 'GE', 'AZO', 'CPB'],
         ['SO', 'CBOE', 'RE', 'CPB', 'UHS', 'DPZ', 'TGT', 'AMCR', 'HAL', 'BMY'],
        ['ED', 'CBOE', 'MKTX', 'CPB', 'TGT', 'AMCR', 'BMY', 'HAS', 'EOG', 'EBAY']]
cuts=  [100,200,300,350,400]
#Cut 
#return
# df132['Date'] = list(df122.index)[1:]
# df132.set_index('Date',inplace = True, drop = True)
# temp = {i:'%'+i for i in best}
# temp = df132.loc[:,best].rename(columns = temp)


# df142 = df122.loc[list(df122.index)[1:],best].copy().join(temp,on = 'Date')
# #variance
# for i in best:
#     df142['v'+i] = df142['%'+i].rolling(7).apply(lambda x: stat.variance(x))
# df142.drop(list(df142.index)[:7],inplace = True)

# for name in names:
#     df142['check '+name] = np.nan
#     df142['w'+name] = np.nan
#     df142['b'+name] = np.nan
#     df142['n '+name] = np.nan
        
# df142['total'] = np.nan

# df142
for j in range(len(cuts)):
    cut = cuts[j]
    variances = []
    df14 = df13.abs().copy()
    for i in names:
        variances.append(stat.variance(list(df14.loc[:,i])))
    variances = pd.Series(variances,index = names)
    variances = variances.sort_values()
    variances = variances.reset_index()
    variances = variances.reset_index()
    variances = variances.set_index('index')
    variances = variances.sort_values('level_0')
    variances = variances.iloc[:cut,:]
    
    best = bests[j]
    
    rec = [1/i for i in variances.loc[best,0]]
    weights = [(i/sum(rec))*250000 for i in rec]
    weights = pd.Series(data = weights, index = best)
    
    
    quantity = {}
    for i in best:
        quantity[i] = round(weights[i]/df12.loc[list(df12.index)[-1],i])
    
    df122[f'total{j}'] = np.zeros
    for i in best:
        df122[f'total{j}'] = quantity[i]*df122[i]
    
    temp = stat.variance(df122[f'total{j}'].pct_change().abs().drop(list(df122.index)[0]))
    
    temp = math.sqrt(temp*250)
    print(temp)
  
cut = 400
variances = []
df142 = df132.abs().copy()
for i in names:
    variances.append(stat.variance(list(df142.loc[:,i])))
variances = pd.Series(variances,index = names)
variances = variances.sort_values()
variances = variances.reset_index()
variances = variances.reset_index()
variances = variances.set_index('index')
variances = variances.sort_values('level_0')
variances = variances.iloc[:cut,:]
temp = variances[0]
temp = temp.sum()/len(temp)
temp = math.sqrt(temp*250)
print(temp)

#for j in range(100,400,100):
#     sns.lineplot(x=list(df122.index), y=df122[f'total{j}'])
#     plt.show()
#     plt.clf()
avg = []
for j in range(len(cuts)):
    df122[f'%{j}'] = df122[f'total{j}'].pct_change()
    avg.append((df122[f'%{j}'].sum()/len(df122[f'%{j}']))*250)
sum(avg)/len(avg)
    
    
returns = []
for i in names:
    returns.append(df122[i].pct_change().sum()/df122.shape[0])
(sum(returns)/len(names))*250
df122.columns<jupyter_output><empty_output><jupyter_text>10K<jupyter_code>temp = pd.read_csv("constituents_csv.csv")
temp<jupyter_output><empty_output><jupyter_text>MCHP<jupyter_code>df12['%TSM'] = data(['TSM'])
index = list(df12.index)
for i in list1:
    x = df12[i].pct_change()
    x = x.drop(index[0])
    print(i,df12.loc[index[0:],'%TSM'].corr(x,method = 'pearson'))
newdf = pd.read_csv('s&p500.csv')
newdf = newdf.set_index('Date',drop=True)
supcomp = 'MCHP'
temp = data([supcomp])
temp = temp.drop(list(temp.index)[-1])
newdf['%'+supcomp] = list(temp[supcomp].pct_change())
newdf
corrs = []
for i in best:
    x = newdf[i].pct_change()
    x = x.drop(index[0])
    corrs.append(newdf.loc[index[1:],'%'+supcomp].corr(x,method = 'pearson'))
corrs = pd.Series(data = corrs, index = best)
corrs.sort_values(ascending = False)
sum(corrs)/len(corrs)
math.sqrt(stat.variance(newdf.loc[index[1]:,'%'+supcomp])*250)
newdf['%'+supcomp]<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.18196897258269099, 'fraction_numerical': 0.038540345399551174, 'mean_word_length': 4.843785632839225, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 34, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '629003', 'license': 'MIT', 'n_tokens_mistral': 4271, 'n_tokens_neox': 3942, 'n_words': 807, 'path': 'diversification.ipynb', 'repo_name': 'pald22/Investment-Portfolio-Management', 'size': '10257'}