Python vs R #1: Getting Stock Prices

I have been using mostly R for a long time in my data analysis and quantitative trading work, but I would like to brush up on my Python skills that I haven't used as much. In order to keep me focused, I would like to produce side-by-side comparisons of the two languages for various tasks that are used extensively in quantittive trading. This is the first in that series and it looks at downloading stock prices and creating a very simple plot of the closing prices using the default look and feel of each language.

Python

Python's main library for storing and working with time series data is pandas and helpfully it also includes functionality to download stock prices from Yahoo as well other financial data from Google, St Louis FED, Kenneth French factor data and the World Bank.

Importing required libraries of pandas for time series analysis and datetime for manipulating dates.
import pandas.io.data as web
    import datetime

R

R's main library for working with time series data is xts, although there are several older and built in ways to work with time series. Quantmod is an additional library that builds on xts with many additional features for quantitative trading analysis, the most important of which for our current task is the ability to load data from Yahoo.

Importing required libraries of xts for time series analysis and quantmod for downloading data from Yahoo.
require(xts)  
    require(quantmod)
Set up date range, the ticker to download and then download stock prices using the DataReader function from the pandas external data module.
start = datetime.datetime(2010,1,1)
    end = datetime.datetime(2014,3,24)
    ticker = "AAPL"
    f=web.DataReader(ticker,'yahoo',start,end)
Set up data range, the ticker to download and download stock prices using the getSymbols function in the Quantmod library.
start = '2010-01-01'
    end = '2014-03-24'
    ticker = 'AAPL'
    f = getSymbols(ticker, src = 'yahoo', from = start, to = end, auto.assign=F)
To plot closing stock prices in Python we use the matplotlib.
import matplotlib.pyplot as plt
    plt.plot(f['Close'])
    plt.title('AAPL Closing Prices')
    plt.show()
Python Simple Stock Chart
To plot closing stock prices we use the default plot function in R.
plot(f[,'AAPL.Close'], main='AAPL Closing Prices')
R Simple Stock Chart
As you can see both languages (at least at this very early comparison) are very similar and require roughly the same amount of syntax to complete the task of downloading stock quotes and creating a very simple graph of the closing prices. Next in the series will be calculating technical analysis values and adding them to the charts.

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

Comments Section

comments powered by Disqus