Plotting Financial Data With Python: History

Sometimes I need to plot some financial data and it might be tricky because most of the financial websites do not offer enough customization or they have a usage limitations unless you subscribe. So, I’ve decided to find a reliable data source and plot this data myself. Here are the basic steps that are necessary to do that.

This is the first part of the “Plotting Financial Data With Python” series and it’s better if you read it in chronological order:

  1. Part 1 - History (you are here)
  2. Part 2 - Variance
  3. Part 3 - Comparing Returns
  4. Part 4 - Efficient Frontier
  5. Part 5 - Efficient Frontier (N Assets)

Picking The Right Tools

There are 3 choices that have to be made before we start coding:

  1. Choose a data source
  2. Choose a programming language
  3. Choose a visualization library

Choosing a Data Source

There are many financial data sources but most of them are not free. There is nothing wrong with paying for high quality data but I don’t use it often enough to justify those costs so I use a free API called AlphaVantage unless it doesn’t have the data I need. I also use AlphaVantage API in this series but you can pick any other data source, it does not affect other parts of the code as long as you’ve got the relevant data.

Programming Language

I prefer to use Python for quick data visualizations since it’s widely adopted for such tasks. It’s also a really nice language for writing small utilities or integrating different parts of a big system.

Plotting Library

There are plenty of libraries for plotting data. Here is the list from the Python wiki: Plotting

I use Matplotlib since it’s widely adopted and it’s got everything that I need.

Here is their website: Matplotlib

Getting Started

This post assumes that you have Python 3 installed. If you have older version of Python you’re going to need some code adjustments.

Let’s create our project folder and give it a sensible name, such as /market-plots. It’s a good practice to isolate our little project from the rest of the system so we won’t mess with the global package registry.

Here is how we can create a local environment for a scope of this project:

cd market-plots
virtualenv venv

This command will create a folder called venv which will contain our project-scoped dependencies.

Let’s activate our virtual environment:

. venv/bin/activate

You can always exit your virtual environment by executing this command:

deactivate

Don’t do it now since we want to stay in our project-scoped environment. Let’s install the only dependency we need using the pip package manager:

pip install matplotlib

Now we have everything ready to start coding.

API

Let’s create a new file and call it alpha_vantage.py. It will wrap TIMESERIES list of functions, you can check the AlphaVantage API documentation for more details.

 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
import urllib.request as url_request
import json
from dateutil import parser
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

API_KEY = 'WVK0W8WGQRYMAYXS'
REQUEST_TIMEOUT_SECONDS = 20

def get_stock_price_history(symbol, interval, adjusted=False):
    url = url_for_function('TIME_SERIES_%s' % interval)

    if adjusted == True:
        url += '_ADJUSTED'

    url += '&apikey=%s' % API_KEY
    url += '&symbol=%s' % symbol
    url += '&outputsize=full'

    response = url_request.urlopen(url, timeout=REQUEST_TIMEOUT_SECONDS)
    data = json.load(response)
    meta_key, dates_key = data.keys()
    dates_data = data[dates_key]

    return {
        parser.parse(k): float(v[get_stock_price_field_name(adjusted)])
        for k, v
        in sorted(dates_data.items())
    }

def get_stock_price_field_name(adjusted):
    if adjusted == True:
        return '5. adjusted close'
    else:
        return '4. close'

def url_for_function(function):
    return 'https://www.alphavantage.co/query?function=%s' % function

The logic inside this file is quite straightforward. Let’s examine all of the arguments to understand how to use this function properly:

  • symbol - it’s just a stock trading symbol such as GOOG, TSLA and so on
  • interval - sampling interval, you can use DAILY, WEEKLY or MONTHLY intervals
  • adjusted - whether to use an absolute price or adjust for stock splits

Price History

Now since we have a financial API wrapper, let’s use it to plot stock price history. We need to add a new file called history.py which should contain the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import sys
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

import alpha_vantage

def show_history(symbol, interval='MONTHLY'):
    data = alpha_vantage.get_stock_price_history(symbol, interval)
    plt.plot(list(data.keys()), list(data.values()))

    plt.title('%s price history' % symbol)
    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.show()

show_history(sys.argv[1])

Let’s test this script by giving it a real query. We can lookup the S&P 500 index history by passing it’s symbol (SPX) as an argument to our new script:

$ python history.py SPX

You should see the chart similar to this one:

SPX

Conclusion

We’ve created a simple wrapper that allows us to query stock price history and used it to plot the data on screen. In the next post we will use this data to show the risk of different stocks.

Next Post: Part 2 - Variance