SlideShare a Scribd company logo
1 of 31
Download to read offline
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
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
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
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
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
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
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
● 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
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
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
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()
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
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?
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
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:
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
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
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
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
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.
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.
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
Backtest using random numbers
Demo TEST_ME_demo4.py:
dataProviderName = 'RANDOM'
Pros: No hist data. Quick to find coding bugs
Cons: Inaccurate portfolio balances
Performance analysis
Daily portfolio balances
Transaction Log
Demo Input/performanceAnalysisChart.py
Go Live
• RUN_ME.py
• Paper account first
• Switch to live account and then Go live!
• 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
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
EPAT®
Webinar video link:
http://bit.ly/IBridgePy
Backtesting and Live Trading Strategies with Interactive Brokers using Python

More Related Content

What's hot

"Quant Trading for a Living – Lessons from a Life in the Trenches" by Andreas...
"Quant Trading for a Living – Lessons from a Life in the Trenches" by Andreas..."Quant Trading for a Living – Lessons from a Life in the Trenches" by Andreas...
"Quant Trading for a Living – Lessons from a Life in the Trenches" by Andreas...Quantopian
 
Being open (source) in the traditionally secretive field of quant finance.
Being open (source) in the traditionally secretive field of quant finance.Being open (source) in the traditionally secretive field of quant finance.
Being open (source) in the traditionally secretive field of quant finance.Quantopian
 
"From Alpha Discovery to Portfolio Construction: Pitfalls and Solutions" by D...
"From Alpha Discovery to Portfolio Construction: Pitfalls and Solutions" by D..."From Alpha Discovery to Portfolio Construction: Pitfalls and Solutions" by D...
"From Alpha Discovery to Portfolio Construction: Pitfalls and Solutions" by D...Quantopian
 
"Portfolio Optimisation When You Don’t Know the Future (or the Past)" by Rob...
"Portfolio Optimisation When You Don’t Know the Future (or the Past)" by Rob..."Portfolio Optimisation When You Don’t Know the Future (or the Past)" by Rob...
"Portfolio Optimisation When You Don’t Know the Future (or the Past)" by Rob...Quantopian
 
From Backtesting to Live Trading by Vesna Straser at QuantCon 2016
From Backtesting to Live Trading by Vesna Straser at QuantCon 2016From Backtesting to Live Trading by Vesna Straser at QuantCon 2016
From Backtesting to Live Trading by Vesna Straser at QuantCon 2016Quantopian
 
Automated Selection and Robustness for Systematic Trading Strategies by Dr. T...
Automated Selection and Robustness for Systematic Trading Strategies by Dr. T...Automated Selection and Robustness for Systematic Trading Strategies by Dr. T...
Automated Selection and Robustness for Systematic Trading Strategies by Dr. T...Quantopian
 
"Deep Q-Learning for Trading" by Dr. Tucker Balch, Professor of Interactive C...
"Deep Q-Learning for Trading" by Dr. Tucker Balch, Professor of Interactive C..."Deep Q-Learning for Trading" by Dr. Tucker Balch, Professor of Interactive C...
"Deep Q-Learning for Trading" by Dr. Tucker Balch, Professor of Interactive C...Quantopian
 
Technology Edge in Algo Trading: Traditional Vs Automated Trading System Arch...
Technology Edge in Algo Trading: Traditional Vs Automated Trading System Arch...Technology Edge in Algo Trading: Traditional Vs Automated Trading System Arch...
Technology Edge in Algo Trading: Traditional Vs Automated Trading System Arch...QuantInsti
 
Simulating HFT for Low-Latency Investors - The Investor’s View (Robert Almgren)
Simulating HFT for Low-Latency Investors - The Investor’s View (Robert Almgren)Simulating HFT for Low-Latency Investors - The Investor’s View (Robert Almgren)
Simulating HFT for Low-Latency Investors - The Investor’s View (Robert Almgren)CBS Competitiveness Platform
 
Master trend-following
Master trend-followingMaster trend-following
Master trend-followingVarlei Rezer
 
The Impact of Algorithmic Trading
The Impact of Algorithmic TradingThe Impact of Algorithmic Trading
The Impact of Algorithmic TradingLov Loothra
 
