Book Image

Mastering Python for Finance

Book Image

Mastering Python for Finance

Overview of this book

Table of Contents (17 chapters)
Mastering Python for Finance
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Building a mean-reverting algorithmic trading system


In the previous section, we established a connection to IB TWS and sent a market order of 100 shares. In this section, we will add logic functions to buy or sell a number of shares, read tick data, and track our positions. In essence, we will try to create a simple, fully automated algorithmic trading system.

Setting up the main program

Since our code might get a little complicated, let's tidy up and put everything into a class named AlgoSystem. We will import the following modules:

from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message
import time
import pandas as pd
import datetime as dt

In the initialization section of our class, declare the following variables:

def __init__(self, symbol, qty, resample_interval,
             averaging_period=5, port=7496):
    self.client_id = 1
    self.order_id = 1
    self.qty = qty
    self.symbol_id, self.symbol = 0, symbol
    self.resample_interval...