Investing with Python: Query Stock Data, Calculate 30 Day Moving Average

Python streamlines tasks requiring multiple steps in a single block of code. For this reason, it is a great tool for querying and performing analysis on data. In this post we will use Python to pull ticker data for a specific stock and then calculate its 30 day moving average. Here are the steps:

1. Import the pandas modules.

import pandas as pd
import pandas.io.data as web

2. Create a list of the stocks for which you would like to query ticker data. For this example, we will pull ticker data for Facebook, ‘FB’. If you would like to add other stocks, simply add the symbols to the list separated by commas.

stocks = ['FB']

Or

stocks = ['FB','AAPL','GOOG','AMZN']

3. Write function to query data from yahoo finance. The function takes three arguments: the stock, the start date, and the end date. It returns the daily ‘Adj Close’. If you would like to pull a different value, simply switch it for ‘Adj Close’ without the brackets.

def get_stock(stock,start,end):
     return web.get_data_yahoo(stock,start,end)['Adj Close']

Or

def get_stock(stock,start,end):
     return web.get_data_yahoo(stock,start,end)['Volume']

4. Call function for the date range, 1/1/2016 – 12/31/2016. Use the ‘for n in stocks’ logic in case you have more than one stock for which you would like to pull data. Compile query in DataFrame, saved to variable ‘px’.

px = pd.DataFrame({n: get_stock(n, '1/1/2016', '12/31/2016') for n in stocks})

5. Add new column to DataFrame in which you calculate the 30 day moving average. Call DataFrame to view contents.

px['30 mavg'] = pd.rolling_mean(px, 30)
px

There you have it! We created a DataFrame containing the daily ticker data for a specific stock and then calculated its 30 day moving average. Here is the full code:

import pandas as pd
import pandas.io.data as web

stocks = ['FB']
def get_stock(stock, start, end):
     return web.get_data_yahoo(stock, start, end)['Adj Close']
px = pd.DataFrame({n: get_px(n, '1/1/2016', '12/31/2016') for n in names})
px['30 mavg'] = pd.rolling_mean(px, 30)
px