Algorithmic Trading: an Overview
Algorithmic Trading: an Overview Algorithmic Trading: an Overview
Algorithmic Trading: an Overview EXANTE
 
Dual Momentum Investing by Gary Antonacci QuantCon 2016
Dual Momentum Investing by Gary Antonacci QuantCon 2016Dual Momentum Investing by Gary Antonacci QuantCon 2016
Dual Momentum Investing by Gary Antonacci QuantCon 2016Quantopian
 
Fibonacci retracement level
Fibonacci retracement levelFibonacci retracement level
Fibonacci retracement levelpipsumo traderfx
 
"Enhancing Statistical Significance of Backtests" by Dr. Ernest Chan, Managin...
"Enhancing Statistical Significance of Backtests" by Dr. Ernest Chan, Managin..."Enhancing Statistical Significance of Backtests" by Dr. Ernest Chan, Managin...
"Enhancing Statistical Significance of Backtests" by Dr. Ernest Chan, Managin...Quantopian
 
"A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ...
"A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ..."A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ...
"A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ...Quantopian
 
"Build Effective Risk Management on Top of Your Trading Strategy" by Danielle...
"Build Effective Risk Management on Top of Your Trading Strategy" by Danielle..."Build Effective Risk Management on Top of Your Trading Strategy" by Danielle...
"Build Effective Risk Management on Top of Your Trading Strategy" by Danielle...Quantopian
 
"Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an...
"Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an..."Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an...
"Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an...Quantopian
 
Quant trading with artificial intelligence
Quant trading with artificial intelligenceQuant trading with artificial intelligence
Quant trading with artificial intelligenceRoger Lee, CFA
 

What's hot (20)

"Quant Trading for a Living – Lessons from a Life in the Trenches" by Andreas...
"Quant Trading for a Living – Lessons from a Life in the Trenches" by Andreas..."Quant Trading for a Living – Lessons from a Life in the Trenches" by Andreas...
"Quant Trading for a Living – Lessons from a Life in the Trenches" by Andreas...
 
Being open (source) in the traditionally secretive field of quant finance.
Being open (source) in the traditionally secretive field of quant finance.Being open (source) in the traditionally secretive field of quant finance.
Being open (source) in the traditionally secretive field of quant finance.
 
"From Alpha Discovery to Portfolio Construction: Pitfalls and Solutions" by D...
"From Alpha Discovery to Portfolio Construction: Pitfalls and Solutions" by D..."From Alpha Discovery to Portfolio Construction: Pitfalls and Solutions" by D...
"From Alpha Discovery to Portfolio Construction: Pitfalls and Solutions" by D...
 
"Portfolio Optimisation When You Don’t Know the Future (or the Past)" by Rob...
"Portfolio Optimisation When You Don’t Know the Future (or the Past)" by Rob..."Portfolio Optimisation When You Don’t Know the Future (or the Past)" by Rob...
"Portfolio Optimisation When You Don’t Know the Future (or the Past)" by Rob...
 
From Backtesting to Live Trading by Vesna Straser at QuantCon 2016
From Backtesting to Live Trading by Vesna Straser at QuantCon 2016From Backtesting to Live Trading by Vesna Straser at QuantCon 2016
From Backtesting to Live Trading by Vesna Straser at QuantCon 2016
 
Automated Selection and Robustness for Systematic Trading Strategies by Dr. T...
Automated Selection and Robustness for Systematic Trading Strategies by Dr. T...Automated Selection and Robustness for Systematic Trading Strategies by Dr. T...
Automated Selection and Robustness for Systematic Trading Strategies by Dr. T...
 
"Deep Q-Learning for Trading" by Dr. Tucker Balch, Professor of Interactive C...
"Deep Q-Learning for Trading" by Dr. Tucker Balch, Professor of Interactive C..."Deep Q-Learning for Trading" by Dr. Tucker Balch, Professor of Interactive C...
"Deep Q-Learning for Trading" by Dr. Tucker Balch, Professor of Interactive C...
 
Technology Edge in Algo Trading: Traditional Vs Automated Trading System Arch...
Technology Edge in Algo Trading: Traditional Vs Automated Trading System Arch...Technology Edge in Algo Trading: Traditional Vs Automated Trading System Arch...
Technology Edge in Algo Trading: Traditional Vs Automated Trading System Arch...
 
