SlideShare a Scribd company logo
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 With Interactive Brokers Using Python With Dr. Hui Liu

More Related Content

What's hot

QuantConnect - Introduction to Pairs Trading
QuantConnect - Introduction to Pairs TradingQuantConnect - Introduction to Pairs Trading
QuantConnect - Introduction to Pairs Trading
QuantConnect
 
Order book dynamics in high frequency trading
Order book dynamics in high frequency tradingOrder book dynamics in high frequency trading
Order book dynamics in high frequency trading
QuantInsti
 
Beware of Low Frequency Data by Ernie Chan, Managing Member, QTS Capital Mana...
Beware of Low Frequency Data by Ernie Chan, Managing Member, QTS Capital Mana...Beware of Low Frequency Data by Ernie Chan, Managing Member, QTS Capital Mana...
Beware of Low Frequency Data by Ernie Chan, Managing Member, QTS Capital Mana...
Quantopian
 
Binary options strategies-how-make-money-in-binary-options-trading
Binary options strategies-how-make-money-in-binary-options-tradingBinary options strategies-how-make-money-in-binary-options-trading
Binary options strategies-how-make-money-in-binary-options-trading
Thomas Jan
 
Should You Build Your Own Backtester? by Michael Halls-Moore at QuantCon 2016
Should You Build Your Own Backtester? by Michael Halls-Moore at QuantCon 2016Should You Build Your Own Backtester? by Michael Halls-Moore at QuantCon 2016
Should You Build Your Own Backtester? by Michael Halls-Moore at QuantCon 2016
Quantopian
 
"Fundamental Forecasts: Methods and Timing" by Vinesh Jha, CEO of ExtractAlpha
"Fundamental Forecasts: Methods and Timing" by Vinesh Jha, CEO of ExtractAlpha"Fundamental Forecasts: Methods and Timing" by Vinesh Jha, CEO of ExtractAlpha
"Fundamental Forecasts: Methods and Timing" by Vinesh Jha, CEO of ExtractAlpha
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
 
Top 8 Forex Trading Strategies That Pro Traders Use
Top 8 Forex Trading Strategies That Pro Traders UseTop 8 Forex Trading Strategies That Pro Traders Use
Top 8 Forex Trading Strategies That Pro Traders Use
Syrous Pejman
 
"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 insti webinar on algorithmic trading for technocrats!
Quant insti webinar on algorithmic trading for technocrats!Quant insti webinar on algorithmic trading for technocrats!
Quant insti webinar on algorithmic trading for technocrats!
QuantInsti
 
"The 6 Stages of a Quant Equity Workflow" by Dr. Jessica Stauth, Vice Preside...
"The 6 Stages of a Quant Equity Workflow" by Dr. Jessica Stauth, Vice Preside..."The 6 Stages of a Quant Equity Workflow" by Dr. Jessica Stauth, Vice Preside...
"The 6 Stages of a Quant Equity Workflow" by Dr. Jessica Stauth, Vice Preside...
Quantopian
 
Price Action Trading - An Introduction
Price Action Trading - An IntroductionPrice Action Trading - An Introduction
Price Action Trading - An Introduction
QuantInsti
 
Scalping in Day Trading
Scalping in Day TradingScalping in Day Trading
Scalping in Day Trading
InvestingTips
 
Tips to Improve your Trading Mindset
Tips to Improve your Trading MindsetTips to Improve your Trading Mindset
Tips to Improve your Trading Mindset
 My Trading Skills
 
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
 
Simple scalping secret strategy
Simple scalping secret strategySimple scalping secret strategy
Simple scalping secret strategy
Heri Valiant
 
Trade what you see not what you think
Trade what you see not what you thinkTrade what you see not what you think
Trade what you see not what you think
Ninja Tan
 
"From Trading Strategy to Becoming an Industry Professional – How to Break in...
"From Trading Strategy to Becoming an Industry Professional – How to Break in..."From Trading Strategy to Becoming an Industry Professional – How to Break in...
"From Trading Strategy to Becoming an Industry Professional – How to Break in...
Quantopian
 
How to build a trading system
How to build a trading systemHow to build a trading system
How to build a trading system
FXstreet.com
 
