import numpy as npimport mathimport cvxpy as cpimport pand.pdf

import numpy as np import math import cvxpy as cp import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import scipy.cluster.hierarchy as sch,random import warnings warnings.filterwarnings('ignore') plt.style.use('ggplot') dataset_log_returns = pd.read_csv('dataset.csv', index_col=0, parse_dates=True) # The function you need to write. # Input: cov: a dataframe containing the covariance matrix of stocks. # sortIx: a list containing the stocks names, ordered by the stage 1&2. # You can add any input argument if you need. # Output: allocation weight. You can output any data type as long as you can use it properly in Q3. def getRecBipart(cov,sortIx): # A sub function for the satge 1 and 2, called in the hrp_s12() def getQuasiDiag(link): link=link.astype(int) sortIx=pd.Series([link[-1,0],link[-1,1]]) numItems=link[-1,3] while sortIx.max()>=numItems: sortIx.index=range(0,sortIx.shape[0]*2,2) df0=sortIx[sortIx>=numItems] i=df0.index;j=df0.values-numItems sortIx[i]=link[j,0] df0=pd.Series(link[j,1],index=i+1) sortIx=sortIx.append(df0) sortIx=sortIx.sort_index() sortIx.index=range(sortIx.shape[0]) return sortIx.tolist() # Transform the correlation matrix to a distance matrix def correlDist(corr, n_stock): dist=((1-corr)/2.)**.5 for i in range(n_stock): dist.iloc[i,i] = 0 return dist # Plot the heatmap of the correlation matrix def plotCorrMatrix(path,corr,labels=None): # if labels isNone:labels=[] plt.pcolor(corr) plt.colorbar() plt.yticks(np.arange(.5,corr.shape[0]+.5),labels) plt.xticks(np.arange(.5,corr.shape[0]+.5),labels) plt.savefig(path) plt.clf();plt.close() return # Function for Stage 1 and 2 def hrp_s12(cov,stock_namelist, ifplot = False): n_stock = len(stock_namelist) #1) compute and plot correlation matrix v = np.diag(np.sqrt(1/np.diag(cov))) corr = np.dot(np.dot(v,cov), v) cov = pd.DataFrame(cov, columns = stock_namelist, index = stock_namelist) corr = pd.DataFrame(corr, columns = stock_namelist, index = stock_namelist) if (ifplot): plotCorrMatrix('HRP_corr0.png',corr,labels=corr.columns) #2) cluster dist=correlDist(corr,n_stock) link=sch.linkage(dist,'single') sortIx=getQuasiDiag(link) sortIx=corr.index[sortIx].tolist() # recover labels df0=corr.loc[sortIx,sortIx] # reorder if (ifplot): plotCorrMatrix('HRP_corr1.png',df0,labels=df0.columns) return sortIx def hrp_s3(cov,stock_namelist,sortIx): cov = pd.DataFrame(cov, columns = stock_namelist, index = stock_namelist) # Finish this function getRecBipart(cov,sortIx). hrp = getRecBipart(cov,sortIx) # Please print and check the "hrp" returned by the "getRecBipart(cov,sortIx)". # The order of stocks in "hrp" maybe follow the "sortIx", which is different from the "stock_namelist". # I suggest you to restore the order of "hrp" to "stock_namelist" here, # in order to avoid mistakes in Q3. # My "hrp" is a pandas.series, so this is what I do: hrp = hrp[stock_namelist] # It's OK if you want to finish this step in "getRecBipart()". # It's also Ok if you want to skip this step here .

