Highlight a period in graph with R - r

Is there an easy way to highlight the period in R?
Right now I am trying to use the following, but it does not work for me:
library (PerformanceAnalytics)
period <- c("2018-02/2019-01")
chart.TimeSeries(btc_xts,
period.areas = "2018-02/2019-01",
period.color = "lightgrey")
As a result, I see the historical graph, but I do not the the highlighting.
The outcome attached. Who could help?
Thank you!
the result of the action, no highlighting

I've never used the library but reading from the doc of period.areas :
period.areas : these are shaded areas described by start and end dates in a vector of
xts date rangees, e.g., c("1926-10::1927-11","1929-08::1933-03")
The code should be :
library(PerformanceAnalytics)
period = c("2018-02::2019-01")
chart.TimeSeries(btc_xts,
period.areas = period,
period.color = "lightgrey")
`

Related

Simple way to shorten time period of graph in ggplot

Let's consider data :
library(ggplot2)
library(quantmod)
start <- as.Date("2013-01-01")
end <- as.Date("2016-10-01")
# Apple stock
getSymbols("AAPL", src = "yahoo", from = start, to = end)
And plot :
autoplot(Cl(AAPL))
My question is : is there any way how can I simlpy shorten time period of my plot ? Let's say for example I want to have my plot from '2013-01-01' up to '2014-01-01'. Of course I can do exactly same thing with changing my start and end variables (defined at the very beggining) and redownload data set. However I found this solution inefficient. Is there any simpler way how it can be performed ?
There are two approaches. One is to specify limits to the plotting routine and the other is to subset the data itself. Since the first one is already illustrated by another answer we will focus on the second:
# xts suppports .../... notation
apple <- Cl(AAPL)['2013-01-01/2014-01-01']
# this will extract all rows for 2013
apple <- Cl(AAPL)['2013']
# window function
apple <- window(Cl(AAPL), start = "2013-01-01", end = "2014-01-01")
Having defined apple we can autoplot it.
You can add an xlim = argument to autoplot:
autoplot(Cl(AAPL),
xlim = as.Date(c("2014-01-01","2016-04-01")))
You can also use the + operator if you prefer:
autoplot(Cl(AAPL)) +
xlim(as.Date(c("2014-01-01","2016-04-01")))
See help(autoplot.zoo) for more.

Issue Plotting Time Series Line Graph in Plotly

I have some code that pulls reservoir elevation from an API. I have sorted the data and plotted it. When I plot it in native R it looks fine and how I would expect:
When I plot it using plotly I get the following:
The y axis appears to be jumbled with some initially low values on top? I'd like to fix this and essentially match what is produced with the plot() function. Any help with this would be much appreciated.
library("rjson")
library('jsonlite')
library('plotly')
CurrentDate = format(Sys.Date(), "%m-%d-%Y")
StartDate = "1850-01-01"
EndDate = CurrentDate
urlWithoutStart =
paste("https://water.usbr.gov/api/web/app.php/api/series?
sites=hdmlc&parameters=Day.Inst.ReservoirElevation.feet,",
"Day.Sum.ReservoirRelease-
Powerplant.af,Day.Avg.ReservoirRelease-
Powerplant.cfs,Day.Inst.ReservoirStorage.af&",
"start=",sep="")
urlWithoutEnd = paste(urlWithoutStart,StartDate,"&end=",sep="")
urlFull = paste(urlWithoutEnd,EndDate,"&format=json",sep="")
LakeMeadAllData = fromJSON(urlFull)
LakeMeadElevation = as.data.frame(LakeMeadAllData[[1]][[18]][[2]][[1]]
[[1]])
LakeMeadElevation$datetime = as.Date(LakeMeadElevation$datetime)
names(LakeMeadElevation) = c("Date","Elevation","Flag")
LakeMeadElevation <- LakeMeadElevation[order(LakeMeadElevation$Date),]
plot_ly(LakeMeadElevation,x=as.Date(LakeMeadElevation$Date),y=
LakeMeadElevation$Elevation,type = 'scatter',mode="line")
plot(LakeMeadElevation$Date,LakeMeadElevation$Elevation,type='l')
setting y to y=as.numeric(LakeMeadElevation$Elevation) solved the problem.

Plotting in ggplot after converting to data.frame with a single column?

I'm trying to convert some simple data into a form I thought ggplot2 would accept.
I snag some simple stock data and now I just want to plot, later I want to plot say a 10-day moving average or a 30-day historical volatility period to go with it, which is I'm using ggplot.
I thought it would work something like this line of pseudocode
ggplot(maindata)+geom_line(moving average)+geom_line(30dayvol)
library(quantmod)
library(ggplot2)
start = as.Date("2008-01-01")
end = as.Date("2019-02-13")
start
tickers = c("AMD")
getSymbols(tickers, src = 'yahoo', from = start, to = end)
closing_prices = as.data.frame(AMD$AMD.Close)
ggplot(closing_prices, aes(y='AMD.Close'))
But I can't even get this to work. The problem of course appears to be that I don't have an x-axis. How do I tell ggplot to use the index column as a. Can this not work? Do I have to create a new "date" or "day" column?
This line for instance using the Regular R plot function works just fine
plot.ts(closing_prices)
This works without requiring me to enter a hard x-axis, and produces a graph, however I haven't figured out how to layer other lines onto this same graph, evidently ggplot is better so I tried that.
Any advice?
as.Date(rownames(df)) will get you the rownames and parse it as a date. You also need to specify a geom_line()
library(quantmod)
library(ggplot2)
start = as.Date("2008-01-01")
end = as.Date("2019-02-13")
start
tickers = c("AMD")
getSymbols(tickers, src = 'yahoo', from = start, to = end)
closing_prices = as.data.frame(AMD$AMD.Close)
ggplot(closing_prices, aes(x = as.Date(rownames(closing_prices)),y=AMD.Close))+
geom_line()
Edit
Thought it would be easier to explain in the answers as opposed to the comments.
ggplot and dplyr have two methods of evaluation. Standard and non standard evaluation. Which is why in ggplot you have both aes and aes_(). The former being non standard evaluation and the later being standard evaluation. In addition there is also aes_string() which is also standard evaluation.
How are these different?
Its easy to see when we explore all the methods,
#Cleaner to read, define every operation in one step
#Non Standard Evaluation
closing_prices%>%
mutate(dates = as.Date(rownames(.)))%>%
ggplot()+
geom_line(aes(x = dates,y = AMD.Close))
#Standard Evaluation
closing_prices%>%
mutate(dates = as.Date(rownames(.)))%>%
ggplot()+
geom_line(aes_(x = quote(dates),y = quote(AMD.Close)))
closing_prices%>%
mutate(dates = as.Date(rownames(.)))%>%
ggplot()+
geom_line(aes_string(x = "dates",y = "AMD.Close"))
Why are there so many different ways of doing the same thing? In most cases its okay to use non standard evaluation. However if we want to wrap these plots in functions and dynamically change the column to plot based on function parametrs passed as strings. It is helpful to plot using the aes_ and aes_string.

Plotting Basic Time Series Data in R - Not Plotting Correctly

I'm trying to plot some time series data. My plot looks like the following:
I'm uncertain as to why it displays the date as such. I'm using R Markdown in R studio. Below is my code:
agemployment<-read.csv("Employment-Level1.csv", header=TRUE)
Tried to change the class of Date:
as.Date(as.character(agemployment$Date),format="%m%d%Y")
That did nothing. Rest of code here:
`attach(agemployment)
View(agemployment)
head(agemployment)
agemployment<-ts(agemployment,frequency=12,start=c(2008, 1))
plot(agemployment, col="black", main="Agriculture Employment Level",
ylab="Total Employment Level (Thousands)", ylim=c(0, 250),lwd=2,
xaxs="i", yaxs="i", lty=1)'
This produces the above plot. I'm uncertain what I'm doing wrong. I would appreciate any help. Thank you!
EDIT:
Data here:
I suspect your issues are somehow driven by attach, generally attaching data frames is not a good practice. The following super-simple code worked for me:
# small dataset from your example, I use package readr to load it as data frame
df = readr::read_csv("DATE,Employment
1/1/2008,1245
2/1/2008,1280
3/1/2008,1343
4/1/2008,1251
5/1/2008,1236
6/1/2008,1265")
ts <- ts(data = df$Employment, frequency = 12, start = c(2008, 1))
plot(ts)
Using the file generated reproducibly in the Note at the end read the file into a zoo object making the index of class "yearmon" (representing year and month without day). Then plot it.
library(zoo)
z <- read.csv.zoo("Employment-Level1.csv", format = "%m/%d/%Y", FUN = as.yearmon)
plot(z)
or
library(ggplot2)
autoplot(z) + scale_x_yearmon()
(continued after plots)
If you wanted to convert z to a ts object or data frame:
tt <- as.ts(z)
DF <- fortify.zoo(z)
Note
Lines <- "DATE,Employment
1/1/2008,1245
2/1/2008,1280
3/1/2008,1343
4/1/2008,1251
5/1/2008,1236
6/1/2008,1265"
cat(Lines, file = "Employment-Level1.csv") # write out file
Realize that by providing an image in the question it means that everyone who answers must retype your data so in the future please provide the input data to questions in a reproducible form as we have done here.

Quantmod Oscillators

Utilizing the chartSeries function in the quantmod package, I want to modify the RSI oscillator. Given an xts object containing OHLC price data, here is the call that I am using:
chartSeries(plot_report[, 1:4],
name = substr(ticker, 1, nchar(ticker) - 4),
theme = chartTheme('white.mono', grid.col = NA),
TA = c(addRSI(n = 14, maType = "SMA")),
type = "line",
bar.type = 'ohlc',
major.ticks = 'months',
show.grid = FALSE,
log.scale = TRUE)
Generating this chart:
I have four questions:
How can I change the default color of blue to something else? I have tried: c(addRSI(n = 14, maType = "SMA", col = "black")). However, I get the "unused argument" error.
Can I draw horizontal lines in the oscillator panel? Traditional RSI's have a horizontal red line at a y-axis value of 70 and a horizontal green line at a y-axis value of 30 to indicate overbought/oversold levels.
Is it possible to plot another calculation as an oscillator line below the chart? I have some proprietary oscillators that I want to visualize instead of the RSI or any of the indicators in the TTR package.
How can I get involved in improving the quantmod charting functionality; is this project being actively maintained?
You can't. You would need to add ... to the arguments for addRSI and modify the body of the function to use ... appropriately. A work-around is to calculate RSI manually, then call addTA as done in the answer to Change line colors of technical indicators made by R quantmod TTR?.
Use addLines:
getSymbols("SPY"); chartSeries(SPY, TA="addRSI();addLines(h=c(30,70), on=2)")
Use addTA with the object containing your proprietary data.
See quantmod's GitHub page. Yes, it's actively maintained. The last update was pushed to CRAN a couple months ago.

Resources