Intraday trading formulae, Strategies and rules
Intraday trading formulae, Strategies and rulesIntraday trading formulae, Strategies and rules
Intraday trading formulae, Strategies and rules
Bikramjit Singh
 

What's hot (20)

QuantConnect - Introduction to Pairs Trading
QuantConnect - Introduction to Pairs TradingQuantConnect - Introduction to Pairs Trading
QuantConnect - Introduction to Pairs Trading
 
Order book dynamics in high frequency trading
Order book dynamics in high frequency tradingOrder book dynamics in high frequency trading
Order book dynamics in high frequency trading
 
Beware of Low Frequency Data by Ernie Chan, Managing Member, QTS Capital Mana...
Beware of Low Frequency Data by Ernie Chan, Managing Member, QTS Capital Mana...Beware of Low Frequency Data by Ernie Chan, Managing Member, QTS Capital Mana...
Beware of Low Frequency Data by Ernie Chan, Managing Member, QTS Capital Mana...
 
Binary options strategies-how-make-money-in-binary-options-trading
Binary options strategies-how-make-money-in-binary-options-tradingBinary options strategies-how-make-money-in-binary-options-trading
Binary options strategies-how-make-money-in-binary-options-trading
 
Should You Build Your Own Backtester? by Michael Halls-Moore at QuantCon 2016
Should You Build Your Own Backtester? by Michael Halls-Moore at QuantCon 2016Should You Build Your Own Backtester? by Michael Halls-Moore at QuantCon 2016
Should You Build Your Own Backtester? by Michael Halls-Moore at QuantCon 2016
 
"Fundamental Forecasts: Methods and Timing" by Vinesh Jha, CEO of ExtractAlpha
"Fundamental Forecasts: Methods and Timing" by Vinesh Jha, CEO of ExtractAlpha"Fundamental Forecasts: Methods and Timing" by Vinesh Jha, CEO of ExtractAlpha
"Fundamental Forecasts: Methods and Timing" by Vinesh Jha, CEO of ExtractAlpha
 
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...
 
Top 8 Forex Trading Strategies That Pro Traders Use
Top 8 Forex Trading Strategies That Pro Traders UseTop 8 Forex Trading Strategies That Pro Traders Use
Top 8 Forex Trading Strategies That Pro Traders Use
 
"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 insti webinar on algorithmic trading for technocrats!
Quant insti webinar on algorithmic trading for technocrats!Quant insti webinar on algorithmic trading for technocrats!
Quant insti webinar on algorithmic trading for technocrats!
 
"The 6 Stages of a Quant Equity Workflow" by Dr. Jessica Stauth, Vice Preside...
"The 6 Stages of a Quant Equity Workflow" by Dr. Jessica Stauth, Vice Preside..."The 6 Stages of a Quant Equity Workflow" by Dr. Jessica Stauth, Vice Preside...
"The 6 Stages of a Quant Equity Workflow" by Dr. Jessica Stauth, Vice Preside...
 
Price Action Trading - An Introduction
Price Action Trading - An IntroductionPrice Action Trading - An Introduction
Price Action Trading - An Introduction
 
Scalping in Day Trading
Scalping in Day TradingScalping in Day Trading
Scalping in Day Trading
 
Tips to Improve your Trading Mindset
Tips to Improve your Trading MindsetTips to Improve your Trading Mindset
Tips to Improve your Trading Mindset
 
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)
 
Simple scalping secret strategy
Simple scalping secret strategySimple scalping secret strategy
Simple scalping secret strategy
 
Trade what you see not what you think
Trade what you see not what you thinkTrade what you see not what you think
Trade what you see not what you think
 
"From Trading Strategy to Becoming an Industry Professional – How to Break in...
"From Trading Strategy to Becoming an Industry Professional – How to Break in..."From Trading Strategy to Becoming an Industry Professional – How to Break in...
"From Trading Strategy to Becoming an Industry Professional – How to Break in...
 
How to build a trading system
How to build a trading systemHow to build a trading system
How to build a trading system
 
Intraday trading formulae, Strategies and rules
Intraday trading formulae, Strategies and rulesIntraday trading formulae, Strategies and rules
Intraday trading formulae, Strategies and rules
 

Similar to Backtesting And Live Trading With Interactive Brokers Using Python With Dr. Hui Liu

