The following script plots 2 charts side by side:
require(xts)
par(mfrow=c(1,2))
XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))
XTS2 <- XTS1 ^ 0.2
plot(XTS1)
plot(XTS2)
The following script fails to plot 2 charts side by side:
require(PerformanceAnalytics)
require(xts)
par(mfrow=c(1,2))
XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))
XTS2 <- XTS1 ^ 0.2
charts.PerformanceSummary(XTS1)
charts.PerformanceSummary(XTS2)
Would anyone know how to get the latter script to plot 2 charts side by side?
I would like to avoid using another package if possible. Thanks.
chart.PerformanceSummary is really just a wrapper to several charts.
You could do this, and extend it to any number of symbols horizontally if you wish (more than 2 symbols if you wanted):
par(mfrow=c(3,2))
# First row
chart.CumReturns(XTS1, ylab = "Cumulative Return", main = "give me a title")
chart.CumReturns(XTS2, ylab = "Cumulative Return", main = "give me a title2")
# second row
chart.BarVaR(XTS1)
chart.BarVaR(XTS2)
# third row
chart.Drawdown(XTS1, main = "DD title", ylab = "Drawdown",
)
chart.Drawdown(XTS2, main = "", ylab = "Drawdown",
)
You need to add the appropriate parameters to each plot for things like colour and titles (leaving that to you), but you have the flexibility of adding any charts from the wonderful xts, quantmod, performanceAnalytics packages (and others).
Related
This is my code, it works so far, except that the legend does not appear in the plot:
plot(norm_prices_daily[,1], col = "blue",lwd=3,grid.col = NA, ylim = c(0,3))
lines(norm_prices_daily[,2],lwd=3, col = "dark green")
legend("bottomright",legend=c("Stock 1","Stock 2"),col = c("blue","dark green"))
norm_prices_daily is a zoo object with two columns and 182 rows.
Here is part of the data. Output from dput(head(norm_prices_daily[,1],20)):
structure(c(1, 0.9929401294387, 0.99644855697716, 0.9936552740678,
0.998526620668352, 1.00517207744161, 1.00230213170477, 1.00929440707496,
1.00776579745506, 1.0096505179963, 1.01809781273736, 1.02202987149226,
1.01931947115634, 1.01961413204347, 1.0207774879027, 1.01154745364837,
0.99563509229331, 1.0056447937894, 1.00477302623885, 1.00792234548049
), class = c("xts", "zoo"), .indexCLASS = "Date", .indexTZ = "UTC", tclass = "Date", tzone = "UTC", src = "yahoo", updated = structure(1600533381.35332, class = c("POSIXct",
"POSIXt")), index = structure(c(1577923200, 1578009600, 1578268800,
1578355200, 1578441600, 1578528000, 1578614400, 1578873600, 1578960000,
1579046400, 1579132800, 1579219200, 1579564800, 1579651200, 1579737600,
1579824000, 1580083200, 1580169600, 1580256000, 1580342400), tzone = "UTC", tclass = "Date"), .Dim = c(20L,
1L), .Dimnames = list(NULL, "^GSPC"))
I have tried different options for the position of the legend, such as specific x and y coordinates, because I suspected that the legend is there but just too low or something. But that does not seem to the issue.
You haven't specified the kind of line you want in the legend, but it should still print the labels. Here is a slight modification of the first example on the manual page for print.zoo to make it more comparable to yours:
x.Date <- as.Date(paste(2003, 02, c(1, 3, 7, 9, 14), sep = "-"))
set.seed(42)
x <- zoo(cbind(rnorm(5), rnorm(5, sd= 0.2)), x.Date)
plot(x[, 1], col = "blue")
lines(x[, 2], col = "dark green")
legend("bottomright", legend=c("Stock 1","Stock 2"), lty=1, col = c("blue","dark green"))
Plotting an xts should be really easy, but I can't seem to get the xlab, and ylab to work..
ylab="Price"
xlab="Date"
plot(x = basket[, 1], lty="dotted", xlab = xlab, ylab = ylab, col = "mediumblue", lwd = 2)
title("Cumulative")
This will plot the figure, but without any labels on the x- and y-axis.
There must be an easy solution to this. The plot looks as it should besides that issue. I have tried with xts.plot, zoo.plot, xyplot but none seem to do the trick.
Data sample
structure(c(1, 1.01463414634146, 0.926829268292683, 0.970731707317073,
0.953658536585366, 1, 0.998263888888889, 1.01159722222222, 1.05076388888889,
1.05034722222222, 1, 1.00178890876565, 0.985688729874776, 1.04293381037567,
1.04651162790698, 1, 0.976675478152698, 0.990359197636448, 1.06515316436013,
1.04571606282071), class = c("xts", "zoo"), index = structure(c(946944000,
947030400, 947116800, 947203200, 947462400), tzone = "UTC", tclass = "Date"), .Dim = 5:4, .Dimnames = list(
NULL, c("new.close", "new.close.1", "new.close.2", "new.close.3"
)))
It is plot.zoo, not zoo.plot. These all work for me:
library(xts)
plot(as.zoo(basket[, 1]), xlab = "X", ylab = "Y")
plot.zoo(basket[, 1], xlab = "X", ylab = "Y")
library(lattice)
xyplot(basket[, 1], xlab = "X", ylab = "Y")
library(ggplot2)
autoplot(basket[, 1]) + xlab("X") + ylab("Y")
Note
basket <-
structure(c(1, 1.01463414634146, 0.926829268292683, 0.970731707317073,
0.953658536585366, 1, 0.998263888888889, 1.01159722222222, 1.05076388888889,
1.05034722222222, 1, 1.00178890876565, 0.985688729874776, 1.04293381037567,
1.04651162790698, 1, 0.976675478152698, 0.990359197636448, 1.06515316436013,
1.04571606282071), class = c("xts", "zoo"), index = structure(c(946944000,
947030400, 947116800, 947203200, 947462400), tzone = "UTC", tclass = "Date"), .Dim = 5:4, .Dimnames = list(
NULL, c("new.close", "new.close.1", "new.close.2", "new.close.3"
)))
I know this might not be exactly what you had in mind, but it gets the job done. Plus, you get to work with ggplot2 which way better than the standard plotting system. In addition, I am using ggfortify which extends ggplot() capabilities to handle time series.
library(xts)
library(zoo)
library(ggfortify)
library(ggplot2)
myts = structure(
c(1, 1.01463414634146, 0.926829268292683, 0.970731707317073,
0.953658536585366, 1, 0.998263888888889, 1.01159722222222, 1.05076388888889,
1.05034722222222, 1, 1.00178890876565, 0.985688729874776, 1.04293381037567,
1.04651162790698, 1, 0.976675478152698, 0.990359197636448, 1.06515316436013,
1.04571606282071),
class = c("xts", "zoo"),
index = structure(c(946944000, 947030400,
947116800, 947203200,
947462400),
tzone = "UTC",
tclass = "Date"),
.Dim = 5:4, .Dimnames = list(NULL,
c("new.close",
"new.close.1",
"new.close.2",
"new.close.3" ) )
)
autoplot( myts[ , 1], xlab = "Date", ylab = "Price" )
Created on 2020-05-05 by the reprex package (v0.3.0)
There are multiple XTS objects. Each one contains one column only (of prices).
The objects may be of different lengths. I want to merge them by index.
I can merge two XTS objects with merge.xts. But I want to merge multiple
(with one function, without repeating merging process multiple times).
So I applied the approach recommended here. It works. Just one issue: it merges all data into one column, rather than placing each XTS object to be merged into its own column. e.g. In the reproducible example, the desired end result is for XTSM to have 3 columns.
How can that be achieved? Thank you.
library('xts')
#Data
XTS1 <- structure(c(125.26, 125.14, 125.21, 125.26, 125.21, 125.26, 125.24, 125.22, 125.3, 125.32, 125.38, 125.38, 125.29, 125.26, 125.3, 125.25, 125.29, 125.37, 125.21, 125.3, 125.25, 125.24, 125.21, 125.24, 125.24, 125.26, 125.23, 125.23), class = c("xts", "zoo"), .indexCLASS = c("POSIXct", "POSIXt"), tclass = c("POSIXct", "POSIXt"), .indexTZ = "", tzone = "", .CLASS = "double", index = structure(c(1403537400, 1403538300, 1403539200, 1403540100, 1403541000, 1403541900, 1403542800, 1403543700, 1403544600, 1403545500, 1403546400, 1403547300, 1403548200, 1403549100, 1403550000, 1403550900, 1403551800, 1403552700, 1403553600, 1403554500, 1403555400, 1403556300, 1403557200, 1403560800, 1403561700, 1403562600, 1403563500, 1403564400), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(28L, 1L))
XTS2 <- structure(c(1867, 1867, 1868.5, 1868.75, 1868.75, 1868.75, 1868.25, 1867.25, 1867.5, 1867.75, 1868, 1868.25, 1868.25, 1868.75, 1868, 1868.5, 1869, 1869.75, 1868.75, 1868.5, 1868.25, 1867.5, 1867, 1866.75, 1866.75, 1867, 1867.5), class = c("xts", "zoo"), .indexCLASS = c("POSIXct", "POSIXt"), tclass = c("POSIXct", "POSIXt"), .indexTZ = "", tzone = "", .CLASS = "double", index = structure(c(1403537400, 1403538300, 1403539200, 1403540100, 1403541000, 1403541900, 1403542800, 1403543700, 1403544600, 1403545500, 1403546400, 1403547300, 1403548200, 1403549100, 1403550000, 1403550900, 1403551800, 1403552700, 1403553600, 1403555400, 1403556300, 1403557200, 1403560800, 1403561700, 1403562600, 1403563500, 1403564400), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(27L, 1L))
XTS3 <- structure(c(1867, 1867, 1868.5, 1868.75, 1868.75, 1868.75, 1868.25, 1867.25, 1867.5, 1867.75, 1868, 1868.25, 1868.25, 1868.75, 1868, 1868.5, 1869, 1869.75, 1868.75, 1868.5, 1868.25, 1867.5, 1867, 1866.75, 1866.75, 1867, 1867.5), class = c("xts", "zoo"), .indexCLASS = c("POSIXct", "POSIXt"), tclass = c("POSIXct", "POSIXt"), .indexTZ = "", tzone = "", .CLASS = "double", index = structure(c(1403537400, 1403538300, 1403539200, 1403540100, 1403541000, 1403541900, 1403542800, 1403543700, 1403544600, 1403545500, 1403546400, 1403547300, 1403548200, 1403549100, 1403550000, 1403550900, 1403551800, 1403552700, 1403553600, 1403555400, 1403556300, 1403557200, 1403560800, 1403561700, 1403562600, 1403563500, 1403564400), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(27L, 1L))
#Following code merges 2 xts objects into a 2 column xts
XTSM <- merge(XTS1,XTS2, all=TRUE)
#Following code merges multiple xts objects into a 1 column xts
XTSlist <- list(XTS1, XTS2, XTS3)
do.call.rbind <- function(lst) {
while(length(lst) > 1) {
idxlst <- seq(from=1, to=length(lst), by=2)
lst <- lapply(idxlst, function(i) {
if(i==length(lst)) { return(lst[[i]]) }
return(rbind(lst[[i]], lst[[i+1]]))
})
}
lst[[1]]
}
XTSM <- do.call.rbind (XTSlist)
Joshua answer the question in the comments. Posting solution for the sake of having the Q answered. It is as simple as this:
XTSM.T <- merge(XTS1,XTS2,XTS3, all=TRUE)
or
XTSM.F <- merge(XTS1,XTS2,XTS3, all=FALSE)
I am trying to estimate overnight returns for many stocks using a for loop and store it in a dataframe with stock names as column names. The trade has raw intraday data and trade2 has cleaned intraday data. list.namess has stock names. This is my code:
require(xts)
require(highfrequency)
OvernightRet<-list()
list.namess<- list.files(pattern="*.IS Equity")
list.namess<- list.namess[2]
for(Q in 1:length(list.namess)){
trade<-readRDS(list.namess[Q])
trade<-xts(trade[,-1], order.by = trade[,1])
colnames(trade)[c(1,2)]<-c("PRICE", "SIZE")
#Unduplicating
trade2<-do.call(rbind, lapply(split(trade,"days"), mergeTradesSameTimestamp))
trade2<-trade2[,1]
fun.first= function(x) first(x)
fun.last= function(x) last(x)
A=do.call(rbind, lapply(split(trade2, "days"), FUN=fun.first))
B=do.call(rbind, lapply(split(trade2, "days"), FUN=fun.last))
OvernightRetA <- (as.numeric(A)-as.numeric(lag.xts(B)))/as.numeric(lag.xts(B))
colnames(OvernightRetA)<-list.namess[Q]
OvernightRet[[Q]]<-OvernightRetA
}
df.OvernightRet<-do.call(merge, OvernightRet)
However, it gives error, probably because of not being able to rename the OvernightRetA:
Error in `colnames<-`(`*tmp*`, value = "ACEM IS Equity.rds") :
attempt to set 'colnames' on an object with less than two dimensions
In addition: There were 50 or more warnings (use warnings() to see the first 50)
> df.OvernightRet<-do.call(merge, OvernightRet)
Error in as.data.frame(x) : argument "x" is missing, with no default
As trade and trade2 is huge and not appropriate for dput. I am posting given Open(A), Close(B) and list of names (list.namess) for reproducibility of error.
dput(head(A,10))
structure(c(231.9, 236.35, 230, 226.85, 229.05, 225.7, 226.95,
224.55, 227, 234.65), class = c("xts", "zoo"), .indexCLASS = c("POSIXct",
"POSIXt"), .indexTZ = "Asia/Calcutta", tclass = c("POSIXct",
"POSIXt"), tzone = "Asia/Calcutta", Price = 1L, index = structure(c(1459481850,
1459741066, 1459827433, 1459913867, 1460000236, 1460086630, 1460345867,
1460432285, 1460518631, 1460950628), tzone = "Asia/Calcutta", tclass = c("POSIXct",
"POSIXt")), .Dim = c(10L, 1L), .Dimnames = list(NULL, "PRICE"))
dput(head(B,10))
structure(c(235.35, 231.2, 226.1, 229.05, 226.45, 225.75, 224.55,
223.75, 231.1, 228.6), class = c("xts", "zoo"), .indexCLASS = c("POSIXct",
"POSIXt"), .indexTZ = "Asia/Calcutta", tclass = c("POSIXct",
"POSIXt"), tzone = "Asia/Calcutta", Price = 1L, index = structure(c(1459508732,
1459767943, 1459854348, 1459940748, 1460027143, 1460113538, 1460374518,
1460465873, 1460545568, 1460977541), tzone = "Asia/Calcutta", tclass = c("POSIXct",
"POSIXt")), .Dim = c(10L, 1L), .Dimnames = list(NULL, "PRICE"))
dput(list.namess) "ACEM IS Equity.rds"
Kindly help me solve this error.
I believe the problem, as the error message implies, is that you are trying to assign a column header to a single value. You can work around this by changing the line above to:
OvernightRetA <- as.data.frame(as.numeric(A)-as.numeric(lag.xts(B)))/as.numeric(lag.xts(B))
I have calculations that identify bar location of events; my calculation output is the number of a bar within my time series or its index (I can work with either). The issue I have is that when I have more than 50 bars on the chart I have to count the bars to identify the bar of interest.
Is there a way to put some kind of an "indicator" on the chart itself for the bars of interest based on the calculation I have?
Say my program indicated bar 3 is a bar of interest. Are there any tricks that would help in identifying that bar graphically on the chart with an arrow or a dot or anything really to avoid having to count the bars. I realize the time is usually on the x axes, but when the chart has many bars you can't read the time and date off the chart, and even if you did its hard to be sure they are aligned properly.
I provided an OHLC AAPL data for 5 minute bars bellow as a dput():
would like to be able to tell R "when you chart my data please identify bar #3 on the chart"
I usually use chartSeries() of the quantmod package to create my charts, but I am open to using other functions.
dput(AAPL)
structure(c(266, 265.95, 265.93, 265.89, 265.91, 266, 266, 265.96,
265.97, 265.98, 265.93, 265.9, 265.84, 265.86, 265.8625, 265.97,
265.96, 265.89, 265.875, 265.98), .Dim = c(5L, 4L), .Dimnames = list(
NULL, c("Open", "High", "Low", "Close")), index = structure(c(1299962039,
1299962098, 1299962157, 1299962219, 1299962278), tzone = "", tclass = c("POSIXct",
"POSIXt")), tclass = c("POSIXct", "POSIXt"), tzone = "", .indexCLASS = c("POSIXct",
"POSIXt"), .indexTZ = "", class = c("xts", "zoo"))
chartSeries(AAPL) would create an OHLC bar chart with 5 bars.
AAPL <- structure(c(266, 265.95, 265.93, 265.89, 265.91, 266, 266, 265.96,
265.97, 265.98, 265.93, 265.9, 265.84, 265.86, 265.8625, 265.97,
265.96, 265.89, 265.875, 265.98), .Dim = c(5L, 4L),
.Dimnames = list(NULL, c("Open", "High", "Low", "Close")),
index = structure(c(1299962039, 1299962098, 1299962157, 1299962219, 1299962278),
tzone = "", tclass = c("POSIXct", "POSIXt")),
tclass = c("POSIXct", "POSIXt"), tzone = "",
.indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", class = c("xts", "zoo"))
chartSeries(AAPL)
addLines(v=3)
addPoints(3, Cl(AAPL)[3])