我有点想从相关矩阵中提取数据,我想提取高于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
如果完全有可能。
非常感谢您!
答案 0 :(得分:1)
加载数据,以便其他人轻松复制结果:
Enter the string: Hi
The reversed string is: ii
现在只需获取索引并在矩阵名称上使用子集即可。
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
功能。
答案 1 :(得分:1)
只需在代码末尾添加此行
correlations[correlations < 0.8 | correlations ==1] <- ""
希望有帮助!