Simulating HFT for Low-Latency Investors - The Investor’s View (Robert Almgren)
Simulating HFT for Low-Latency Investors - The Investor’s View (Robert Almgren)Simulating HFT for Low-Latency Investors - The Investor’s View (Robert Almgren)
Simulating HFT for Low-Latency Investors - The Investor’s View (Robert Almgren)
 
Master trend-following
Master trend-followingMaster trend-following
Master trend-following
 
The Impact of Algorithmic Trading
The Impact of Algorithmic TradingThe Impact of Algorithmic Trading
The Impact of Algorithmic Trading
 
Algorithmic Trading: an Overview
Algorithmic Trading: an Overview Algorithmic Trading: an Overview
Algorithmic Trading: an Overview
 
Dual Momentum Investing by Gary Antonacci QuantCon 2016
Dual Momentum Investing by Gary Antonacci QuantCon 2016Dual Momentum Investing by Gary Antonacci QuantCon 2016
Dual Momentum Investing by Gary Antonacci QuantCon 2016
 
Fibonacci retracement level
Fibonacci retracement levelFibonacci retracement level
Fibonacci retracement level
 
Algo Trading
Algo TradingAlgo Trading
Algo Trading
 
"Enhancing Statistical Significance of Backtests" by Dr. Ernest Chan, Managin...
"Enhancing Statistical Significance of Backtests" by Dr. Ernest Chan, Managin..."Enhancing Statistical Significance of Backtests" by Dr. Ernest Chan, Managin...
"Enhancing Statistical Significance of Backtests" by Dr. Ernest Chan, Managin...
 
"A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ...
"A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ..."A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ...
"A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ...
 
"Build Effective Risk Management on Top of Your Trading Strategy" by Danielle...
"Build Effective Risk Management on Top of Your Trading Strategy" by Danielle..."Build Effective Risk Management on Top of Your Trading Strategy" by Danielle...
"Build Effective Risk Management on Top of Your Trading Strategy" by Danielle...
 
"Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an...
"Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an..."Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an...
"Quantitative Trading as a Mathematical Science" by Dr. Haksun Li, Founder an...
 
Quant trading with artificial intelligence
Quant trading with artificial intelligenceQuant trading with artificial intelligence
Quant trading with artificial intelligence
 

Similar to Backtesting and Live Trading Strategies with Interactive Brokers using Python

Cis 115 Education Redefined-snaptutorial.com
Cis 115 Education Redefined-snaptutorial.comCis 115 Education Redefined-snaptutorial.com
Cis 115 Education Redefined-snaptutorial.comrobertledwes38
 
Sales force certification-lab
Sales force certification-labSales force certification-lab
Sales force certification-labAmit Sharma
 
Apex code Benchmarking
Apex code BenchmarkingApex code Benchmarking
Apex code BenchmarkingAmit Chaudhary
 
SplunkSummit 2015 - Security Ninjitsu
SplunkSummit 2015 - Security NinjitsuSplunkSummit 2015 - Security Ninjitsu
SplunkSummit 2015 - Security NinjitsuSplunk
 
Baltimore MuleSoft Meetup #8
Baltimore MuleSoft Meetup #8Baltimore MuleSoft Meetup #8
Baltimore MuleSoft Meetup #8ManjuKumara GH
 
Sales force certification-lab
Sales force certification-labSales force certification-lab
Sales force certification-labAmit Sharma
 
Dropwizard with MongoDB and Google Cloud
Dropwizard with MongoDB and Google CloudDropwizard with MongoDB and Google Cloud
Dropwizard with MongoDB and Google CloudYun Zhi Lin
 
Introduction to trader bots with Python
Introduction to trader bots with PythonIntroduction to trader bots with Python
Introduction to trader bots with Pythonroskakori
 
Trading: How to attain maximum advantage while trading?
Trading: How to attain maximum advantage while trading?Trading: How to attain maximum advantage while trading?
Trading: How to attain maximum advantage while trading?Knoldus Inc.
 
Scaling AutoML-Driven Anomaly Detection With Luminaire
Scaling AutoML-Driven Anomaly Detection With LuminaireScaling AutoML-Driven Anomaly Detection With Luminaire
Scaling AutoML-Driven Anomaly Detection With LuminaireDatabricks
 
