For the Webinar video, you can also visit: https://blog.quantinsti.com/ibridgepy-webinar-14-november-2019/
-----------------------------------------
Session Outline:
- IBridgePy installation
- A simple algorithmic trading strategy, daily close reverse
- Go through the code and basic functions used in this strategy
- Backtest strategy using historical data from IB in IBridgePy
- Backtest strategy using historical data from local csv file
- How to live trade a strategy
- Place orders to multiple accounts
- Analyze trading results from a strategy
Speaker Profile:
Dr. Hui Liu - Faculty, Executive Programme in Algorithmic Trading by QuantInsti
He is the author of IBridgePy (open-sourced software to trade with Interactive Brokers) and founder of Running River Investment LLC. His major trading interests are US equities and Forex market. Running River Investment LLC is a private hedge fund specialized in the development of automated trading strategies using Python.
He obtained his bachelor degree and master degree in materials science and engineering from Tsinghua University, China and Ph.D from University of Virginia, U.S.A. His MBA was from Indiana University, U.S.A and his study interest at Indiana was quantitative analysis.
-----------------------------------------
For the Webinar video, you can also visit: https://blog.quantinsti.com/ibridgepy-webinar-14-november-2019/
-----------------------------------------
Learn more about our EPAT® course here: https://www.quantinsti.com/epat/
OR Visit us at: https://www.quantinsti.com/
Like and Follow us on:
Facebook: https://www.facebook.com/quantinsti/
LinkedIn: https://www.linkedin.com/company/quantinsti
Twitter: https://twitter.com/QuantInsti
Backtesting and Live Trading Strategies with Interactive Brokers using Python
1. Backtesting and Live Trading with Interactive
Brokers using Python
Dr. Hui Liu
IBridgePy@gmail.com
www.IBridgePy.com
San Jose, CA, United States
Nov. 14th 2019
www.IBridgePy.com
2. Contents
• Intro of Algorithmic trading, Interactive Brokers and
IBridgePy
• Explain a simple trading strategy, Daily Close Reverse
• Implement Daily Close Reverse in IBridgePy
• Backtest the strategy
– Use historical data from IB
– Use historical data from other data providers
– Analyze backtest results
• Live trade the strategy
• Place orders to multiple accounts
3. Algo trading
Algorithmic trading is a method of executing orders using
automated pre-programmed trading instructions accounting
for variables such as time, price, and volume to send the
orders out to the market over time.
Benefits of algo trading
• Less pressure from constantly watching market
• Less human errors, most of things done by code
• More free time because of less manul works
• More profitable
How to algo trading?
Broker, internet, computer and programs
4. Interactive Brokers
Interactive Brokers LLC, IB, is a U.S.-based brokerage firm. It
operates the largest electronic trading platform in the U.S. by
number of daily average revenue trades.
www.interactivebrokers.com
Advantages of IB
• Advanced API technology
• Competitive pricing
• Global market access
How to do algo trading with IB?
Write python programs in IBridgePy, get connected to IB and
trade
5. IBridgePy
IBridgePy is a Python software, helping traders to set up
algo trading platform at their own computers or at virtual
computers in the cloud.
www.IBridgePy.com
Advantages of IBridgePy
• Protect trader’s intellectual properties
• Back test and live trade together
• Use any python packages, including AI and machine learning
• Trade with different brokers, IB and Robinhood
• Manage multiple accounts
• Run Quantopian algorithms
6. Preparation
1. Download IBridgePy from www.IBridgePy.com/download
2. Apply a paper/live account with Interactive Brokers
3. Download and install IB Gateway or Trader Workstation
https://www.interactivebrokers.com/en/index.php?f=14099#tws-software
https://www.interactivebrokers.com/en/index.php?f=16457
1. Config IB Gateway or TWS
2. Install Python
3. Check out IBridgePy tutorials
http://www.ibridgepy.com/tutorials/
Demo:
1. Config TWS
2. Config IB Gateway
7. IBridgePy Quick Demo
1. Open a Python environment
2. Open “RUN_ME.py”, the main entrance of IBridgePy
3. Find out your accountCode in IB Gateway
4. Change the accountCode in “RUN_ME.py” to your IB
accountCode, either real account or paper account
5. Choose an IBridgePy example code,
“example_show_positions.py” by commenting out all other
fileName lines by “#” in Python
6. Run/Execute “RUN_ME.py” in python
8. ● initialize is a function to declare global variables. It runs once
at the beginning. Required.
● handle_data is a function where trading decisions are made. It
runs every second(default)
● schedule_function is a function to schedule events.
Code structure
9. Show real time prices
# The sample code will print the ask price of SPY every second
def initialize(context):
context.security = symbol('SPY')
def handle_data(context, data):
ask_price = show_real_time_price(context.security, 'ask_price')
print ("SPY ask_price=", ask_price)
Demo: run example_show_real_time_price.py
10. Fetch historical data
# The sample code will fetch historical data of SPY, daily bar, go back 5 days
def initialize(context):
context.security = symbol('SPY')
def handle_data(context, data):
print ('Historical Data of %s' % (context.security,))
hist = request_historical_data(context.security, '1 day', '5 D')
print(hist)
end()
Historical Data of STK,SPY,USD
close high low open volume
2019-07-31 00:00:00+00:00 297.43 301.20 295.20 300.99 822384
2019-08-01 00:00:00+00:00 294.84 300.87 293.96 297.60 1121765
2019-08-02 00:00:00+00:00 292.62 294.12 290.90 293.85 831326
2019-08-05 00:00:00+00:00 283.82 288.21 281.72 288.09 1321027
2019-08-06 00:00:00+00:00 287.80 288.04 284.28 285.91 810061
11. Place order
# The sample code will place a limit order of 100 shares of SPY at $99.95 when
the ask price is greater than $100.01
def initialize(context):
context.security = symbol('SPY')
context.shares = 100
def handle_data(context, data):
ask_price = show_real_time_price(context.security, 'ask_price')
if ask_price > 100.01:
order(context.security, context.shares, LimitOrder(99.95)
end()
12. Stock screener
# This sample code will search securities with high social sentiment net and price is
higher than $100.00 in US major market
def handle_data(context, data):
response = get_scanner_results(instrument='STK', locationCode="STK.US.MAJOR",
scanCode='SCAN_socialSentimentNet_DESC',
abovePrice=100.0, numberOfRows=10)
print(response)
end()
legsStr projection rank security
0 0 STK,CI,USD
1 1 STK,STRA,USD
2 2 STK,FISV,USD
3 3 STK,HEI,USD
4 4 STK,JKHY,USD
5 5 STK,OLED,USD
6 6 STK,MPWR,USD
7 7 STK,NVDA,USD
8 8 STK,TFX,USD
9 9 STK,DIS,USD
13. Steps to build algo strategies
• What contracts do you want to trade? Read in from other
resources or from results of stock screener?
• How often do you plan to make trading decisions?
Every hour? Every minute? -- handle_data
At spot times? -- schedule_function
• Do you plan to calculate technical indicators?
If yes, you need request_historical_data
• What order type you want to place?
– LimitOrder StopOrder Trailing?
– MarketOrder?
14. Daily Close Reverse
Strategy description:
If today’s close price is lower than yesterday’s close price, buy
SPY using all cash. Otherwise, sell off all positions.
Strategy analysis:
• Daily reversion strategy
• Trading contract is hard-coded
• Need historical data
• Trading decision made at spot time
• Placing Market order for instant execution
15. Strategy code
def initialize(context):
context.security = symbol('SPY') # Define a security, SP500
ETF
schedule_function(dailyFunc, # decisions and actions are made in this function
date_rule=date_rules.every_day(), # dailyFunc is triggered every
day
time_rule=time_rules.market_close(minutes=1)) # at 15:59PM EST
def dailyFunc(context, data): # Trading decision and actions are made in this
function
hist = data.history(context.security, 'close', 2, '1d') # Retrieve historical data, daily
bars
close_yesterday = hist[-2]
close_today = hist[-1]
if close_today > close_yesterday:
order_target_percent(context.security, 0.0) # Sell off all
positions
else:
16. Moving average crossover
Strategy description:
If fast moving average starts to jump higher than slow moving
average, buy SPY using all cash. Otherwise, sell off all positions
Strategy analysis:
• Daily trend strategy
• Need historical data
• Trading decision made at a spot time
• Placing market order for instant execution
17. Strategy code
def initialize(context):
context.security = symbol('SPY') # Define a security, SP500
ETF
schedule_function(dailyFunc, # decisions and actions are made in this function
date_rule=date_rules.every_day(), # dailyFunc is triggered every
day
time_rule=time_rules.market_close(minutes=1)) # at 15:59PM EST
def dailyFunc(context, data): # Trading decision and actions are made in this
function
hist = data.history(context.security, 'close', 80, '1d') # Retrieve historical data, daily
bars
mv_5 = hist.rolling(5).mean()[-1] # Calculate fast moving
average
mv_60 = hist.rolling(60).mean()[-1] # Calculate slow moving
average
if mv_5 > mv_60:
order_target_percent(context.security, 1.0) # Buy SPY all cash
18. Backtesting fundamentals
Backtesting is the process of applying a trading strategy
to historical data to see how accurately the strategy or
method would have predicted actual results
1. Hist data can be supplied by IB or user’s csv files
2. IBridgePy simulates processing orders as IB server does,
supporting MarketOrder, LimitOrde and StopOrder
3. Simulated transactions are stored in the folder of
IBridgePy/Output TansactionLog_yyyy_mm_dd_hh_mm_ss.txt
4. Simulated Portfolio values are recorded in
IBridgePy/Output/balanceLog.txt
19. Backtesting using historical data from IB
Demo:
Open “TEST_ME_demo1.py”
Change the following values and explain
1. fileName
2. accountCode
3. Plan(security=symbol('SPY'), barSize='1 min', goBack='10 D'))
4. startTime
5. endTime
6. freq
Then, Run/Execute “TEST_ME_demo1.py”
Go to ~/Output/ to see BalanceLog and TransactionLog
20. Improvements
1. Fetch exactly same data from IB for every test, which may
violate IB’s pacing rules
2. Every minute bar in past 4 days goes through the code but
‘demo_close_price_reversion.py’ is only scheduled to run at
15:59:00 EST
3. User just want to test the program to find coding bugs, real
hist data are not critical for testing.
21. Backtest data supplied by user
Demo:
Open “TEST_ME_demo2.py”
Change the following values and explain
1. dataProviderName
2. histIngestionPlan
histIngestionPlan = HistIngestionPlan(defaultFolderName=os.path.join(os.getcwd(), 'Input'))
histIngestionPlan.add(Plan(security=symbol('SPY'), barSize='1 min', fileName='STK_SPY_USD_1min_20190726_20190808.csv'))
histIngestionPlan.add(Plan(security=symbol('SPY'), barSize='1 day', fileName='STK_SPY_USD_1day_20190726_20190808.csv'))
3. startTime
4. endTime
Pros: Accurate results, use other data sources defined by user
Cons: Need to provide hist data.
22. User-defined backtest spot time
Demo TEST_ME_demo3.py:
Add each backtest spot time into
customSpotTimeList, a reserved word
Pros: Backtest is much faster
Cons: Need to declare each backtest spot time
23. Backtest using random numbers
Demo TEST_ME_demo4.py:
dataProviderName = 'RANDOM'
Pros: No hist data. Quick to find coding bugs
Cons: Inaccurate portfolio balances
25. Go Live
• RUN_ME.py
• Paper account first
• Switch to live account and then Go live!
26. • IBridgePy is able to handle multiple accounts
A very useful feature for fund managers
Speaker: Dr. Hui Liu (www.IBridgePy.com |
In the following example, a signal triggers BUY 100
shares in account 1 and BUY 500 shares in account 2
Handle Multiple Accounts
27. Summary
• IBridgePy can help you:
– Set up your own algo trading platform
– Backtest and live trade together
– Trade with different brokers
– Manage multiple accounts
IBridgePy is Flexible and Easy-to-use