Archives for posts with tag: graphs

In my investments class, we have to produce charts and perform technical analysis. Though quantmod has the mucho excellente chartSeries() function, I can't leave well enough alone and decided to try to write some functions that will draw a chart using ggplot and add technical indicators.

I got basic functionality down, but want to continue to add things to the function. call ggChartSeries() and provide an OHLC object from quantmod, along with start and end dates in as.Date() form. It calculates moving averages and after that trims the data series, as opposed to chartSeries(), which has issues with this since it takes the pre-trimmed data as an input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
require(quantmod)
require(ggplot2)
 
getSymbols('AAPL')
x<-AAPL
start <- Sys.Date()-200
end <- Sys.Date()
 
#Pass an OHLC object into this function
#also pass two dates formatted as.Date()
ggChartSeries <- function(x, start, end){
 
# the below is done redundantly for ease of maintenance later on
#First, strip OHLC data (need to vectorize)
  date <- as.Date(time(x))
  open <- as.vector(Op(x))
  high <- as.vector(Hi(x))
  low <- as.vector(Lo(x))
  close <- as.vector(Cl(x))
 
#Then build the data frame
  xSubset <-data.frame('date'=date,'open'=open,'high'= high,'low'=low,'close'=close)
 
#We want to construct our candlesticks  
  xSubset$candleLower <- pmin(xSubset$open, xSubset$close)
  xSubset$candleMiddle <- NA
  xSubset$candleUpper <- pmax(xSubset$open, xSubset$close)
  xSubset$fill <- ''
  xSubset$fill[xSubset$open < xSubset$close] = 'white'
  xSubset$fill[xSubset$fill ==''] = 'red'
 
#Add Moving Averages
  xSubset$ma200 <- SMA(xSubset$close, 200)
  xSubset$ma50 <- SMA(xSubset$close, 50)
 
#Trim Data
  xSubset <-subset(xSubset, xSubset$date > start & xSubset$date < end)
 
#Graphing Step
  g <- ggplot(xSubset, aes(x=date, lower=candleLower, middle=candleMiddle, upper=candleUpper, ymin=low, ymax=high)) 
  g <- g + geom_boxplot(stat='identity', aes(group=date, fill=fill))
  g <- g + geom_line(aes(x=date, y=ma50))+ geom_line(aes(x=date, y=ma200))
  g 
}
 
#call our graphing function
ggChartSeries(AAPL, start, end)

Todo list:

  • Add titles and labeling
  • Add more TA indicators
  • Tweak colors
  • Add/refine options to the function
  • Add volume bars at the bottom

Recently, reading an article by Megan McArdle about income inequality, she speculated about the idea that the share of income of the 1% gets worse during a recession. She posted a graph:
Income share of the top 1% in the US from 1913
I wasn't a fan of the graph. The ticks distracted from the data being presented, and recessions were not highlighted on the graph, as they are on graphs from places like FRED. Fortunately the data from the graph is available and we can make a run of it using R and ggplot. Read the rest of this entry »