Implementing Your Full Stack App with MongoDB Stitch (Tutorial)
Implementing Your Full Stack App with MongoDB Stitch (Tutorial)Implementing Your Full Stack App with MongoDB Stitch (Tutorial)
Implementing Your Full Stack App with MongoDB Stitch (Tutorial)MongoDB
 
Subscribed zuora forsalesforce training -section301-final
Subscribed zuora forsalesforce training -section301-finalSubscribed zuora forsalesforce training -section301-final
Subscribed zuora forsalesforce training -section301-finalSamuel Sharaf
 
Welcome Webinar Slides
Welcome Webinar SlidesWelcome Webinar Slides
Welcome Webinar SlidesSumo Logic
 
Supporting Enterprise System Rollouts with Splunk
Supporting Enterprise System Rollouts with SplunkSupporting Enterprise System Rollouts with Splunk
Supporting Enterprise System Rollouts with SplunkErin Sweeney
 
How to design quant trading strategies using “R”?
How to design quant trading strategies using “R”?How to design quant trading strategies using “R”?
How to design quant trading strategies using “R”?QuantInsti
 
Asynchronous Apex Salesforce World Tour Paris 2015
Asynchronous Apex Salesforce World Tour Paris 2015Asynchronous Apex Salesforce World Tour Paris 2015
Asynchronous Apex Salesforce World Tour Paris 2015Samuel De Rycke
 
Market Basket Analysis in SAS
Market Basket Analysis in SASMarket Basket Analysis in SAS
Market Basket Analysis in SASAndrew Kramer
 

Similar to Backtesting and Live Trading Strategies with Interactive Brokers using Python (20)

Write bulletproof trigger code
Write bulletproof trigger codeWrite bulletproof trigger code
Write bulletproof trigger code
 
Cis 115 Education Redefined-snaptutorial.com
Cis 115 Education Redefined-snaptutorial.comCis 115 Education Redefined-snaptutorial.com
Cis 115 Education Redefined-snaptutorial.com
 
Sales force certification-lab
Sales force certification-labSales force certification-lab
Sales force certification-lab
 
Apex code Benchmarking
Apex code BenchmarkingApex code Benchmarking
Apex code Benchmarking
 
SplunkSummit 2015 - Security Ninjitsu
SplunkSummit 2015 - Security NinjitsuSplunkSummit 2015 - Security Ninjitsu
SplunkSummit 2015 - Security Ninjitsu
 
Baltimore MuleSoft Meetup #8
Baltimore MuleSoft Meetup #8Baltimore MuleSoft Meetup #8
Baltimore MuleSoft Meetup #8
 
Sales force certification-lab
Sales force certification-labSales force certification-lab
Sales force certification-lab
 
Dropwizard with MongoDB and Google Cloud
Dropwizard with MongoDB and Google CloudDropwizard with MongoDB and Google Cloud
Dropwizard with MongoDB and Google Cloud
 
Introduction to trader bots with Python
Introduction to trader bots with PythonIntroduction to trader bots with Python
Introduction to trader bots with Python
 
Database training for developers
Database training for developersDatabase training for developers
Database training for developers
 
Trading: How to attain maximum advantage while trading?
Trading: How to attain maximum advantage while trading?Trading: How to attain maximum advantage while trading?
Trading: How to attain maximum advantage while trading?
 
Scaling AutoML-Driven Anomaly Detection With Luminaire
Scaling AutoML-Driven Anomaly Detection With LuminaireScaling AutoML-Driven Anomaly Detection With Luminaire
Scaling AutoML-Driven Anomaly Detection With Luminaire
 
WSO2 Complex Event Processor
WSO2 Complex Event ProcessorWSO2 Complex Event Processor
WSO2 Complex Event Processor
 
Implementing Your Full Stack App with MongoDB Stitch (Tutorial)
Implementing Your Full Stack App with MongoDB Stitch (Tutorial)Implementing Your Full Stack App with MongoDB Stitch (Tutorial)
Implementing Your Full Stack App with MongoDB Stitch (Tutorial)
 