import numpy as np
import math
import cvxpy as cp
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import scipy.cluster.hierarchy as sch,random
import warnings
warnings.filterwarnings('ignore')
plt.style.use('ggplot')
dataset_log_returns = pd.read_csv('dataset.csv', index_col=0, parse_dates=True)
# The function you need to write.
# Input: cov: a dataframe containing the covariance matrix of stocks.
# sortIx: a list containing the stocks names, ordered by the stage 1&2.
# You can add any input argument if you need.
# Output: allocation weight. You can output any data type as long as you can use it properly in
Q3.
def getRecBipart(cov,sortIx):
# A sub function for the satge 1 and 2, called in the hrp_s12()
def getQuasiDiag(link):
link=link.astype(int)
sortIx=pd.Series([link[-1,0],link[-1,1]])
numItems=link[-1,3]
while sortIx.max()>=numItems:
sortIx.index=range(0,sortIx.shape[0]*2,2)
df0=sortIx[sortIx>=numItems]
i=df0.index;j=df0.values-numItems
sortIx[i]=link[j,0]
df0=pd.Series(link[j,1],index=i+1)
sortIx=sortIx.append(df0)
sortIx=sortIx.sort_index()
sortIx.index=range(sortIx.shape[0])
return sortIx.tolist()
# Transform the correlation matrix to a distance matrix
def correlDist(corr, n_stock):
dist=((1-corr)/2.)**.5
for i in range(n_stock):
dist.iloc[i,i] = 0
return dist
# Plot the heatmap of the correlation matrix
def plotCorrMatrix(path,corr,labels=None):
#
if labels isNone:labels=[]
plt.pcolor(corr)
plt.colorbar()
plt.yticks(np.arange(.5,corr.shape[0]+.5),labels)
plt.xticks(np.arange(.5,corr.shape[0]+.5),labels)
plt.savefig(path)
plt.clf();plt.close()
return
# Function for Stage 1 and 2
def hrp_s12(cov,stock_namelist, ifplot = False):
n_stock = len(stock_namelist)
#1) compute and plot correlation matrix
v = np.diag(np.sqrt(1/np.diag(cov)))
corr = np.dot(np.dot(v,cov), v)
cov = pd.DataFrame(cov, columns = stock_namelist, index = stock_namelist)
corr = pd.DataFrame(corr, columns = stock_namelist, index = stock_namelist)
if (ifplot): plotCorrMatrix('HRP_corr0.png',corr,labels=corr.columns)
#2) cluster
dist=correlDist(corr,n_stock)
link=sch.linkage(dist,'single')
sortIx=getQuasiDiag(link)
sortIx=corr.index[sortIx].tolist() # recover labels
df0=corr.loc[sortIx,sortIx] # reorder
if (ifplot): plotCorrMatrix('HRP_corr1.png',df0,labels=df0.columns)
return sortIx
def hrp_s3(cov,stock_namelist,sortIx):
cov = pd.DataFrame(cov, columns = stock_namelist, index = stock_namelist)
# Finish this function getRecBipart(cov,sortIx).
hrp = getRecBipart(cov,sortIx)
# Please print and check the "hrp" returned by the "getRecBipart(cov,sortIx)".
# The order of stocks in "hrp" maybe follow the "sortIx", which is different from the
"stock_namelist".
# I suggest you to restore the order of "hrp" to "stock_namelist" here,
# in order to avoid mistakes in Q3.
# My "hrp" is a pandas.series, so this is what I do:
hrp = hrp[stock_namelist]
# It's OK if you want to finish this step in "getRecBipart()".
# It's also Ok if you want to skip this step here and deal with this small order problem in Q3.
return hrp
if __name__ == '__main__':
stock_namelist = dataset_log_returns.columns.values.tolist()
log_returns_1 = dataset_log_returns.loc['2015-01-06':'2015-05-29']
Sigma = np.cov(log_returns_1.T)
# Fill in the right argument to get the plots and new order of stocks:
sortIx = hrp_s12(Sigma, stock_namelist, ifplot= )
# After finish the function of stage 3, call it and print the final weight:
w_hrp = hrp_s3(Sigma, stock_namelist, sortIx)
print(w_hrp) Question 2: Hierarchical Risk Parity (25 points) Hierarchical Risk Parity (HRP)
combines the ideas of hierarchical clustering and inversevariance allocation. The algorithm
operates in three stages: tree clustering, quasidiagonalization and recursive bisection. The code
of stage 1 and 2 is provided in the attached file "Q2code.py". Stage 1&2 reorder the stocks. The
figures__ show the correlation matrix before and after Stage 1&2. Values of correlation matrix
are not changed. We just reorder the stocks so that the similar ones are next to each other and
form a quasi-diagonal matrix. Stage 3 will be illustrated with a small example. Suppose we have
6 stocks and after Stage 1 &2, the order of stocks are { "JNJ", "PG", "AMZN", "JPM", "V",
"FB"}. The steps of Stage 3 are as follows. 1.Initialization. Set the list of stocks
L={1,2,3,4,5,6}. The numbers of L correspond to the stocks. Assign a unit weight to all items:
wn=1,n=1,,6. 2.Bisection and weight allocation. 2.1 Bisect L into two subsets L1={1,2,3} and
L2={4,5,6}, which correspond to { "JNJ", "PG", "AMZN" } and { "JPM", "V", "FB" } 2.2
Calculate the following value for Li,i=1,2 : Vi=wiViwi,wi=diag(Vi)1/tr(diag(Vi)1), where Vi is
the covariance matrix of the Li,diag() is the diagonal operator and tr() is the trace operator. 2.3
Compute the split factor: =1V1+V2V1. 2.4 Re-scale allocations wn,nL1 by :wn=wn,n=1,2,3. Re-
scale allocations wn,nL2 by 1:wn=wn(1),n=4,5,6. 3.Continue the bisection and weight allocation
for L1 and L2 until all subsets have only 1 stock. In this example, we get subsets {1} and {2,3}
from L1. Then we apply step 2 to {1} and {2,3}, updating the allocations of stock {1} and {2,3}.
After this round, {1} has only one stock, so no more bisection can be done. But {2,3} need to be
bisected and update the allocations one more time. The same is for L2.
Plot the correlation matrix before and after the stage 1&2 with the code provided. (Use the
function "hrp_s12()".) Please read the notes in the attached code file carefully. The "hrp_s12()",
"hrp_s3()" and "getRecBipart() " are three functions you need to focus. You do not need to read
the code of other functions in detail. (b) Finish the code for Stage 3 (the function "getRecBipart
() "). Please read the notes in the attached code file carefully. (c) Print the final weight for log-
returns from "2015-01-06" to "2015-05-29" .

Recomendados

Codebaseimport numpy as npimport mathimport cvxpy as cpimpo.pdf por
Codebaseimport numpy as npimport mathimport cvxpy as cpimpo.pdfCodebaseimport numpy as npimport mathimport cvxpy as cpimpo.pdf
Codebaseimport numpy as npimport mathimport cvxpy as cpimpo.pdfsecunderbadtirumalgi
15 vistas4 diapositivas
Multinomial Logistic Regression with Apache Spark por
Multinomial Logistic Regression with Apache SparkMultinomial Logistic Regression with Apache Spark
Multinomial Logistic Regression with Apache SparkDB Tsai
12.9K vistas31 diapositivas
Alpine Spark Implementation - Technical por
Alpine Spark Implementation - TechnicalAlpine Spark Implementation - Technical
Alpine Spark Implementation - Technicalalpinedatalabs
10.4K vistas31 diapositivas
Array 31.8.2020 updated por
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updatedvrgokila
86 vistas17 diapositivas
Xgboost por
XgboostXgboost
XgboostVivian S. Zhang
46.5K vistas128 diapositivas
maXbox starter69 Machine Learning VII por
maXbox starter69 Machine Learning VIImaXbox starter69 Machine Learning VII
maXbox starter69 Machine Learning VIIMax Kleiner
117 vistas7 diapositivas

Más contenido relacionado

Similar a import numpy as npimport mathimport cvxpy as cpimport pand.pdf

Crypto cs36 39 por
Crypto cs36 39Crypto cs36 39
Crypto cs36 39sravanbabu
675 vistas30 diapositivas
Tutorial 2 por
Tutorial     2Tutorial     2
Tutorial 2Mohamed Yaser
486 vistas7 diapositivas
C++ Course - Lesson 2 por
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2Mohamed Ahmed
256 vistas13 diapositivas
can please someone help me with this assignment IT117 Recursion Comp.pdf por
can please someone help me with this assignment IT117 Recursion Comp.pdfcan please someone help me with this assignment IT117 Recursion Comp.pdf
can please someone help me with this assignment IT117 Recursion Comp.pdfFootageetoffe16
4 vistas2 diapositivas
Python High Level Functions_Ch 11.ppt por
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptAnishaJ7
30 vistas34 diapositivas
Introduction to python programming por
Introduction to python programmingIntroduction to python programming
Introduction to python programmingRakotoarison Louis Frederick
190 vistas17 diapositivas

Similar a import numpy as npimport mathimport cvxpy as cpimport pand.pdf(20)

Crypto cs36 39 por sravanbabu
Crypto cs36 39Crypto cs36 39
Crypto cs36 39
sravanbabu675 vistas
can please someone help me with this assignment IT117 Recursion Comp.pdf por Footageetoffe16
can please someone help me with this assignment IT117 Recursion Comp.pdfcan please someone help me with this assignment IT117 Recursion Comp.pdf
can please someone help me with this assignment IT117 Recursion Comp.pdf
Footageetoffe164 vistas
Python High Level Functions_Ch 11.ppt por AnishaJ7
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
AnishaJ730 vistas
Loops and functions in r por manikanta361
Loops and functions in rLoops and functions in r
Loops and functions in r
manikanta3611K vistas
Design and Analysis of algorithms por Dr. Rupa Ch
Design and Analysis of algorithmsDesign and Analysis of algorithms
Design and Analysis of algorithms
Dr. Rupa Ch2.1K vistas
Introduction to Algorithms por pppepito86
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
pppepito861K vistas
C interview question answer 2 por Amit Kapoor
C interview question answer 2C interview question answer 2
C interview question answer 2
Amit Kapoor22.4K vistas
C aptitude.2doc por Srikanth
C aptitude.2docC aptitude.2doc
C aptitude.2doc
Srikanth3.6K vistas
10 points Define a function called update_clusters_GMM tha.pdf por adamsmannequins1
10 points Define a function called update_clusters_GMM tha.pdf10 points Define a function called update_clusters_GMM tha.pdf
10 points Define a function called update_clusters_GMM tha.pdf
adamsmannequins19 vistas
2014-06-20 Multinomial Logistic Regression with Apache Spark por DB Tsai
2014-06-20 Multinomial Logistic Regression with Apache Spark2014-06-20 Multinomial Logistic Regression with Apache Spark
2014-06-20 Multinomial Logistic Regression with Apache Spark
DB Tsai11.5K vistas
def ddg(poultry) # Write your code here and edit the return .docx por simonithomas47935
def ddg(poultry)    # Write your code here and edit the return .docxdef ddg(poultry)    # Write your code here and edit the return .docx
def ddg(poultry) # Write your code here and edit the return .docx
Functional object por ruchijindal87
Functional objectFunctional object
Functional object
ruchijindal8724.6K vistas

Más de maheshkumar12354

in a super fast photonic switch that you are designing, each incomin.pdf por
in a super fast photonic switch that you are designing, each incomin.pdfin a super fast photonic switch that you are designing, each incomin.pdf
in a super fast photonic switch that you are designing, each incomin.pdfmaheshkumar12354
17 vistas1 diapositiva
In a lightdark bottle experiment to estimate primary productivity, .pdf por
In a lightdark bottle experiment to estimate primary productivity, .pdfIn a lightdark bottle experiment to estimate primary productivity, .pdf
In a lightdark bottle experiment to estimate primary productivity, .pdfmaheshkumar12354
9 vistas1 diapositiva
In a study on the effects of alcohol on eyewitness memory, participa.pdf por
In a study on the effects of alcohol on eyewitness memory, participa.pdfIn a study on the effects of alcohol on eyewitness memory, participa.pdf
In a study on the effects of alcohol on eyewitness memory, participa.pdfmaheshkumar12354
3 vistas1 diapositiva
In about 225-250 words, describe the most important thing you learne.pdf por
In about 225-250 words, describe the most important thing you learne.pdfIn about 225-250 words, describe the most important thing you learne.pdf
In about 225-250 words, describe the most important thing you learne.pdfmaheshkumar12354
2 vistas1 diapositiva
In a study of how close British drivers get to bicyclist when passin.pdf por
In a study of how close British drivers get to bicyclist when passin.pdfIn a study of how close British drivers get to bicyclist when passin.pdf
In a study of how close British drivers get to bicyclist when passin.pdfmaheshkumar12354
3 vistas1 diapositiva
In a single strand of DNA, the individual nucleotides are covalenty .pdf por
In a single strand of DNA, the individual nucleotides are covalenty .pdfIn a single strand of DNA, the individual nucleotides are covalenty .pdf
In a single strand of DNA, the individual nucleotides are covalenty .pdfmaheshkumar12354
2 vistas1 diapositiva

Más de maheshkumar12354(20)

in a super fast photonic switch that you are designing, each incomin.pdf por maheshkumar12354
in a super fast photonic switch that you are designing, each incomin.pdfin a super fast photonic switch that you are designing, each incomin.pdf
in a super fast photonic switch that you are designing, each incomin.pdf
maheshkumar1235417 vistas
In a lightdark bottle experiment to estimate primary productivity, .pdf por maheshkumar12354
In a lightdark bottle experiment to estimate primary productivity, .pdfIn a lightdark bottle experiment to estimate primary productivity, .pdf
In a lightdark bottle experiment to estimate primary productivity, .pdf
maheshkumar123549 vistas
In a study on the effects of alcohol on eyewitness memory, participa.pdf por maheshkumar12354
In a study on the effects of alcohol on eyewitness memory, participa.pdfIn a study on the effects of alcohol on eyewitness memory, participa.pdf
In a study on the effects of alcohol on eyewitness memory, participa.pdf
maheshkumar123543 vistas
In about 225-250 words, describe the most important thing you learne.pdf por maheshkumar12354
In about 225-250 words, describe the most important thing you learne.pdfIn about 225-250 words, describe the most important thing you learne.pdf
In about 225-250 words, describe the most important thing you learne.pdf
maheshkumar123542 vistas
In a study of how close British drivers get to bicyclist when passin.pdf por maheshkumar12354
In a study of how close British drivers get to bicyclist when passin.pdfIn a study of how close British drivers get to bicyclist when passin.pdf
In a study of how close British drivers get to bicyclist when passin.pdf
maheshkumar123543 vistas
In a single strand of DNA, the individual nucleotides are covalenty .pdf por maheshkumar12354
In a single strand of DNA, the individual nucleotides are covalenty .pdfIn a single strand of DNA, the individual nucleotides are covalenty .pdf
In a single strand of DNA, the individual nucleotides are covalenty .pdf
maheshkumar123542 vistas
In a recent year, the scores for the reading portion of a test were .pdf por maheshkumar12354
In a recent year, the scores for the reading portion of a test were .pdfIn a recent year, the scores for the reading portion of a test were .pdf
In a recent year, the scores for the reading portion of a test were .pdf
maheshkumar123546 vistas
In a survey of 1030 Canadian adults, 710 say that the energy situati.pdf por maheshkumar12354
In a survey of 1030 Canadian adults, 710 say that the energy situati.pdfIn a survey of 1030 Canadian adults, 710 say that the energy situati.pdf
In a survey of 1030 Canadian adults, 710 say that the energy situati.pdf
maheshkumar123542 vistas
In a neoclassical model without adjustment costs, firms will keep in.pdf por maheshkumar12354
In a neoclassical model without adjustment costs, firms will keep in.pdfIn a neoclassical model without adjustment costs, firms will keep in.pdf
In a neoclassical model without adjustment costs, firms will keep in.pdf
maheshkumar123542 vistas
In a recent study, the distances of certain raptor nests to the near.pdf por maheshkumar12354
In a recent study, the distances of certain raptor nests to the near.pdfIn a recent study, the distances of certain raptor nests to the near.pdf
In a recent study, the distances of certain raptor nests to the near.pdf
maheshkumar1235415 vistas
In a parallel universe there are 5 days in a week, no Saturday or Su.pdf por maheshkumar12354
In a parallel universe there are 5 days in a week, no Saturday or Su.pdfIn a parallel universe there are 5 days in a week, no Saturday or Su.pdf
In a parallel universe there are 5 days in a week, no Saturday or Su.pdf
maheshkumar123542 vistas
In a lottery ticket there are 7 numbers to be selected with replacem.pdf por maheshkumar12354
In a lottery ticket there are 7 numbers to be selected with replacem.pdfIn a lottery ticket there are 7 numbers to be selected with replacem.pdf
In a lottery ticket there are 7 numbers to be selected with replacem.pdf
maheshkumar123543 vistas
In a recent poll, the Gallup Organization found that 45 of adult Am.pdf por maheshkumar12354
In a recent poll, the Gallup Organization found that 45 of adult Am.pdfIn a recent poll, the Gallup Organization found that 45 of adult Am.pdf
In a recent poll, the Gallup Organization found that 45 of adult Am.pdf
maheshkumar1235416 vistas
In a certain species of plant, flowers occur in three colors blue, .pdf por maheshkumar12354
In a certain species of plant, flowers occur in three colors blue, .pdfIn a certain species of plant, flowers occur in three colors blue, .pdf
In a certain species of plant, flowers occur in three colors blue, .pdf
maheshkumar123545 vistas
In a management trainee program, 80 of the trainees are female, w.pdf por maheshkumar12354
In a management trainee program, 80 of the trainees are female, w.pdfIn a management trainee program, 80 of the trainees are female, w.pdf
In a management trainee program, 80 of the trainees are female, w.pdf
maheshkumar123549 vistas
In a backward_chaining function, it should call an apply function .pdf por maheshkumar12354
In a backward_chaining function, it should call an apply function .pdfIn a backward_chaining function, it should call an apply function .pdf
In a backward_chaining function, it should call an apply function .pdf
maheshkumar123542 vistas
In a certain instant lottery game, the chances of a win are stated a.pdf por maheshkumar12354
In a certain instant lottery game, the chances of a win are stated a.pdfIn a certain instant lottery game, the chances of a win are stated a.pdf
In a certain instant lottery game, the chances of a win are stated a.pdf
maheshkumar123543 vistas
In a bumper test, three types of autos were deliberately crashed int.pdf por maheshkumar12354
In a bumper test, three types of autos were deliberately crashed int.pdfIn a bumper test, three types of autos were deliberately crashed int.pdf
In a bumper test, three types of autos were deliberately crashed int.pdf
maheshkumar123547 vistas
In 2013, the Pew Research Foundation reported that 41 of U.S. adul.pdf por maheshkumar12354
In 2013, the Pew Research Foundation reported that 41 of U.S. adul.pdfIn 2013, the Pew Research Foundation reported that 41 of U.S. adul.pdf
In 2013, the Pew Research Foundation reported that 41 of U.S. adul.pdf
maheshkumar123545 vistas
In 2013, a research team published an article on the user post lengt.pdf por maheshkumar12354
In 2013, a research team published an article on the user post lengt.pdfIn 2013, a research team published an article on the user post lengt.pdf
In 2013, a research team published an article on the user post lengt.pdf
maheshkumar123543 vistas

Último

BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB... por
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...Nguyen Thanh Tu Collection
73 vistas113 diapositivas
Google solution challenge..pptx por
Google solution challenge..pptxGoogle solution challenge..pptx
Google solution challenge..pptxChitreshGyanani1
135 vistas18 diapositivas
Ch. 7 Political Participation and Elections.pptx por
Ch. 7 Political Participation and Elections.pptxCh. 7 Political Participation and Elections.pptx
Ch. 7 Political Participation and Elections.pptxRommel Regala
105 vistas11 diapositivas
Monthly Information Session for MV Asterix (November) por
Monthly Information Session for MV Asterix (November)Monthly Information Session for MV Asterix (November)
Monthly Information Session for MV Asterix (November)Esquimalt MFRC
58 vistas26 diapositivas
EIT-Digital_Spohrer_AI_Intro 20231128 v1.pptx por
EIT-Digital_Spohrer_AI_Intro 20231128 v1.pptxEIT-Digital_Spohrer_AI_Intro 20231128 v1.pptx
EIT-Digital_Spohrer_AI_Intro 20231128 v1.pptxISSIP
379 vistas50 diapositivas
unidad 3.pdf por
unidad 3.pdfunidad 3.pdf
unidad 3.pdfMarcosRodriguezUcedo
106 vistas38 diapositivas

Último(20)

BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB... por Nguyen Thanh Tu Collection
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
Ch. 7 Political Participation and Elections.pptx por Rommel Regala
Ch. 7 Political Participation and Elections.pptxCh. 7 Political Participation and Elections.pptx
Ch. 7 Political Participation and Elections.pptx
Rommel Regala105 vistas
Monthly Information Session for MV Asterix (November) por Esquimalt MFRC
Monthly Information Session for MV Asterix (November)Monthly Information Session for MV Asterix (November)
Monthly Information Session for MV Asterix (November)
Esquimalt MFRC58 vistas
EIT-Digital_Spohrer_AI_Intro 20231128 v1.pptx por ISSIP
EIT-Digital_Spohrer_AI_Intro 20231128 v1.pptxEIT-Digital_Spohrer_AI_Intro 20231128 v1.pptx
EIT-Digital_Spohrer_AI_Intro 20231128 v1.pptx
ISSIP379 vistas
When Sex Gets Complicated: Porn, Affairs, & Cybersex por Marlene Maheu
When Sex Gets Complicated: Porn, Affairs, & CybersexWhen Sex Gets Complicated: Porn, Affairs, & Cybersex
When Sex Gets Complicated: Porn, Affairs, & Cybersex
Marlene Maheu73 vistas
Narration lesson plan por TARIQ KHAN
Narration lesson planNarration lesson plan
Narration lesson plan
TARIQ KHAN59 vistas
Sociology KS5 por WestHatch
Sociology KS5Sociology KS5
Sociology KS5
WestHatch76 vistas
Psychology KS5 por WestHatch
Psychology KS5Psychology KS5
Psychology KS5
WestHatch103 vistas
7 NOVEL DRUG DELIVERY SYSTEM.pptx por Sachin Nitave
7 NOVEL DRUG DELIVERY SYSTEM.pptx7 NOVEL DRUG DELIVERY SYSTEM.pptx
7 NOVEL DRUG DELIVERY SYSTEM.pptx
Sachin Nitave61 vistas
Solar System and Galaxies.pptx por DrHafizKosar
Solar System and Galaxies.pptxSolar System and Galaxies.pptx
Solar System and Galaxies.pptx
DrHafizKosar94 vistas
ISO/IEC 27001 and ISO/IEC 27005: Managing AI Risks Effectively por PECB
ISO/IEC 27001 and ISO/IEC 27005: Managing AI Risks EffectivelyISO/IEC 27001 and ISO/IEC 27005: Managing AI Risks Effectively
ISO/IEC 27001 and ISO/IEC 27005: Managing AI Risks Effectively
PECB 598 vistas
Education and Diversity.pptx por DrHafizKosar
Education and Diversity.pptxEducation and Diversity.pptx
Education and Diversity.pptx
DrHafizKosar177 vistas
Drama KS5 Breakdown por WestHatch
Drama KS5 BreakdownDrama KS5 Breakdown
Drama KS5 Breakdown
WestHatch87 vistas
CUNY IT Picciano.pptx por apicciano
CUNY IT Picciano.pptxCUNY IT Picciano.pptx
CUNY IT Picciano.pptx
apicciano54 vistas
The Accursed House by Émile Gaboriau por DivyaSheta
The Accursed House  by Émile GaboriauThe Accursed House  by Émile Gaboriau
The Accursed House by Émile Gaboriau
DivyaSheta212 vistas

import numpy as npimport mathimport cvxpy as cpimport pand.pdf

  • 1. import numpy as np import math import cvxpy as cp import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import scipy.cluster.hierarchy as sch,random import warnings warnings.filterwarnings('ignore') plt.style.use('ggplot') dataset_log_returns = pd.read_csv('dataset.csv', index_col=0, parse_dates=True) # The function you need to write. # Input: cov: a dataframe containing the covariance matrix of stocks. # sortIx: a list containing the stocks names, ordered by the stage 1&2. # You can add any input argument if you need. # Output: allocation weight. You can output any data type as long as you can use it properly in Q3. def getRecBipart(cov,sortIx): # A sub function for the satge 1 and 2, called in the hrp_s12() def getQuasiDiag(link): link=link.astype(int) sortIx=pd.Series([link[-1,0],link[-1,1]]) numItems=link[-1,3] while sortIx.max()>=numItems: sortIx.index=range(0,sortIx.shape[0]*2,2) df0=sortIx[sortIx>=numItems] i=df0.index;j=df0.values-numItems sortIx[i]=link[j,0] df0=pd.Series(link[j,1],index=i+1) sortIx=sortIx.append(df0) sortIx=sortIx.sort_index()
  • 2. sortIx.index=range(sortIx.shape[0]) return sortIx.tolist() # Transform the correlation matrix to a distance matrix def correlDist(corr, n_stock): dist=((1-corr)/2.)**.5 for i in range(n_stock): dist.iloc[i,i] = 0 return dist # Plot the heatmap of the correlation matrix def plotCorrMatrix(path,corr,labels=None): # if labels isNone:labels=[] plt.pcolor(corr) plt.colorbar() plt.yticks(np.arange(.5,corr.shape[0]+.5),labels) plt.xticks(np.arange(.5,corr.shape[0]+.5),labels) plt.savefig(path) plt.clf();plt.close() return # Function for Stage 1 and 2 def hrp_s12(cov,stock_namelist, ifplot = False): n_stock = len(stock_namelist) #1) compute and plot correlation matrix v = np.diag(np.sqrt(1/np.diag(cov))) corr = np.dot(np.dot(v,cov), v) cov = pd.DataFrame(cov, columns = stock_namelist, index = stock_namelist) corr = pd.DataFrame(corr, columns = stock_namelist, index = stock_namelist) if (ifplot): plotCorrMatrix('HRP_corr0.png',corr,labels=corr.columns) #2) cluster dist=correlDist(corr,n_stock) link=sch.linkage(dist,'single') sortIx=getQuasiDiag(link)
  • 3. sortIx=corr.index[sortIx].tolist() # recover labels df0=corr.loc[sortIx,sortIx] # reorder if (ifplot): plotCorrMatrix('HRP_corr1.png',df0,labels=df0.columns) return sortIx def hrp_s3(cov,stock_namelist,sortIx): cov = pd.DataFrame(cov, columns = stock_namelist, index = stock_namelist) # Finish this function getRecBipart(cov,sortIx). hrp = getRecBipart(cov,sortIx) # Please print and check the "hrp" returned by the "getRecBipart(cov,sortIx)". # The order of stocks in "hrp" maybe follow the "sortIx", which is different from the "stock_namelist". # I suggest you to restore the order of "hrp" to "stock_namelist" here, # in order to avoid mistakes in Q3. # My "hrp" is a pandas.series, so this is what I do: hrp = hrp[stock_namelist] # It's OK if you want to finish this step in "getRecBipart()". # It's also Ok if you want to skip this step here and deal with this small order problem in Q3. return hrp if __name__ == '__main__': stock_namelist = dataset_log_returns.columns.values.tolist() log_returns_1 = dataset_log_returns.loc['2015-01-06':'2015-05-29'] Sigma = np.cov(log_returns_1.T) # Fill in the right argument to get the plots and new order of stocks: sortIx = hrp_s12(Sigma, stock_namelist, ifplot= ) # After finish the function of stage 3, call it and print the final weight: w_hrp = hrp_s3(Sigma, stock_namelist, sortIx) print(w_hrp) Question 2: Hierarchical Risk Parity (25 points) Hierarchical Risk Parity (HRP) combines the ideas of hierarchical clustering and inversevariance allocation. The algorithm operates in three stages: tree clustering, quasidiagonalization and recursive bisection. The code of stage 1 and 2 is provided in the attached file "Q2code.py". Stage 1&2 reorder the stocks. The figures__ show the correlation matrix before and after Stage 1&2. Values of correlation matrix are not changed. We just reorder the stocks so that the similar ones are next to each other and form a quasi-diagonal matrix. Stage 3 will be illustrated with a small example. Suppose we have
  • 4. 6 stocks and after Stage 1 &2, the order of stocks are { "JNJ", "PG", "AMZN", "JPM", "V", "FB"}. The steps of Stage 3 are as follows. 1.Initialization. Set the list of stocks L={1,2,3,4,5,6}. The numbers of L correspond to the stocks. Assign a unit weight to all items: wn=1,n=1,,6. 2.Bisection and weight allocation. 2.1 Bisect L into two subsets L1={1,2,3} and L2={4,5,6}, which correspond to { "JNJ", "PG", "AMZN" } and { "JPM", "V", "FB" } 2.2 Calculate the following value for Li,i=1,2 : Vi=wiViwi,wi=diag(Vi)1/tr(diag(Vi)1), where Vi is the covariance matrix of the Li,diag() is the diagonal operator and tr() is the trace operator. 2.3 Compute the split factor: =1V1+V2V1. 2.4 Re-scale allocations wn,nL1 by :wn=wn,n=1,2,3. Re- scale allocations wn,nL2 by 1:wn=wn(1),n=4,5,6. 3.Continue the bisection and weight allocation for L1 and L2 until all subsets have only 1 stock. In this example, we get subsets {1} and {2,3} from L1. Then we apply step 2 to {1} and {2,3}, updating the allocations of stock {1} and {2,3}. After this round, {1} has only one stock, so no more bisection can be done. But {2,3} need to be bisected and update the allocations one more time. The same is for L2. Plot the correlation matrix before and after the stage 1&2 with the code provided. (Use the function "hrp_s12()".) Please read the notes in the attached code file carefully. The "hrp_s12()", "hrp_s3()" and "getRecBipart() " are three functions you need to focus. You do not need to read the code of other functions in detail. (b) Finish the code for Stage 3 (the function "getRecBipart () "). Please read the notes in the attached code file carefully. (c) Print the final weight for log- returns from "2015-01-06" to "2015-05-29" .