I am using twoord.plot for the first time, and I am having trouble getting the x axis set to years for a time-series data set. I have two different y-axes on different scales. Here is the code that I am working with.
#Install BatchGetSymbols
install.packages('BatchGetSymbols')
library(BatchGetSymbols)
#Get data from FRED
library(quantmod)
getSymbols('CPALTT01USM661S', src = 'FRED')
library(quantmod)
getSymbols('M2SL', src = 'FRED')
#Create data sets with equal number of observations
CPI = CPALTT01USM661S["1960-01-01/2019-01-01"]
M2 = M2SL["1960-01-01/2019-01-01"]
library(plotrix)
twoord.plot(rx = time(CPI), ry = CPI, lx = time(CPI), ly = M2,
main = "Money Supply and Prices",
xlim = NULL, lylim = NULL, rylim = NULL,
mar = c(5,4,4,4), lcol = "red", rcol = "blue", xlab = "", lytickpos = NA,
ylab = "M2", ylab.at = NA,
rytickpos = NA, rylab = "CPI", rylab.at = NA, lpch = 1,rpch = 2,
type = "l", xtickpos = NULL, xticklab = NULL,
halfwidth = 0.4, axislab.cex = 1, do.first = NULL)
Here is the graph that I am getting. Notice the x-axis is not in years.
The date values ( beginnings of each month) are in the index of the matrices, so to extract the year beginnings get every 12th item:
twoord.plot(rx=time(CPI), ry=CPI, lx=time(CPI),ly = M2, main="Money Supply and Prices",xlim=NULL,lylim=NULL,rylim=NULL,
mar=c(5,4,4,4),lcol="red",rcol="blue",xlab="",lytickpos=NA,ylab="M2",ylab.at=NA,
rytickpos=NA,rylab="CPI",rylab.at=NA,lpch=1,rpch=2,
type="l",
xtickpos=index(CPI)[seq(1,nrow(CPI), by=12)], #tick at year start
xticklab=format( index(CPI)[seq(1,nrow(CPI), by=12)], "%Y"), #just year
halfwidth=0.4, axislab.cex=1,
do.first=NULL, las=2) # not sure why las=2 didn't seem to work.
Related
I want to apply a simple wavelet analyze using "waveletcomp" package. I want to use the year shown in x-axis. But it always report error in "lease check your calendar dates, format and time zone: dates may not be in an unambiguous format or chronological. The default numerical axis was used instead." I tried to fix the date, but it seems fine. I really don't know where is the wrong part. Thank you in advance.
Here is the code.
library('WaveletComp')
firecount <- data.frame( YEAR = c("1986-01-01","1987-01-01","1988-01-01","1989-01-01","1990-01-01"
,"1991-01-01","1992-01-01","1993-01-01","1994-01-01","1995-01-01"
,"1996-01-01","1997-01-01","1998-01-01","1999-01-01","2000-01-01"
,"2001-01-01","2002-01-01","2003-01-01","2004-01-01","2005-01-01"
,"2006-01-01","2007-01-01","2008-01-01","2009-01-01","2010-01-01"
,"2011-01-01","2012-01-01","2013-01-01","2014-01-01","2015-01-01"
,"2016-01-01","2017-01-01","2018-01-01","2019-01-01","2020-01-01"
),
COUNT = c(3,5,4,0,0,0,13,0,2,3,0,1,0,3,15,13,
59,18,42,16,20,46,44,8,68,18,7,3,9
,48,7,48,23,84,54)
)
flycount$YEAR <- as.Date(as.character(firecount$YEAR),"%Y")
my.w <- analyze.wavelet(flycount, my.series = "COUNT",
loess.span = 0.5,
dt = 1, dj = 1/35,
lowerPeriod = 2, upperPeriod = 12,
make.pval = TRUE, n.sim = 10,
)
wt.image(my.w, color.key = "interval", n.levels = 15,
legend.params = list(lab = "fire occurrence wavelet", label.digits = 2),
periodlab = "periods (years)",
# Concerning item 1 above --- plot the square root of power:
exponent = 0.5,
# Concerning item 2 above --- time axis:
show.date = TRUE,
date.format = "%F",
timelab = "",
spec.time.axis = list(at = c(paste(1986:2020, "-01-01", sep = "")),
labels = c(1986:2020)),
timetcl = -0.5)
The function analyze.wavelet automatically takes the date from a dataframe column called date. So just rename your column from YEAR to date and you're good to go.
I first started with developing a SMA moving average but I wanted to adapt the function to initiate a stock name from the user
here is my code below
library(quantmod)
library(TTR)
library(PerformanceAnalytics)
stock = readline("Enter the stock name:")
stock
getSymbols(stock, src = 'yahoo', from = '2021-01-01')
barChart(as.name(stock), theme = chartTheme('black'))
# Creating Leading and Lagging Technical Indicators
# a. Simple Moving Average (SMA)
# 1. stock
sma10_stock <- SMA(as.name(stock)$as.name(stock.Close), n = 10)
sma15_stock <- SMA(as.name(stock)$as.name(stock.Close), n = 15)
lineChart(as.name(stock), theme = chartTheme('black'))
addSMA(n = 10, col = 'blue')
addSMA(n = 15, col = 'orange')
legend('left', col = c('green','blue','orange'),
legend = c('stock','SMA10','SMA15'), lty = 1, bty = 'n',
text.col = 'white', cex = 0.8)
# Creating Trading signal with Indicators
# SMA
# a. stock
# SMA 10 Crossover Signal
sma10_stock_ts <- Lag(
ifelse(Lag(Cl(as.name(stock))) < Lag(as.name(stock)) & Cl(as.name(stock)) > sma10_stock,1,
ifelse(Lag(Cl(AMC)) > Lag(sma10_stock) & Cl(AMC) < sma10_stock,-1,0)))
sma10_stock_ts[is.na(sma10_stock_ts)] <- 0
As #MrFlick mentioned you can pass character value of stock in getSymbols with auto.assign = FALSE. To use SMA function you'll not be able to use $stock.Close, you can replace it with column number instead.
library(quantmod)
library(TTR)
library(PerformanceAnalytics)
stock = readline("Enter the stock name:")
data <- getSymbols(stock,src = 'yahoo', from = '2021-01-01', auto.assign = FALSE)
barChart(data, theme = chartTheme('black'))
# Creating Leading and Lagging Technical Indicators
# a. Simple Moving Average (SMA)
# 1. stock
sma10_stock <- SMA(data[, 4], n = 10)
sma15_stock <- SMA(data[, 4], n = 15)
lineChart(data, theme = chartTheme('black'))
addSMA(n = 10, col = 'blue')
addSMA(n = 15, col = 'orange')
legend('left', col = c('green','blue','orange'),
legend = c('stock','SMA10','SMA15'), lty = 1, bty = 'n',
text.col = 'white', cex = 0.8)
> dput(head(inputData))
structure(list(Date = c("2018:07:00", "2018:06:00", "2018:05:00",
"2018:04:00", "2018:03:00", "2018:02:00"), IIP = c(125.8, 127.5,
129.7, 122.6, 140.3, 127.4), CPI = c(139.8, 138.5, 137.8, 137.1,
136.5, 136.4), `Term Spread` = c(1.580025, 1.89438, 2.020112,
1.899074, 1.470544, 1.776862), RealMoney = c(142713.9916, 140728.6495,
140032.2762, 139845.5215, 139816.4682, 139625.865), NSE50 = c(10991.15682,
10742.97381, 10664.44773, 10472.93333, 10232.61842, 10533.10526
), CallMoneyRate = c(6.161175, 6.10112, 5.912088, 5.902226, 5.949956,
5.925538), STCreditSpread = c(-0.4977, -0.3619, 0.4923, 0.1592,
0.3819, -0.1363)), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
I want to make my autoregressive plot like this plot:
#------> importing all libraries
library(readr)
install.packages("lubridtae")
library("lubridate")
install.packages("forecast")
library('ggplot2')
library('fpp')
library('forecast')
library('tseries')
#--------->reading data
inputData <- read_csv("C:/Users/sanat/Downloads/exercise_1.csv")
#--------->calculating the lag=1 for NSE50
diff_NSE50<-(diff(inputData$NSE50, lag = 1, differences = 1)/lag(inputData$NSE50))
diff_RealM2<-(diff(inputData$RealMoney, lag = 1, differences = 1)/lag(inputData$RealMoney))
plot.ts(diff_NSE50)
#--------->
lm_fit = dynlm(IIP ~ CallMoneyRate + STCreditSpread + diff_NSE50 + diff_RealM2, data = inputData)
summary(lm_fit)
#--------->
inputData_ts = ts(inputData, frequency = 12, start = 2012)
#--------->area of my doubt is here
VAR_data <- window(ts.union(ts(inputData$IIP), ts(inputData$CallMoneyRate)))
VAR_est <- VAR(y = VAR_data, p = 12)
plot(VAR_est)
I want to my plots to get plotted together in same plot. How do I serparate the var() plots to two separate ones.
Current plot:
My dataset :
dataset
Okay, so this still needs some work, but it should set the right framework for you. I would look more into working with the ggplot2 for future.
Few extra packages needed, namely library(vars) and library(dynlm).
Starting from,
VAR_est <- VAR(y = VAR_data, p = 12)
Now we extract the values we want from the VAR_est object.
y <- as.numeric(VAR_est$y[,1])
z <- as.numeric(VAR_est$y[,2])
x <- 1:length(y)
## second data set on a very different scale
par(mar = c(5, 4, 4, 4) + 0.3) # Leave space for z axis
plot(x, y, type = "l") # first plot
par(new = TRUE)
plot(x, z, type = "l", axes = FALSE, bty = "n", xlab = "", ylab = "")
axis(side=4, at = pretty(range(z)))
mtext("z", side=4, line=3)
I will leave you to add the dotted lines on etc...
Hint: Decompose the VAR_est object, for example, VAR_est$datamat, then see which bit of data corresponds to the part of the plot you want.
Used some of this
My goal is to assign a plot produced by the pyramid package to a list. Later, I will have that plot and others inserted from the list into a document. But the pyramid function appears not to return a value. How can I assign the pyramid plot to an object?
install.packages("pyramid") # functions to draw a population pyramid
library(pyramid)
# create a mock data frame to comparing this plot to a counterpart from plotrix
df <- data.frame(level1 = c(9,9,4,3,34,28), levelsame = c(9,9,4,3,34,28),
title = c("Dir", "Exec. Dir", "Mgr", "Sr. Mgr", "Mgt Princ", "EVP+"))
# assign the plot (hopefully) to an object
empty <- pyramid(df, Laxis = seq(1,35,5), AxisFM = "g", Csize = 0.8, Cgap = .5, Llab = "",
Rlab = "", Clab = "Title", GL = F, Lcol = "blue", Rcol = "blue",
Ldens = -1, main = "Distribution of Levels")
> empty
NULL
Likewise, if I assign the pyramid call to my list, nothing happens. There is no value for the list returned by pyramid.
plotlist2[["pyramid"]] <- pyramid(df, Laxis = seq(1,35,5), AxisFM = "g", Csize = 0.8, Cgap = .5, Llab = "",
Rlab = "", Clab = "Title", GL = F, Lcol = "blue", Rcol = "blue",
Ldens = -1, main = "Distribution of Levels")
> plotlist2[1]
[[1]]
NULL
I fear I am blundering in some obvious mis-understanding, so I welcome being set aright. Thank you.
You can use the recordPlot() function to save the current plot to a variable.
In your case you could do:
#print the plot
pyramid(df, Laxis = seq(1,35,5), AxisFM = "g", Csize = 0.8, Cgap = .5, Llab = "",
Rlab = "", Clab = "Title", GL = F, Lcol = "blue", Rcol = "blue",
Ldens = -1, main = "Distribution of Levels")
#save the current printed plot
pyrPlot<-recordPlot()
#plot it again
pyrPlot
You might have to enable the displaylist using dev.control(displaylist ="enable") for this to work depending on the graphical device you are using
I have 3 columns of data. In columns data ranging from approximately 0,0727
to 10,2989.
and this is how it looks:
http://i61.tinypic.com/2uen3hz.jpg
My Code
MyData <- read.csv2(file="C:/Users/Sysop/Desktop/Koncentracija.csv",header=T,sep=";")
MyData
Data_1<-MyData$Sul311
Data_2<-MyData$Sul322
Data_3<-MyData$Sul333
Data_1_density<- density(Data_1,na.rm = TRUE)
Data_2_density<- density(Data_2,na.rm = TRUE)
Data_3_density<- density(Data_3,na.rm = TRUE)
xlim <- range(Data_1_density$x,Data_2_density$x,Data_3_density$x, na.rm = TRUE)
ylim <- range(Data_1_density$y, Data_2_density$y, Data_3_density$y, na.rm = TRUE)
Col_1 <- rgb(1,0,0,0.4)
Col_2 <- rgb(0,0,1,0.4)
Col_3 <- rgb(0,1,0,0.4)
plot(Data_1_density, xlim = xlim, ylim = ylim, xlab = 'Zn concentracion, mg/l',main = 'Distribution of data', panel.first = grid(nx = 10, ny = 10))
polygon(Data_1_density, density = -1, col = Col_1)
polygon(Data_2_density, density = -1, col = Col_2)
polygon(Data_3_density, density = -1, col = Col_3)
legend('topright',c('distribution 1 ','distribution 2','distribution 3'),cex=1.0, fill = c(Col_1, Col_2, Col_3), bty = 'n',border = NA)
But as we can see density plots begining from negative values, but my data does not have any negative values. One column missing one value so R shows as NA, but I use (na.rm = TRUE) to ignore NA values.
So is these density plots plotted correctly or not?
Here is my data:
Sul311 Sul322 Sul333
1,8032 NA 2,3981
3,4949 3,1696 1,8218
0,5856 0,5577 0,0837
0,1859 1,5894 0,093
1,4686 1,45 2,9744
0,079 0,0727 0,0543
1,0317 1,0782 2,7513
0,5112 0,5484 0,9295
1,3943 1,1805 2,7513
1,1526 1,1619 2,6305
1,3013 10,2989 5,577
0,5949 0,5856 0,725
0,1766 0,2696 1,6917
0,4229 0,3309 1,1089
1,1953 0,3328 1,6787
1,4853 0,6116 1,8367
0,4443 0,3514 1,2939
0,5912 0,3309 1,2901
you can define the begining or the "first value" with the from argument :
density(x, na.rm=T, from=min(x, na.rm=T))
for instance