I have 5413 companies (as columns) and time period of 2000 to 2014 daily stock price observations, 3789 is observation count in my dataset. So, now I want to plot the graphs of these companies prices and also plot the graphs of the log returns I created in separate dataframe. I illustrate some portion of the dataframe as follows
Date A G L ABA ABB ABBEY
2000-1-3 NA NA NA NA
2000-1-4 79.5 325 NA 961
2000-1-5 79.5 322.5 NA 945
2000-1-6 79.5 327.5 NA 952
2000-1-7 NA 327.5 NA 941
2000-1-10 79.5 327.5 NA 946
2000-1-11 79.5 327.5 NA 888
and daily log returns
Date A G L ABA ABB ABBEY
2000-01-04 NA NA NA NA
2000-01-05 0 -0.007722046 NA -0.016789481
2000-01-06 0 0.015384919 NA 0.007380107
2000-01-07 NA 0.000000000 NA -0.011621895
2000-01-10 NA 0.000000000 NA 0.005299429
2000-01-11 0 0.000000000 NA -0.063270826
I want to plot the graphs with companies name as Y-axis and Date as X-axis, separately for each company in my dataframes. I want to show that trend or stationarity in the stock prices series has been removed by log returns I tried plot.ts(Price)
but it returns
Error in plotts(x = x, y = y, plot.type = plot.type, xy.labels = xy.labels, :
cannot plot more than 10 series as "multiple"
so here is a couple of examples you can use. I prefer ggplot2 but it's up to you :-)
data <- read.table(text="
Date AGL ABA ABB ABBEY
2000-1-3 NA NA NA NA
2000-1-4 79.5 325 NA 961
2000-1-5 79.5 322.5 NA 945
2000-1-6 79.5 327.5 NA 952
2000-1-7 NA 327.5 NA 941
2000-1-10 79.5 327.5 NA 946
2000-1-11 79.5 327.5 NA 888",
header = TRUE)
format your date
data$Date <- as.Date(data$Date)
and then use your plot function
plot.ts(data)
or with ggplot2
library(ggplot2)
ggplot(data=data, aes(x=Date, y=AGL)) + geom_line() + geom_line(data=data, aes(x=Date, y=ABA), color="red") + geom_line(data=data, aes(x=Date, y=ABBEY), color="green") + theme_bw()
obviously you can change the graphics by playing with the options!
Import necessary R packages:
require(ggplot2)
require(dplyr)
I create a toy data.frame to make the point:
df <- tribble(
~day, ~stock1, ~stock2,
1, 3, 5,
2, 2, 1,
3, -3, 7
)
Now, using gather function from dplyr you can transform the data into long format:
df2 <- df %>% gather(stock1:stock2, key = 'stock', value= 'price')
Use ggplot2 to make the plot:
ggplot(df2, aes(day, price, color = stock)) + geom_line()
Or, you could do it in one step:
df %>% gather(stock1:stock2, key = 'stock', value= 'price') %>%
ggplot(aes(day, price, color = stock)) +
geom_line()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.