I want to do a project with quantmod and compare Stock charts. As these Charts usually have different absolute values I wanted to normalize by dividing through the first value.
loading data
getSymbols(Symbols = "^IXIC", verbose = FALSE, warnings = TRUE, src = "yahoo", symbol.lookup = TRUE, auto.assign = getOption('getSymbols.auto.assign',TRUE))
IXIC_test1 <- IXIC/2
works well, as I got a time-series again
> head(IXIC_test1)
IXIC.Open IXIC.High IXIC.Low IXIC.Close IXIC.Volume IXIC.Adjusted
2007-01-03 1214.860 1227.310 1197.330 1211.580 1217640000 1211.580
2007-01-04 1211.910 1230.255 1206.875 1226.715 1052105000 1226.715
2007-01-05 1222.535 1222.535 1210.295 1217.125 1030180000 1217.125
2007-01-08 1217.625 1222.815 1210.565 1219.100 952810000 1219.100
2007-01-09 1221.630 1224.935 1211.780 1221.915 1072080000 1221.915
2007-01-10 1217.020 1230.670 1213.950 1229.665 1137105000 1229.665
But, when I try to use
IXIC_Norm <- IXIC/first(IXIC)
I get only one line
> head(IXIC_Norm)
IXIC.Open IXIC.High IXIC.Low IXIC.Close IXIC.Volume IXIC.Adjusted
2007-01-03 1 1 1 1 1 1
Could somebody please tell me, why this isn't gonna work?
You have to loop through the rows of matrix coredata(IXIC)
while performing normalization. The result you get as shown in the question is a consequence of data of first row is divided by itself. No subsequent rows are divided by the first row data as per expected output.
Try this: It will use the apply()
function to loop through the time series object and perform the normalization, then returns a matrix. The matrix is converted back to time series object using as.xts()
function.
library('xts')
as.xts(t(apply( IXIC, 1, function(x) x/first(IXIC))))
# IXIC.Open IXIC.High IXIC.Low IXIC.Close IXIC.Volume IXIC.Adjusted
# 2007-01-03 1.0000000 1.0000000 1.000000 1.000000 1.0000000 1.000000
# 2007-01-04 0.9975717 1.0023996 1.007972 1.012492 0.8640526 1.012492
# 2007-01-05 1.0063176 0.9961094 1.010828 1.004577 0.8460465 1.004577
# 2007-01-08 1.0022760 0.9963375 1.011054 1.006207 0.7825055 1.006207
# 2007-01-09 1.0055727 0.9980649 1.012069 1.008530 0.8804573 1.008530
# 2007-01-10 1.0017780 1.0027377 1.013881 1.014927 0.9338598 1.014927
Data:
library('xts')
df1 <- read.table(text='ds IXIC.Open IXIC.High IXIC.Low IXIC.Close IXIC.Volume IXIC.Adjusted
2007-01-03 1214.860 1227.310 1197.330 1211.580 1217640000 1211.580
2007-01-04 1211.910 1230.255 1206.875 1226.715 1052105000 1226.715
2007-01-05 1222.535 1222.535 1210.295 1217.125 1030180000 1217.125
2007-01-08 1217.625 1222.815 1210.565 1219.100 952810000 1219.100
2007-01-09 1221.630 1224.935 1211.780 1221.915 1072080000 1221.915
2007-01-10 1217.020 1230.670 1213.950 1229.665 1137105000 1229.665', header=TRUE)
rownames(df1) <- df1$ds
df1$ds <- NULL
IXIC <- xts(df1, order.by=as.Date(rownames(df1),"%Y-%m-%d"))