How to combine VaR graphics? - r

I want to programm a rolling Value at Risk by hand. So I don't want to use the VaR from the PerformanceAnalytics package. I want to plot after calculations against the log-returns of a time series.
Input:
getSymbols('^GDAXI', src='yahoo', return.class='ts',from="2005-01-01", to="2015-01-01")
GDAXI.DE=GDAXI[ , "GDAXI.Close"]
log_r1=diff(log(GDAXI.DE)) #log_r1=data
alpha=0.95
The VaR function:
VatR=function(data, alpha)
{
x=diff(log(data))
mu=mean(x)
sigma=sqrt(var(x))
quant=qnorm(alpha, mean=0, sd=1)
vatr=tail(data,n=1)*(1-exp((-sigma)*quant+mu))
}
data=GDAXI.DE
alpha=0.95
t=125
l=(-1)*diff(data) #if GDAXI used code must be changed here diff
loss=c(0,l)
ValueatRisk=matrix(rep(0),length(data),1)
violations=matrix(rep(0),length(data),1)
for(i in (t+1):length(data))
{
ValueatRisk[i]=VatRnorm(data[(i-t):(i-1)] ,alpha) #failure source
violations[i]=(loss[i] > ValueatRisk[i])
}
outputtheo=(1-alpha)*(length(data)-t)
print(outputtheo)
outputreal=sum(violations)
print(outputreal)
I want to combine these graphics. It seems to be a scaling problem, I tried qplot, ggplot and so on without success.
graph1=plot(loss[(t+1):length(data)], type="l", col="blue")
graph2=plot(ValueatRisk[(t+1):length(data)], type="l", col="red")
How to bring them together in one plot?

