# Stock Ticker

A demo I have produced is that of a stock ticker. It draws lines representing the stock prices of a few companies over one year. I sourced the pricing data for well-known tech companies from Google Finance. The idea behind this demonstration is to show how animation can be applied to time series data, in particular with line graphs.

We can see how the lines appear to “draw” themselves over time. Although this is a basic demonstration, it might appear more engaging to a casual observer than a static plot.

```
library(gridSVG)
library(grid)
library(scales)
library(ggplot2)
aapl <- read.csv("aapl.csv")
aapl$Date <- as.Date(aapl$Date, format = "%d-%b-%y")
goog <- read.csv("goog.csv")
goog$Date <- as.Date(goog$Date, format = "%d-%b-%y")
amzn <- read.csv("amzn.csv")
amzn$Date <- as.Date(amzn$Date, format = "%d-%b-%y")
msft <- read.csv("msft.csv")
msft$Date <- as.Date(msft$Date, format = "%d-%b-%y")
stockprices.df <- rbind(aapl, amzn, goog, msft)
```

```
qplot(Date, Close, data = stockprices.df, group = Code, geom = "line",
colour = Code) +
scale_y_log10(breaks = trans_breaks('log10', function(x) 10^x),
labels = trans_format('log10', math_format(10^.x)))
```

```
# Find out what the name of the polyline is
grid.force()
grid.ls()
# Get the polyline
g <- grid.get("GRID.polyline.1")
gx <- split(g$x, g$id)
gy <- split(g$y, g$id)
nTimeIntervals <- length(gx[[1]])
nPointsOverTime <- nTimeIntervals^2
nGroups <- length(unique(g$id))
```

```
# Preallocating vectors
animid <- rep(1:4, each = nPointsOverTime)
animx <- numeric(nPointsOverTime * nGroups)
animy <- numeric(nPointsOverTime * nGroups)
for (i in seq_len(nGroups)) {
xs <- as.numeric(gx[[i]])
ys <- as.numeric(gy[[i]])
indexRange <- (i - 1) * (length(xs) * length(xs)) +
seq_along(rep(xs, length(xs)))
newxs <- numeric(length(indexRange))
newys <- numeric(length(indexRange))
for (j in seq_along(xs)) {
innerIndexRange <- (j - 1) * length(xs) + seq_along(xs)
newxs[innerIndexRange] <- c(xs[seq_len(j)], rep(xs[j], length(xs) - j))
newys[innerIndexRange] <- c(ys[seq_len(j)], rep(ys[j], length(ys) - j))
}
animx[indexRange] <- newxs
animy[indexRange] <- newys
}
```

```
x1 x2 x3 x4 x5
t1 1 1 1 1 1
t2 1 2 2 2 2
t3 1 2 3 3 3
t4 1 2 3 4 4
t5 1 2 3 4 5
```

```
unitxs <- animUnit(unit(animx, "native"),
timeid = rep(seq_len(nTimeIntervals),
nTimeIntervals * nGroups),
id = rep(seq_len(nGroups),
each = nPointsOverTime))
unitys <- animUnit(unit(animy, "native"),
timeid = rep(seq_len(nTimeIntervals),
nTimeIntervals * nGroups),
id = rep(seq_len(nGroups),
each = nPointsOverTime))
```

```
grid.animate("GRID.polyline.1", x = unitxs, y = unitys,
duration = 30, rep = TRUE)
grid.export("stock-ticker.svg")
```