Reputation: 2233
I would like to add an open price as a new row at the end of a "SPY" data frame that was produce using the quantmod package, I used the following code in order to rbind the new row but I got an error
# rm(list = ls()) # generally considered as bad manner in an MWE
require(quantmod)
options(scipen=999)
spy <- getSymbols(("SPY") , src = 'yahoo', from = '2016-01-01', auto.assign = T)
spy<-cbind(SPY)
tail(SPY)
SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted
2016-01-14 189.55 193.26 187.66 191.93 240795600 191.93
2016-01-15 186.77 188.76 185.52 187.81 324846400 187.81
2016-01-19 189.96 190.11 186.20 188.06 190196000 188.06
2016-01-20 185.03 187.50 181.02 185.65 280016900 185.65
2016-01-21 186.21 188.87 184.64 186.69 189174000 186.69
2016-01-22 189.78 190.76 188.88 190.52 163849600 190.52
I would like to insert new row manually into the spy dataset, so I tried to create a new xts object and than to use an rbind
function but I got an error after those lines :
q <- c("2016-01-25",100,200,200,200,200,200) # creating the data
colnames(q) <- colnames(SPY) # creating column names as in SPY
But I got an error:
Error in `colnames<-`(`*tmp*`, value = c("SPY.Open", "SPY.High", "SPY.Low", :
attempt to set 'colnames' on an object with less than two dimensions # creating the column names
How can I add this hand made row on the data frame's top ?
Upvotes: 2
Views: 39464
Reputation: 11
This problem is related to covariance matrix. The covariance matrix of returns should be non singular (positive definite or invertible). You can test if the covariance matrix is positive difinite using this code:
#Testing if the covariance matrix is non singular (invertible) install.packages("matrixcalc") library(matrixcalc) is.positive.definite(cov(YOUR-RETURN-MATRIX))
If the response is TRUE, it's ok!
If the response is FALSE, the problem can be solved by increasing the number of observations (rows) or reducing the number of assets (columns). The greater the number of observations (rows) per columns (assets), the greater the chance that covariance matrix be positive definite.
Upvotes: 0
Reputation:
You probably want:
q <- data.frame(100,200,200,200,200,200)
colnames(q) <- colnames(SPY)
q <- xts(q, as.Date("2016-01-26"))
# SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted
# 2016-01-26 100 200 200 200 200 200
class(SPY)
# [1] "xts" "zoo"
class(q)
# [1] "xts" "zoo"
tail(rbind(SPY, q))
# SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted
# 2016-01-19 189.96 190.11 186.20 188.06 190196000 188.06
# 2016-01-20 185.03 187.50 181.02 185.65 280016900 185.65
# 2016-01-21 186.21 188.87 184.64 186.69 189174000 186.69
# 2016-01-22 189.78 190.76 188.88 190.52 163849600 190.52
# 2016-01-25 189.92 190.15 187.41 187.64 122676200 187.64
# 2016-01-26 100.00 200.00 200.00 200.00 200 200.00
Upvotes: 2