Cis 115 Education Redefined-snaptutorial.com
Cis 115 Education Redefined-snaptutorial.comCis 115 Education Redefined-snaptutorial.com
Cis 115 Education Redefined-snaptutorial.com
robertledwes38
 
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 Benchmarking
Amit Chaudhary
 
SplunkSummit 2015 - Security Ninjitsu
SplunkSummit 2015 - Security NinjitsuSplunkSummit 2015 - Security Ninjitsu
SplunkSummit 2015 - Security Ninjitsu
Splunk
 
Baltimore MuleSoft Meetup #8
Baltimore MuleSoft Meetup #8Baltimore MuleSoft Meetup #8
Baltimore MuleSoft Meetup #8
ManjuKumara 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 Cloud
Yun Zhi Lin
 
Introduction to trader bots with Python
Introduction to trader bots with PythonIntroduction to trader bots with Python
Introduction to trader bots with Python
roskakori
 
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 Luminaire
Databricks
 
WSO2 Complex Event Processor
WSO2 Complex Event ProcessorWSO2 Complex Event Processor
WSO2 Complex Event Processor
Sriskandarajah Suhothayan
 
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-final
Samuel Sharaf
 
Welcome Webinar Slides
Welcome Webinar SlidesWelcome Webinar Slides
Welcome Webinar Slides
Sumo Logic
 
Supporting Enterprise System Rollouts with Splunk
Supporting Enterprise System Rollouts with SplunkSupporting Enterprise System Rollouts with Splunk
Supporting Enterprise System Rollouts with Splunk
Erin 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 2015
Samuel De Rycke
 

Similar to Backtesting And Live Trading With Interactive Brokers Using Python With Dr. Hui Liu (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
 
Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
 
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
 

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 Trading
QuantInsti
 
Introduction to Quantitative Factor Investing
Introduction to Quantitative Factor InvestingIntroduction to Quantitative Factor Investing
Introduction to Quantitative Factor Investing
QuantInsti
 
Machine Learning for Options Trading
Machine Learning for Options TradingMachine Learning for Options Trading
Machine Learning for Options Trading
QuantInsti
 
Portfolio Assets Allocation with Machine Learning
Portfolio Assets Allocation with Machine LearningPortfolio Assets Allocation with Machine Learning
Portfolio Assets Allocation with Machine Learning
QuantInsti
 
Introduction to Systematic Options Trading
Introduction to Systematic Options TradingIntroduction to Systematic Options Trading
Introduction to Systematic Options Trading
QuantInsti
 
Competitive Edges in Algorithmic Trading
Competitive Edges in Algorithmic TradingCompetitive Edges in Algorithmic Trading
Competitive Edges in Algorithmic Trading
QuantInsti
 
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
QuantInsti
 
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
QuantInsti
 
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
QuantInsti
 
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
QuantInsti
 
How To Set Up Automated Trading
How To Set Up Automated TradingHow To Set Up Automated Trading
How To Set Up Automated Trading
QuantInsti
 
How To Set Up Automated Trading
How To Set Up Automated TradingHow To Set Up Automated Trading
How To Set Up Automated Trading
QuantInsti
 
Quantitative Data Analysis of Cryptocurrencies
Quantitative Data Analysis of CryptocurrenciesQuantitative Data Analysis of Cryptocurrencies
Quantitative Data Analysis of Cryptocurrencies
QuantInsti
 
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 strategy
QuantInsti
 
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 Analysis
QuantInsti
 
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
 
Algorithmic Trading in FX Market By Dr. Alexis Stenfors
Algorithmic Trading in FX Market By Dr. Alexis StenforsAlgorithmic Trading in FX Market By Dr. Alexis Stenfors
Algorithmic Trading in FX Market By Dr. Alexis Stenfors
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
 
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...
 
Algorithmic Trading in FX Market By Dr. Alexis Stenfors
Algorithmic Trading in FX Market By Dr. Alexis StenforsAlgorithmic Trading in FX Market By Dr. Alexis Stenfors
Algorithmic Trading in FX Market By Dr. Alexis Stenfors
 

Recently uploaded

1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 

Recently uploaded (20)

1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 

Backtesting And Live Trading With Interactive Brokers Using Python With Dr. Hui Liu

  • 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.