Python vs R #2: Adding Technical Analysis Indicators to ChartsThis is the second in a series that is comparing Python and R for quantitative trading analysis. It looks at extending the previous example in the first of the series by adding technical analysis indicators to the charts.
I start with the code from the previous entry in the series for downloading the closing stock prices from YahooImporting closing stock price of Apple from Yahoo
import pandas.io.data as web import datetime #Download data from yahoo finance start = datetime.datetime(2010,1,1) end = datetime.datetime(2014,3,24) ticker = "AAPL" f=web.DataReader(ticker,'yahoo',start,end)
R code from the previous entry in the series for downloading the closing stock price from YahooImporting closing stock price of Apple from Yahoo
library(quantmod) library(xts) start = '2010-01-01' end = '2014-03-24' ticker = 'AAPL' f = getSymbols(ticker, src = 'yahoo', from = start, to = end, auto.assign=F)
The python module (talib) that I will be using to calculate the technical indicators is a wrapper around the open source TA-Lib.
TTR is the R library that I will be using to calculate the technical indicators.
Calculating simple moving averages with two lookback periods of 20 and 50 days and appending as two columns on the end of the pandas dataframe that contains the closing stock prices. Then I call the plot function to plot them together with the closing stock price.
f['SMA_20'] = talib.SMA(numpy.asarray(f['Close']), 20) f['SMA_50'] = talib.SMA(numpy.asarray(f['Close']), 50) f.plot(y= ['Close','SMA_20','SMA_50'], title='AAPL Close & Moving Averages')
In R we could do it in a very similar manner but the Quantmod library has helpfully added the chartSeries function that includes the ability to add technical analysis indicators directly to the chart within the function.
chartSeries( f[,'AAPL.Close'], theme = chartTheme("white"), TA = c(addSMA(20),addSMA(50)) )
For many technical indicators we don't want to overlay them like above but to have a seperate chart panel for them. In this example I create a two row layout and fill the top row with the existing chart. The second row I fill with a typical MACD chart.
#Calculate MACD to be put in a lower panel f['macd'], f['macdsignal'], f['macdhist'] = MACD(numpy.asarray(f['Close']), fastperiod=12, slowperiod=26, signalperiod=9) #Plot stacked price and MACD chart plt.subplot(2, 1, 1) plt.gca().axes.get_xaxis().set_visible(False) f.plot(y= ['Close','SMA_20','SMA_50'], title='AAPL Close & Moving Averages') plt.subplot(2, 1, 2) f.plot(y= ['macdsignal','macd','macdhist'], title='MACD')