If plotting is the only issue now, I think this will produce what you want.
plot(loss[(t+1):length(data)], type="l", col="blue")
lines(ValueatRisk[(t+1):length(data)], type="l", col="red")
(And BTW, your code won't run as is because VatRnorm() inside the loop is really the old/original VatR().)

Related

How to overlay two lines using the -plot- function in R

I am using R version 3.6.0. I am trying to overlay 3 lines on a single plot. I have done this successfully in the past using identical code and for some reason it doesn't seem to be working. I have the following RWE:
y.l <- function(x){0.024 - 0.00004*x + 0.00001*(10-16.8764)}
y.a <- function(x){0.024 - 0.00004*x}
y.h <- function(x){0.024 - 0.00004*x + 0.00001*(20-16.8764)}
png("yplot.png")
yplot <- plot(y.l(1:800),
type="l", lty=2,
xlab="x", ylab="y", main="Getting better :/",
ylim=c(-0.025,0.025))
lines(1:800, lty=1, y.a(1:800))
lines(1:800, lty=3, y.h(1:800))
dev.off()
which produces the following plot:
For some reason it is ignoring the extra -lines()- code. Is there some obvious mistake I am overlooking after staring at a computer all day? I have done this exact same thing before and I cannot for the life of me figure it out. And yes I have expanded the y-axis to see if they were hiding above or below and they aren't.
Your 3 lines are plotted, it is because of your function that you can't see them.
Here the output of your three function:
> head(y.a(1:800))
[1] 0.02396 0.02392 0.02388 0.02384 0.02380 0.02376
> head(y.h(1:800))
[1] 0.02399124 0.02395124 0.02391124 0.02387124 0.02383124 0.02379124
> head(y.l(1:800))
[1] 0.02389124 0.02385124 0.02381124 0.02377124 0.02373124 0.02369124
You can see that your three function give almost the same results, it because of your 0.00001*(10-16.8764) that's is basically to small to modify your output.
If you zoom enough on the plot:
yplot <- plot(y.l(1:800),
type="l", lty=2,
xlab="x", ylab="y", main="Getting better :/",
ylim=c(.023,0.024),
xlim=c(0,30))
lines(1:800, lty=1, y.a(1:800))
lines(1:800, lty=3, y.h(1:800))
You can see the three lines:
I think you need to change the last parameter of your function if you want to see a dramatic difference between your lines.

Add changepoint lines to plot in prophet (R)

I am using prophet in R (https://facebook.github.io/prophet/), and I would like to overlay changepoints on top of the forecasting plot prophet makes. Here's my code (df is a dataframe containing dates (column ds) and values (column y):
m <- prophet(df)
future <- make_future_dataframe(m, periods=5)
forecast <- predict(m, future)
plot(m, forecast, xlab="Day", ylab="Counts")
i = 0
while (i <= length(m$changepoints.t)) {
tmp <- m$changepoints[i]
abline(v=as.POSIXct(tmp), col='red')
i = i + 1
}
However, the changepoint lines never show up. I double-checked that the changepoints are in range of the main plot, and I tried both as.Date and as.POSIXct in abline. No errors in either case, but no changepoint lines either. Could someone please help?
If you check the class of the plot object:
class(plot(m,forecast,xlab="Day", ylab="Counts"))
... you'll see that it's a ggplot graphic. Additionally, if you access m$changepoints instead of m$changepoints.t, you'll find the changepoints of your model already in POSIXct format.
To plot all of your changepoints as vertical lines, you can use geom_vline like so:
p <- plot(m,forecast,xlab="Day", ylab="Counts")
for (changepoint in m$changepoints) {
p <- p + geom_vline(xintercept = changepoint)
}
print(p)
The prophet package has a dedicated function for this, add_changepoints_to_plot.
In your case, this would do the trick:
plot(m, forecast, xlab="Day", ylab="Counts") +
add_changepoints_to_plot(m)
See ?add_changepoints_to_plot for customisations.

Smooth curve through points and include the origin in R

I am a beginner in R and started with graphics recently.
I have managed to program a working empirical cumulative distribution function (user-generated, not using the standard ecdf() function) and to generate a plot. However, the plot is not as it should be, there are two issues with it and I am not sure on how to solve them (I have done my 'research' but have not found a solution).
This is my code:
set.seed(1)
n = 50
x = rpois(n, 2.2)
cdf = function(x,n)
{
v=c()
for(z in 1:max(x))
{
a = length(x[x<=z])/n
v = c(v, a)
}
plot(v,type="l", main="empirical cumulative distribution function", xlab="x", ylab="cumulative probability", xlim=c(0,6), ylim=c(0,1.0))
}
cdf(x, n)
There are two issues with this plot:
The lines are straight but it should be a smooth curve through all points.
The origin is not included (now the curve starts at x = 1).
How can these issues be resolved in an elegant way?
Try the following spline interpolator:
plot(spline(c(0, v)), type = "l")

function lines() is not working

I have a problem with the function lines.
this is what I have written so far:
model.ew<-lm(Empl~Wage)
summary(model.ew)
plot(Empl,Wage)
mean<-1:500
lw<-1:500
up<-1:500
for(i in 1:500){
mean[i]<-predict(model.ew,data.frame(Wage=i*100),interval="confidence",level=0.90)[1]
lw[i]<-predict(model.ew,data.frame(Wage=i*100),interval="confidence",level=0.90)[2]
up[i]<-predict(model.ew,data.frame(Wage=i*100),interval="confidence",level=0.90)[3]
}
plot(Wage,Empl)
lines(mean,type="l",col="red")
lines(up,type="l",col="blue")
lines(lw,type="l",col="blue")
my problem i s that no line appears on my plot and I cannot figure out why.
Can somebody help me?
You really need to read some introductory manuals for R. Go to this page, and select one that illustrates using R for linear regression: http://cran.r-project.org/other-docs.html
First we need to make some data:
set.seed(42)
Wage <- rnorm(100, 50)
Empl <- Wage + rnorm(100, 0)
Now we run your regression and plot the lines:
model.ew <- lm(Empl~Wage)
summary(model.ew)
plot(Empl~Wage) # Note. You had the axes flipped here
Your first problem was that you flipped the axes. The dependent variable (Empl) goes on the vertical axis. That is the main reason you didn't get any lines on the plot. To get the prediction lines requires no loops at all and only a single plot call using matlines():
xval <- seq(min(Wage), max(Wage), length.out=101)
conf <- predict(model.ew, data.frame(Wage=xval),
interval="confidence", level=.90)
matlines(xval, conf, col=c("red", "blue", "blue"))
That's all there is to it.

In R, how to prevent blank page in pdf when using gridBase to embed subplot inside plot

As explained here, it is easy to embed a plot into an existing one thanks to gridBase, even though both plots use the base graphics system of R. However, when saving the whole figure into a pdf, the first page is always blank. How to prevent this?
Here is an example:
require(gridBase)
## generate dummy data
set.seed(1859)
x <- 1:100
y <- x + rnorm(100, sd=5)
ols <- lm(y ~ x)
pdf("test.pdf")
## draw the first plot
plot.new() # blank page also happens when using grid.newpage()
pushViewport(viewport())
plot(x, y)
## draw the second plot, embedded into the first one
pushViewport(viewport(x=.75,y=.35,width=.2,height=.2,just=c("center","center")))
par(plt=gridPLT(), new=TRUE)
hist(ols$residuals, main="", xlab="", ylab="")
popViewport(2)
dev.off()
I think it's a bit of a hack but setting onefile=FALSE worked on my machine:
pdf("test.pdf", onefile=FALSE)
In searching for an answer (which I didn't really find so much as stumbled upon in the forest) I came across this post to Rhelp from Paul Murrell who admits that mixing grid and base graphics is confusing even to the Master.
A work around solution I found was to initiate the pdf file inside the for loop; then insert an if clause to assess whether the first iteration is being run. When the current iteration is the first one, go ahead and create the output device using pdf(). Put the dev.off() after closing the for loop. An quick example follows:
for(i in 1:5){
if (i == 1) pdf(file = "test.pdf")
plot(rnorm(50, i, i), main = i)}
dev.off()

Resources