Subscribed zuora forsalesforce training -section301-final
Subscribed zuora forsalesforce training -section301-finalSubscribed zuora forsalesforce training -section301-final
Subscribed zuora forsalesforce training -section301-final
 
Welcome Webinar Slides
Welcome Webinar SlidesWelcome Webinar Slides
Welcome Webinar Slides
 
Supporting Enterprise System Rollouts with Splunk
Supporting Enterprise System Rollouts with SplunkSupporting Enterprise System Rollouts with Splunk
Supporting Enterprise System Rollouts with Splunk
 
How to design quant trading strategies using “R”?
How to design quant trading strategies using “R”?How to design quant trading strategies using “R”?
How to design quant trading strategies using “R”?
 
Asynchronous Apex Salesforce World Tour Paris 2015
Asynchronous Apex Salesforce World Tour Paris 2015Asynchronous Apex Salesforce World Tour Paris 2015
Asynchronous Apex Salesforce World Tour Paris 2015
 
Market Basket Analysis in SAS
Market Basket Analysis in SASMarket Basket Analysis in SAS
Market Basket Analysis in SAS
 

More from QuantInsti

ChatGPT and Machine Learning in Trading
ChatGPT and Machine Learning in TradingChatGPT and Machine Learning in Trading
ChatGPT and Machine Learning in TradingQuantInsti
 
Introduction to Quantitative Factor Investing
Introduction to Quantitative Factor InvestingIntroduction to Quantitative Factor Investing
Introduction to Quantitative Factor InvestingQuantInsti
 
Machine Learning for Options Trading
Machine Learning for Options TradingMachine Learning for Options Trading
Machine Learning for Options TradingQuantInsti
 
Portfolio Assets Allocation with Machine Learning
Portfolio Assets Allocation with Machine LearningPortfolio Assets Allocation with Machine Learning
Portfolio Assets Allocation with Machine LearningQuantInsti
 
Price Action Trading - An Introduction
Price Action Trading - An IntroductionPrice Action Trading - An Introduction
Price Action Trading - An IntroductionQuantInsti
 
Introduction to Systematic Options Trading
Introduction to Systematic Options TradingIntroduction to Systematic Options Trading
Introduction to Systematic Options TradingQuantInsti
 
Competitive Edges in Algorithmic Trading
Competitive Edges in Algorithmic TradingCompetitive Edges in Algorithmic Trading
Competitive Edges in Algorithmic TradingQuantInsti
 
Volatility Trading: Trading The Fear Index VIX
Volatility Trading: Trading The Fear Index VIXVolatility Trading: Trading The Fear Index VIX
Volatility Trading: Trading The Fear Index VIXQuantInsti
 
Big Data And The Future Of Retail Investing
Big Data And The Future Of Retail InvestingBig Data And The Future Of Retail Investing
Big Data And The Future Of Retail InvestingQuantInsti
 
Backtest of Short Straddles on SPX Index
Backtest of Short Straddles on SPX IndexBacktest of Short Straddles on SPX Index
Backtest of Short Straddles on SPX IndexQuantInsti
 
Pairs Trading In the Brazilian Stock Market
Pairs Trading In the Brazilian Stock MarketPairs Trading In the Brazilian Stock Market
Pairs Trading In the Brazilian Stock MarketQuantInsti
 
How To Set Up Automated Trading
How To Set Up Automated TradingHow To Set Up Automated Trading
How To Set Up Automated TradingQuantInsti
 
How To Set Up Automated Trading
How To Set Up Automated TradingHow To Set Up Automated Trading
How To Set Up Automated TradingQuantInsti
 
Quantitative Data Analysis of Cryptocurrencies
Quantitative Data Analysis of CryptocurrenciesQuantitative Data Analysis of Cryptocurrencies
Quantitative Data Analysis of CryptocurrenciesQuantInsti
 
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...Introduction to Quantitative Trading - Investment Management Club of Yale Uni...
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...QuantInsti
 
How to automate an options day trading strategy
How to automate an options day trading strategyHow to automate an options day trading strategy
How to automate an options day trading strategyQuantInsti
 
Predict daily stock prices with random forest classifier, technical indicator...
Predict daily stock prices with random forest classifier, technical indicator...Predict daily stock prices with random forest classifier, technical indicator...
Predict daily stock prices with random forest classifier, technical indicator...QuantInsti
 
How Pandemics Impact the Financial Markets - A Quantitative Analysis
How Pandemics Impact the Financial Markets - A Quantitative AnalysisHow Pandemics Impact the Financial Markets - A Quantitative Analysis
How Pandemics Impact the Financial Markets - A Quantitative AnalysisQuantInsti
 
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...QuantInsti
 
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...QuantInsti
 

More from QuantInsti (20)

ChatGPT and Machine Learning in Trading
ChatGPT and Machine Learning in TradingChatGPT and Machine Learning in Trading
ChatGPT and Machine Learning in Trading
 
Introduction to Quantitative Factor Investing
Introduction to Quantitative Factor InvestingIntroduction to Quantitative Factor Investing
Introduction to Quantitative Factor Investing
 
Machine Learning for Options Trading
Machine Learning for Options TradingMachine Learning for Options Trading
Machine Learning for Options Trading
 
Portfolio Assets Allocation with Machine Learning
Portfolio Assets Allocation with Machine LearningPortfolio Assets Allocation with Machine Learning
Portfolio Assets Allocation with Machine Learning
 
Price Action Trading - An Introduction
Price Action Trading - An IntroductionPrice Action Trading - An Introduction
Price Action Trading - An Introduction
 
Introduction to Systematic Options Trading
Introduction to Systematic Options TradingIntroduction to Systematic Options Trading
Introduction to Systematic Options Trading
 
Competitive Edges in Algorithmic Trading
Competitive Edges in Algorithmic TradingCompetitive Edges in Algorithmic Trading
Competitive Edges in Algorithmic Trading
 
Volatility Trading: Trading The Fear Index VIX
Volatility Trading: Trading The Fear Index VIXVolatility Trading: Trading The Fear Index VIX
Volatility Trading: Trading The Fear Index VIX
 
Big Data And The Future Of Retail Investing
Big Data And The Future Of Retail InvestingBig Data And The Future Of Retail Investing
Big Data And The Future Of Retail Investing
 
Backtest of Short Straddles on SPX Index
Backtest of Short Straddles on SPX IndexBacktest of Short Straddles on SPX Index
Backtest of Short Straddles on SPX Index
 
Pairs Trading In the Brazilian Stock Market
Pairs Trading In the Brazilian Stock MarketPairs Trading In the Brazilian Stock Market
Pairs Trading In the Brazilian Stock Market
 
How To Set Up Automated Trading
How To Set Up Automated TradingHow To Set Up Automated Trading
How To Set Up Automated Trading
 
How To Set Up Automated Trading
How To Set Up Automated TradingHow To Set Up Automated Trading
How To Set Up Automated Trading
 
Quantitative Data Analysis of Cryptocurrencies
Quantitative Data Analysis of CryptocurrenciesQuantitative Data Analysis of Cryptocurrencies
Quantitative Data Analysis of Cryptocurrencies
 
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...Introduction to Quantitative Trading - Investment Management Club of Yale Uni...
Introduction to Quantitative Trading - Investment Management Club of Yale Uni...
 
How to automate an options day trading strategy
How to automate an options day trading strategyHow to automate an options day trading strategy
How to automate an options day trading strategy
 
Predict daily stock prices with random forest classifier, technical indicator...
Predict daily stock prices with random forest classifier, technical indicator...Predict daily stock prices with random forest classifier, technical indicator...
Predict daily stock prices with random forest classifier, technical indicator...
 
How Pandemics Impact the Financial Markets - A Quantitative Analysis
How Pandemics Impact the Financial Markets - A Quantitative AnalysisHow Pandemics Impact the Financial Markets - A Quantitative Analysis
How Pandemics Impact the Financial Markets - A Quantitative Analysis
 
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...
Masterclass: Natural Language Processing in Trading with Terry Benzschawel & ...
 
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...
Webinar on Algorithmic Trading - Why make the move? with Vivek Krishnamoorthy...
 

Recently uploaded

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 

Recently uploaded (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 

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
  • 24. Performance analysis Daily portfolio balances Transaction Log Demo Input/performanceAnalysisChart.py
  • 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
  • 29.