My plot is displaying weird numbers instead of dates. When converting them I find today's date. The issue is that I'm studying past dates. I would like to display on the chart below, the dates corresponding to the values.
This is the Data Frame:
I already converted dates using:
dates <- lubridate::mdy(rv_data_USDC_DAILY$Date)
This is my code for the plot:
par(mfrow = c(1, 2))
plot.ts(x=df_peg$date, y=df_peg$BUSDPEG, type="l", main = "", col="#1F4690", ylab="USD")
abline(h=0)
mtext("BUSD Deviations from Peg")
hist(df_peg$BUSDPEG, xlim = c(-0.01,0.01), main="", col="#D61C4E")
Sample of Data:
date BUSDPEG USDCPEG DAIPEG GEMINIPEG HUSDPEG PAXPEG STASISPEG
1 2022-06-29 -2.383111e-03 0.00010 -0.0044920717 2.048424e-03 -1.543622e-04 1.639760e-02 -0.04452180
2 2022-06-28 -1.414367e-03 0.00005 -0.0020128418 1.531139e-03 -3.612265e-04 1.710005e-02 -0.03907985
Thanks
You can use the plot function only when you want to use dates. It works very well. Here is an example :
date <- seq(from = as.Date("2001-01-01"), to = as.Date("2020-01-01"), by = "quarter")
returns <- rnorm(n = length(date))
plot(x = date, y = returns, type = "l")
Related
I have a simple data frame, observations_df, with two columns DateTime and Value:
2002-03-28T19:30:00, 23.53, ...
How to create a time series from data frame observations_df and show time series in graph?
Tutorials are very rich and complex.I have tried different approaches unsuccessfully.
Does this answer your question?
library(tidyverse)
df <- tibble(
date = Sys.Date() + 0:10,
value = runif(n = 11)
)
df %>%
ggplot(aes(x = date, y = value)) +
geom_line()
First you may use ts to create a time series "ts" object.
dat.ts <- ts(dat[,2], start=dat[1,1], end=dat[nrow(dat),1])
# Time Series:
# Start = 18263
# End = 18292
# Frequency = 1
# [1] 0.16804153 0.80751640 0.38494235 0.32773432 0.60210067 0.60439405 0.12463344 0.29460092
# [9] 0.57760992 0.63097927 0.51201590 0.50502391 0.53403535 0.55724944 0.86791949 0.82970869
# [17] 0.11144915 0.70368836 0.89748826 0.27973255 0.22820188 0.01532989 0.12898156 0.09338193
# [25] 0.23688501 0.79114741 0.59973157 0.91014771 0.56042455 0.75570477
Then, actually there is a plot method and you could just do plot(dat.ts). However, "ts" objects store dates numerically, and we want to read "real" dates on the x-axis and therefore probably want to do a manual axis labeling with somewhat "thinned out" elements from the date column using e.g. modulo %%.
labs <- dat$datetime[as.numeric(substr(dat$datetime, 9, 10)) %% 7 == 0]
plot(dat.ts, xaxt="n", main="My Title", col=2, xlab="time", ylab="value")
axis(1, labels=F, at=dat$datetime, tck=-.01)
axis(1, labels=F, at=labs, tck=-.03)
mtext(as.character(labs), 1, 1, at=labs)
legend("topleft", lty=1, legend="time series xy", col=2)
Toy data used
set.seed(3)
dat <- data.frame(datetime=as.Date(seq(1:30), "2020-01-01"),
value=runif(30))
I have been creating a few technical indicators using Quantmod's NewTa function.
I've been trying to create a custom indicator that ideally should be charted using ChartSeries. This indicator should show the slope of the line of the 50 day EMA of the adjusted closing price.
getSymbols("NOVO-B.CO")
p <- na.omit('NOVO-B.CO')
FiftyEMA <- function(x){
MA <- removeNA((EMA(p[,6],n=50)))
}
SlopeFiftyEMA <- function(x){
run=(FiftyEMA(y)/FiftyEMA(x))
}
Slope.Indicator <- newTA(SlopeFiftyEMA,legend.name = "50 Day EMA Slope of Line Indicator")
Slope.Indicator()
This gives me the error: Error in get.current.chob() : improperly set or missing graphics device
I also tried a new code that gives me an actual INDICATOR! Please let me know what you think (if you think it looks correct or not):
First I export the data to excel: (the stock data is still denoted as p)
write.csv(p,"data")
import data
x <- data[,1]
y <- data[,7]
MA <- removeNA(EMA(y,n=50))
length(MA)
length of MA = 1923
l=1:1923
SlopeFiftyEMA <- function(x){
(diff(MA)/diff(l))
}
Slope.Indicator <- newTA(SlopeFiftyEMA,legend.name = "50 Day EMA Slope of Line Indicator")
twelvemonths="last 12 months"
chartSeries(p,subset = twelvemonths,theme = 'white',up.col = 'blue',dn.col = 'grey',name ="Custom Indicators")
Slope.Indicator()
Any Input anyone? Last time I posted there was no indicator
Thanks in advance!
Your first error seems to exist because you don't call chartSeries before calling Slope.indicator(). But your code is a bit messy, including not defining y (maybe you introduce it later in import data).
The approach presented here will plot the slope of the MA according to linear regression, using chart_Series (arguably cleaner plots than the original chartSeries). Two types of slopes are computed, including the one you proposed, which is the differences of the EMA.
getSymbols(c("NOVO-B.CO"))
x <- `NOVO-B.CO`
x[, c(1:4, 6)] <- na.locf(x[, c(1:4, 6)])
x$EMA <- EMA(Cl(x), n = 50)
x <- merge(x, rollSFM(Ra = x[, "EMA"], Rb = 1:NROW(x), n = 20))
x <- merge(x, setNames(diff(x$EMA), "diff1"))
chart_Series(x, subset = "2016/")
add_TA(x$EMA, on = 1, col = "purple")
# Plot the slope of the MA:
add_TA(x$beta, col = "green")
# Plot the 1 lag diff of the moving average:
add_TA(x$diff1, lty = 2)
I have been looking at the documentation but I cannot figure out how to control the time stamp on the x-axis of a filled.contour() plot in R. I have tried axis.POSIXct() and plot.axes = {}. But neither works for me.
Here is my simplified example:
x1 <- seq(as.Date("2016-01-01"),as.Date("2018-07-01"),by="month")
z1 <- c(0.45062130 ,0.51136174 ,0.6 ,0.8 ,0.29481738 ,0.6 ,0.27713756 ,0.62638512 ,0.23547530,0.29253901 ,0.75899501 ,0.67779756 ,0.51831742 ,0.08050147 ,0.71183739 ,0.13154414 ,0.79406706 ,0.13154414,0.03434758 ,0.59573892 ,0.22102821 ,0.13154414 ,0.13154414 ,0.13154414 ,0.13154414 ,0.13154414 ,0.23692593,0.95215104 ,0.38810846 ,0.17970580 ,0.05176054)
z2 <- z1^2
z3 <- z2^2
df <- data.frame(x1,z1,z2,z3)
time <- c(x1)
depths <- c(1,2,3)
temp2 <- as.matrix(data.frame(df$z1,df$z2,df$z3))
temp2<- matrix(temp2,ncol=ncol(temp2), dimnames = NULL)
filled.contour(time,depths,temp2, col=(matlab.like2(28)),
ylab="Depth", xlab="Time",
key.title=title(expression(' Temp ('*degree*'C)')),xaxs="i")
Which outputs:
X-axis labels are in year format. I would like the format to be %b-%y for every month (e.g. May-16, June-16 etc). How do I do this?
Here's how to do it using the plot.axes option with axis.Date.
filled.contour(time,depths,temp2, #col=(matlab.like2(28)),
ylab="Depth", xlab="Time",
plot.axes = { axis.Date(side=1,x=time,at=time,format="%b-%y"); axis(2) },
key.title=title(expression(' Temp ('*degree*'C)')),xaxs="i")
We have used the forecast function to forecast future values as follows:
library("zoo")
library("forecast")
Lines = "20/03/2014,9996792524
21/04/2014,8479115468
21/09/2014,11394750532
16/10/2014,9594869828
18/11/2014,10850291677
08/12/2014,10475635302
22/01/2015,10116010939
26/02/2015,11206949341
20/03/2015,11975140317
09/04/2015,11526960332
29/04/2015,9986194500
16/09/2015,11501088256
13/10/2015,11833183163
10/11/2015,13246940910
16/12/2015,13255698568
27/01/2016,13775653990
23/02/2016,13567323648
22/03/2016,14607415705
11/04/2016,13835444224
04/04/2016,14118970743"
z <- read.zoo(text = Lines, sep = ",", header = TRUE, index = 1:1, tz = "", format = "%d/%m/%Y")
x <- ts(z,f=4)
fit <- ts(rowSums(tsSmooth(StructTS(x))[,-2]))
tsp(fit) <- tsp(x)
plot(x)
lines(fit,col=2)
fit
fcst <- forecast(fit)
plot(fcst)
However, the plot fcst does not show time/date labels on the x-axis and instead just shows generic numbers 1,2,3...
To understand forecasted values, we need monthly date labels on the x-axis. How can we do this?
I have a seasonal (7 days interval) time series, daily data for 30 days.
What is the best approach for a reasonable forecast?
The time series contains orders made with a app, it shows a seasonality of 1 week (lower sales at the beginning of the week).
I try the holt winters approach with this code:
(m <- HoltWinters(ts,seasonal = "mult"))
plot(m)
plot(fitted(m))
but it gives me an error like: Error in decompose(ts(x[1L:wind], start = start(x), frequency = f),seasonal) :
time series has no or less than 2 periods
What do you suggest?
EDIT:
data here
You must first determine a ts object. Assuming your data is called df:
ts <- ts(df$install, frequency = 7)
(m <- HoltWinters(ts,seasonal = "mult"))
plot(m)
plot(fitted(m))
Then you can make prediction like (10 steps-ahead):
predict(m, n = 10)
Time Series:
Start = c(4, 5)
End = c(5, 7)
Frequency = 7
fit
[1,] 1028.8874
[2,] 1178.4244
[3,] 1372.5466
[4,] 1165.2337
[5,] 866.6185
[6,] 711.6965
[7,] 482.2550
[8,] 719.0593
[9,] 807.6147
[10,] 920.3250
The question about the best method is too difficult to answer. Usually one compares the performance of different models considering their out-of-sample accuracy and chooses the one whith the best result.
You can use df$data to keep the dates that correspond to each day in the ts series.
ts_series <- ts(df$install, frequency = 7)
ts_dates <- as.Date(df$data, format = "%d/%m/%Y")
In a similar way, dates for the forecasted values can be kept in another sequence
m <- HoltWinters(ts_series, seasonal = "mult")
predict_values <- predict(m, 10)
predict_dates <- seq.Date(tail(ts_dates, 1) + 1, length.out = 10, by = "day")
With the dates sequence, the daily series can be plot with dates in x axis with the right format. More control on the x axis ticks can be obtained with the axis.Date function
plot(ts_dates, ts_series, typ = "o"
, ylim = c(0, 4000)
, xlim = c(ts_dates[1], tail(predict_dates, 1))
, xlab = "Date", ylab = "install", las = 1)
lines(predict_dates, predict_values, lty = 2, col = "blue", lwd = 2)
grid()