Exploring Ally Financial’s API

One of my passions is analyzing stock and option data. Although I love trading, I find looking for an edge in the data to be the most fun part of the game (besides making money, of course). Since I learned about using API’s in the Data Analysis class in which I’m currently enrolled, I decided to flex my new skills and connect to a broker’s API so I can start collecting more data for my first trading algorithm.

For anyone interested using the Ally Financial API to collect and analyze data, I have put together a brief cheat sheet to help you get started making the API calls and outputting the data to a Pandas’ dataframe.

It contains the following examples:

  • Time and Sales for Stocks
  • Options Market Depth
  • Options Extended Quote

Click here to check out my Ally Financial API Cheat Sheet on my github. It is written for Python 3

#!/usr/bin/env python
# coding: utf-8

# # Ally Financial API Cheat Sheet
# * Refer to the documentation for additional routes:
# * https://www.ally.com/api/invest/documentation/getting-started/

import requests
from requests_oauthlib import OAuth1
from config import (api_key, secret, oath_token, oath_secret)

import pandas as pd
import sqlalchemy
import numpy as np

import sqlite3
from sqlite3 import Error

import matplotlib.pyplot as plt
import datetime as dt


#authentication 
auth = OAuth1(api_key, secret, oath_token, oath_secret)


# # Time and Sales for Stocks Example
# * documentation: https://www.ally.com/api/invest/documentation/market-timesales-get/ 
# * base url: https://api.tradeking.com/
# * route: v1/market/timesales.json
# * query: ?symbols=MSFT&startdate=2019-05-03&interval=1min


#url 
url = 'https://api.tradeking.com/v1/market/timesales.json?symbols=MSFT&startdate=2019-05-03&interval=1min'


#api request
response = requests.get(url, auth = auth).json()


#send to data frame and format data types
df = pd.DataFrame(response["response"]["quotes"]["quote"])
df = df.sort_values(['datetime'], ascending = False)
df['date'] = pd.to_datetime(df['date'])
df['datetime'] = pd.to_datetime(df['datetime'],  utc=False).dt.tz_convert('US/Central')
df['hi'] = df["hi"].astype(float)
df['incr_vol'] = df["incr_vl"].astype(float)
df['last'] = df["last"].astype(float)
df['lo'] = df["lo"].astype(float)
df['opn'] = df["opn"].astype(float)
df['vl'] = df['vl'].astype(float)
df.head()



#resample the time value to be greater than 1 min as needed. Example: 30 min resample for last price
df.set_index(df['datetime'], inplace = True)
df.head()
df_resample30 = df.resample(rule = '30min', label = 'right').last()
df_resample30.head()


# # Options Search Example
# * Provides market depth for options
# * Documentation: https://www.ally.com/api/invest/documentation/market-options-search-get-post/
# * base url: https://api.tradeking.com/
# * route: v1/market/timesales.json
# * query: ?symbol=MSFT&query=xyear-eq%3A2019%20AND%20xmonth-eq%3A06%20AND%20strikeprice-eq%3A140
# 
# 
# * Query breakdown:
#     * exipiration year equals 2019:
#     * xyear-eq%3A 2019
# 
#     * and:
#     * %20AND%20
# 
#     * expiration month equals 06:
#     * xmonth-eq%3A 06
# 
#     * and strike price equals 140:
#     * %20AND%20 strikeprice -eq%3A 140
# 
# 
# * Operators:
#     * lt :	less than
#     * gt :	greater than
#     * gte :	greater than or equal to
#     * lte :	less than or equal to
#     * eq :	equal to


url = 'https://api.tradeking.com/v1/market/options/search.json?symbol=MSFT&query=xyear-eq%3A2019%20AND%20xmonth-eq%3A06%20AND%20strikeprice-eq%3A140'
response = requests.get(url, auth = auth).json()


df = pd.DataFrame(response["response"]["quotes"]["quote"])
df


# # Extended Quote Example (Option)
# * Works for stocks too
# * Documentation: https://www.ally.com/api/invest/documentation/market-ext-quotes-get-post/
# * base url: https://api.tradeking.com/
# * route: v1/market/ext/quotes.json
# * query: ?symbols=MSFT190607C00140000
# 
# * Option Symbol naming convention:
#     * Underlying symbol - MSFT
#     * 2 digit expiration year - 19
#     * 2 digit expiration month - 06
#     * 2 digit expiration day - 07
#     * "C" for Call or "P" for Put - C
#     * 8 digit strike price - 00140000
#     
# 
# * Specify desired fields in the query as needed using fids: 
#     * i.e. fids=ask,bid,vol


url = 'https://api.tradeking.com/v1/market/ext/quotes.json?symbols=MSFT190607C00140000'
response = requests.get(url, auth = auth).json()


df = pd.DataFrame(response["response"]["quotes"]["quote"], index = [0])
df

%d bloggers like this: