Skip to content

Instantly share code, notes, and snippets.

@mages
Created February 5, 2012 08:50
Show Gist options
  • Save mages/1744195 to your computer and use it in GitHub Desktop.
Save mages/1744195 to your computer and use it in GitHub Desktop.
Plot Apple's share price with googleVis and gvisAnnotatedTimeLine
## Markus Gesmann, February 2012
## This R script requires the googleVis package,
## a browser with Flash and an Internet connection.
gvisWeeklyStockData <- function(tckr = "AAPL",
chartid ="Apple",
start.year=1984){
require(googleVis)
d <- Sys.time()
current.year <- format(d, "%Y")
current.month <- format(d, "%m")
current.day <- format(d, "%d")
## Yahoo finance sets January to 00 hence:
current.month <- as.numeric(current.month) - 1
current.month <- ifelse(current.month < 10,
paste("0", current.month, sep=""), m)
## Get weekly stock prices for Apple Inc.
## Get data from Yahoo! Finance
fn <- sprintf('http://ichart.finance.yahoo.com/table.csv?s=%s&a=08&b=7&c=%s&d=%s&e=%s&f=%s&g=w&ignore=.csv',
tckr, start.year, current.month, current.day, current.year)
data <- read.csv(fn, colClasses=c("Date", rep("numeric",6)))
## Reshape the data into a long format, see also
## http://lamages.blogspot.com/2012/02/reshape-function.html
stock <- reshape(
data[,c("Date","Close","Volume")],
idvar="Date",
times=c("Close", "Volume"),
timevar="Type",
varying=list(c("Close", "Volume")),
v.names="Value", direction="long"
)
## Calculate previous two years for zoom start time
lyd <- as.POSIXlt(as.Date(d))
lyd$year <- lyd$year-2
lyd <- as.Date(lyd)
## Create annotated time line chart
gvisAnnotatedTimeLine(
stock, datevar="Date",
numvar="Value",
idvar="Type",
options=list(
colors="['blue', 'lightblue']",
zoomStartTime=lyd,
zoomEndTime=as.Date(d),
legendPosition='newRow',
width=600, height=400,
scaleColumns='[0,1]',
scaleType='allmaximized'),
chartid=chartid
)
}
output <- gvisWeeklyStockData(tckr = "AAPL",
chartid ="Apple",
start.year=1984)
plot(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment