繁体   English   中英

滤波器相关矩阵R

[英]Filter correlation matrix R

我有点想从相关矩阵中提取数据,我想提取高于0.8且低于0.99的值,因为我想排除正好为1的两只股票的相关性。

这是我的代码:

  #Test 

#load the packages
library(corrr)
library(ggplot2)
library(ggcorrplot)
library(dplyr)
library(quantmod)

#get the data needed
startdate <- "2001-01-03"

tickers <- c("MMM", "AA", "AXP", "T", "BAC")
portfolioprices <- NULL

for(ticker in tickers)
  portfolioprices <- cbind(portfolioprices, getSymbols(ticker, from=startdate, auto.assign=F)[,4])
colnames(portfolioprices) <- tickers

#check if there is nothing wrong with the data
print(portfolioprices)

#create a correlation matrix and plot it
correlations <- cor(as.matrix(portfolioprices))
correlations <- as.data.frame(correlations)
correlations
ggcorrplot(correlations, hc.order = TRUE, type = "lower",
           lab = TRUE)

作为输出,我得到:

           MMM          AA        AXP           T        BAC
MMM  1.0000000 -0.40325223  0.8772498  0.39019025 -0.2406640
AA  -0.4032522  1.00000000 -0.3029517  0.06347736  0.8383226
AXP  0.8772498 -0.30295171  1.0000000  0.41189453 -0.1304659
T    0.3901902  0.06347736  0.4118945  1.00000000 -0.1297723
BAC -0.2406640  0.83832262 -0.1304659 -0.12977234  1.0000000

在理想情况下,这是数据框,我将提取与最小值0.8正相关的数据。

我不知道我是否会完全以错误的方式进行操作,欢迎任何反馈!

编辑:

理想情况下,我希望数据像这样出来:

          MMM          AA        AXP           T        BAC
MMM                          0.8772498  
AA                                                  0.8383226
AXP  0.8772498 
T    
BAC               0.83832262 

仅过滤相关正值的地方。 删除不相同的值。

MMM:AXP = 0.8772498 BAC:AA = 0.8382262

如果有可能的话。

提前非常感谢您!

加载数据,使其他人轻松重现结果:

dat <- structure(list(MMM = c(1, -0.4032522, 0.8772498, 0.3901902, -0.240664
), AA = c(-0.40325223, 1, -0.30295171, 0.06347736, 0.83832262
), AXP = c(0.8772498, -0.3029517, 1, 0.4118945, -0.1304659), 
T = c(0.39019025, 0.06347736, 0.41189453, 1, -0.12977234), 
BAC = c(-0.240664, 0.8383226, -0.1304659, -0.1297723, 1)), 
.Names = c("MMM", "AA", "AXP", "T", "BAC"), 
class = "data.frame", 
row.names = c("MMM", "AA", "AXP", "T", "BAC"))

现在只需获取索引并在矩阵名称上使用子集即可。

index <- which(abs(dat) > .80 & abs(dat) < 1, # your criteria
               arr.ind = T) # the result of the which function is now in rows & columns
cbind.data.frame(stock1 = rownames(dat)[index[,1]], # get the row name 
                 stock2 = colnames(dat)[index[,2]]) # get the column name
#      stock1 stock2
#1    AXP    MMM
#2    BAC     AA
#3    MMM    AXP
#4     AA    BAC

**我假设您需要较高的绝对相关性(以确保可预测性),但是如果您只希望股票朝同一方向串联移动 ,则只需删除abs功能即可。

只需在代码末尾添加此行

correlations[correlations < 0.8 | correlations ==1] <- ""

希望能帮助到你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM