Why you should be Learning Python for Trading and Investing

Python
Python | Source

Python is Easy to use and Easy to Learn

Python is easy to use and easy to learn, yet extremely powerful.

It is widely used for server automation, running web applications, desktop applications, robotics, science, machine learning and more. And, yes, it is very much capable of handling large sets of financial data.

As Python is a scripting language it is easy to do iterative development of software as there is no compilation waiting time. At the same time it is possible to extend Python code with code in C or C++ for parts in the app or code library that need better optimization and better speeds. The scientific libraries that I will discuss later on in this post make extensive use of this possibility.

Guido van Rossum developed Python as a programming language that would help him automate his day to day work. He also based it on a programming language that was developed for teaching people how to code. Because of this Python is simple and practical in nature.

Plotting a Basic Line Graph is Easy with Matplotlib

Graphing is easy with matplotlib
Graphing is easy with matplotlib

Included: Idle the IDE for Python

Idle: simple but effective
Idle: simple but effective

There are Many Excelent Libraries to use when Researching Financial Data

I typically use the following Python libraries when I research trading and investing strategies:

  • The standard library
    Almost everything can be done with the standard library. Other non-standard libraries build upon this library to implement specific use cases and basically to make complicated stuff easier to implement.
  • SciPy
    This is a combination of libraries used for science, mathematics and engineering.
  • NumPy
    Part of SciPy and implements among other stuff matrices and vectorisation.
  • MatPlotLib
    Part of SciPy and implements advanced plotting capabilities.
  • Pandas
    Part of SciPy. Implements working with dataframes and timeseries.

Besides these libraries there are some additional libraries helpfull for data scraping, wrangling, munging and working with APIs:

  • BeautifulSoup
    Library for parsing HTML. Very useful if you want to get data from websites.
  • Mechanize
    This library allows for programmatical access to websites, like filling out a form and posting it, etc.
  • Requests
    Most APIs require authentication when accessing them. This can be accomplished using the tools in the standard library, but the Requests Library makes it almost "Curl" - like simple.

Also very powerful:

  • ScikitLearn
    A library that let's you implement machine learning algorithms.
  • NLTK
    Natural Language Toolkit, Makes sense out of unstructured text based data, like for instance twitter feeds, news, etc.

And to make your live as a researcher of trading strategies even more easy, there are many trading related APIs, that have a python library ready to access the data.

  • Pandas
    The web.DataReader method allows you to pull data from Yahoo Finance and Google Finance.
    Example:

    import pandas.io.data as web
    import datetime
    start = datetime.datetime(2010, 1, 1)
    end = datetime.datetime(2013, 1, 27)
    f = web.DataReader("AAPL", 'yahoo', start, end)
  • Quandl
    "Get millions of financial and economic datasets from hundreds of publishers directly into Python."

Example: Testing a Simple Strategy on Historical Financial Pricing Data

import pandas.io.data as web
import pandas
import datetime
import pylab
import math

def pairtrade(p1,p2):
    start = datetime.datetime(2008, 01, 01)
    end = datetime.datetime(2014, 03, 03)

    P1=web.DataReader(p1, 'yahoo', start, end)
    P1['Norm'] = (P1['Close'] - P1['Close'].shift(1)) /P1['Close']
    P1['Norm'] = P1['Norm'].fillna(0.0)

    P2=web.DataReader(p2, 'yahoo', start, end)
    P2['Norm'] = (P2['Close'] - P2['Close'].shift(1)) / P2['Close']
    P2['Norm'] = P2['Norm'].fillna(0.0)
    
    df = pandas.DataFrame(index = P1.index)
    df['diff'] = P2['Norm'] - P1['Norm']
    df['cum'] = df['diff'].cumsum()

    pylab.plot(P1.index,P1['Norm'].cumsum())
    pylab.plot(P2.index,P2['Norm'].cumsum())
    pylab.plot(df.index,df['cum'])
    pylab.title("Short: " + p1 + " and Long: " + p2 \
                + "\n MDD: " + str(highWM(df)) + " %" + " Sharpe: " + str(sharpe(df)))
    #pylab.show()
    pylab.savefig("Short_" + p1 + "_Long_" + p2 + ".png")
    pylab.close()
    return df

def highWM(df):
    maxDD = 0.0
    highWaterMark = 0.0
    for i in df.index:
        if df['cum'][i] < highWaterMark:
            drawDown = highWaterMark - df['cum'][i]
            if drawDown > maxDD:
                maxDD = drawDown
        if df['cum'][i] > highWaterMark:
            highWaterMark = df['cum'][i]
    return maxDD*100        

def sharpe(df):
    return ( df['diff'].mean() / df['diff'].std() ) * math.sqrt(len(df['diff']) )

def main():
    pairtrade('^aex', '^gdaxi')
    pairtrade('^aex', '^gspc')
    pairtrade('^aex', '^ftse')
    pairtrade('^aex', '^ixic')
    pairtrade('^aex', '^rut')

main()

So, will you Choose Python for Trading and Investing?

5 out of 5 stars from 1 rating of Python for trading and investing

Python gets Work done

Python can also be sued to automate all kind of tasks, like:

  • Checking if sites are up or down
  • Automated restarting of services
  • Generating configuration files
  • Making backups
  • Moving files around
  • And much more

To learn how to do all kinds of automation task, I recommend the book python for system administration

Other uses of Python

If you wanna use Python to research and develop your own trading and investing strategies, you can use most of the tools that I discussed here. If you are looking for ideas on how to use Python, then check out the Python related posts at www.davetromp.net.

Python for all

What do you use Python for?

See results without voting

More by this Author


3 comments

taiwokareem profile image

taiwokareem 14 months ago from Salford

Yeah, it's good meeting someone with similar interests here. Even though i'm still learning. it's a good opportunity to learn extra.


davetromp profile image

davetromp 14 months ago from Amsterdam Author

Taiwokareem, Great to hear. I will look into your module. All it takes is pip install eventsim. This is why I like python. Very strong community. Someone almost always already build a solution that helps you solve your problem. Thanks.


taiwokareem profile image

taiwokareem 14 months ago from Salford

Python is a great Programming language because of its simplicity as opposed to C++. I like Ruby as well and even created a module called "eventsim" on the python packaging index for simulating events in the workplace. Simple but useful mainly for simulating things like inter-arrival time, arrival time, service begin and end times etc.

But Python is really my first choice programming language along with Ruby.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working