Python vs R #2: Adding Technical Analysis Indicators to Charts

This 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.

Python

I start with the code from the previous entry in the series for downloading the closing stock prices from Yahoo

Importing 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

R code from the previous entry in the series for downloading the closing stock price from Yahoo

Importing 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.
import talib
TTR is the R library that I will be using to calculate the technical indicators.
require(TTR)
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')
Python Simple Stock Chart with MAs
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))
      )
R Simple Stock Chart with MAs
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')
Python Simple Stock Chart with MAs and MACD
This is where an existing library functionality comes in handy as the chartSeries function takes care of many of the issues with new panels and the look and feel of a financial chart.
chartSeries(
        f[,'AAPL.Close'],
        theme = chartTheme("white"),
        TA = c(addSMA(20),addSMA(50),addMACD(12,26,9))
      )
R Simple Stock Chart with MAs and MACD
Again both languages are very similar and require roughly the same amount of syntax to complete the simple task but the use of the built in functionality of Quantmod to chart financial time series reduces the amount of code in R. While I have found many python modules for backtesting there does not seem to be a consensus module for nice financial charting in Python, like in R. Let me know in the comments if there is one out there. Next in the series will be creating a very simple backtesting model.

By Jon Eickmeier | March 25, 2014 | analysis R Python programming quantitative comparisons trading

Comments Section

comments powered by Disqus