SlideShare une entreprise Scribd logo
1  sur  31
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

How To Swing Trade Stocks For Consistent Profits
How To Swing Trade Stocks For Consistent ProfitsHow To Swing Trade Stocks For Consistent Profits
How To Swing Trade Stocks For Consistent ProfitsMorpheus Trading Group
 
The simple scalping strategy rules
The simple scalping strategy rules  The simple scalping strategy rules
The simple scalping strategy rules Nasir Tareen
 
A Guided Tour of Machine Learning for Traders by Tucker Balch at QuantCon 2016
A Guided Tour of Machine Learning for Traders by Tucker Balch at QuantCon 2016A Guided Tour of Machine Learning for Traders by Tucker Balch at QuantCon 2016
A Guided Tour of Machine Learning for Traders by Tucker Balch at QuantCon 2016Quantopian
 
How to Become a Professional Trader
How to Become a Professional TraderHow to Become a Professional Trader
How to Become a Professional Trader My Trading Skills
 
The QuantCon Keynote: "Counter Trend Trading – Threat or Complement to Trend ...
The QuantCon Keynote: "Counter Trend Trading – Threat or Complement to Trend ...The QuantCon Keynote: "Counter Trend Trading – Threat or Complement to Trend ...
The QuantCon Keynote: "Counter Trend Trading – Threat or Complement to Trend ...Quantopian
 
"Deep Reinforcement Learning for Optimal Order Placement in a Limit Order Boo...
"Deep Reinforcement Learning for Optimal Order Placement in a Limit Order Boo..."Deep Reinforcement Learning for Optimal Order Placement in a Limit Order Boo...
"Deep Reinforcement Learning for Optimal Order Placement in a Limit Order Boo...Quantopian
 
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 tradingQuantInsti
 
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
 
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 2016Quantopian
 
EXANTE Algorithmic Trading: Practical Aspects
EXANTE Algorithmic Trading: Practical AspectsEXANTE Algorithmic Trading: Practical Aspects
EXANTE Algorithmic Trading: Practical AspectsEXANTE
 
"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 ExtractAlphaQuantopian
 
High Probability Trading Setups
High Probability Trading SetupsHigh Probability Trading Setups
High Probability Trading Setupsbtrader
 
Algorithmic Trading
Algorithmic TradingAlgorithmic Trading
Algorithmic TradingAlice Chan
 
Simple scalping secret strategy
Simple scalping secret strategySimple scalping secret strategy
Simple scalping secret strategyHeri Valiant
 
Combining the Best Stock Selection Factors by Patrick O'Shaughnessy at QuantC...
Combining the Best Stock Selection Factors by Patrick O'Shaughnessy at QuantC...Combining the Best Stock Selection Factors by Patrick O'Shaughnessy at QuantC...
Combining the Best Stock Selection Factors by Patrick O'Shaughnessy at QuantC...Quantopian
 
Paradigms of trading strategies formulation
Paradigms of trading strategies formulationParadigms of trading strategies formulation
Paradigms of trading strategies formulationQuantInsti
 
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
 
"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
 
"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
 

Tendances (20)

How To Swing Trade Stocks For Consistent Profits
How To Swing Trade Stocks For Consistent ProfitsHow To Swing Trade Stocks For Consistent Profits
How To Swing Trade Stocks For Consistent Profits
 
The simple scalping strategy rules
The simple scalping strategy rules  The simple scalping strategy rules
The simple scalping strategy rules
 
A Guided Tour of Machine Learning for Traders by Tucker Balch at QuantCon 2016
A Guided Tour of Machine Learning for Traders by Tucker Balch at QuantCon 2016A Guided Tour of Machine Learning for Traders by Tucker Balch at QuantCon 2016
A Guided Tour of Machine Learning for Traders by Tucker Balch at QuantCon 2016
 
How to Become a Professional Trader
How to Become a Professional TraderHow to Become a Professional Trader
How to Become a Professional Trader
 
The QuantCon Keynote: "Counter Trend Trading – Threat or Complement to Trend ...
The QuantCon Keynote: "Counter Trend Trading – Threat or Complement to Trend ...The QuantCon Keynote: "Counter Trend Trading – Threat or Complement to Trend ...
The QuantCon Keynote: "Counter Trend Trading – Threat or Complement to Trend ...
 
"Deep Reinforcement Learning for Optimal Order Placement in a Limit Order Boo...
"Deep Reinforcement Learning for Optimal Order Placement in a Limit Order Boo..."Deep Reinforcement Learning for Optimal Order Placement in a Limit Order Boo...
"Deep Reinforcement Learning for Optimal Order Placement in a Limit Order Boo...
 
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...
 
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
 
EXANTE Algorithmic Trading: Practical Aspects
EXANTE Algorithmic Trading: Practical AspectsEXANTE Algorithmic Trading: Practical Aspects
EXANTE Algorithmic Trading: Practical Aspects
 
"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
 
High Probability Trading Setups
High Probability Trading SetupsHigh Probability Trading Setups
High Probability Trading Setups
 
Algorithmic Trading
Algorithmic TradingAlgorithmic Trading
Algorithmic Trading
 
Simple scalping secret strategy
Simple scalping secret strategySimple scalping secret strategy
Simple scalping secret strategy
 
Combining the Best Stock Selection Factors by Patrick O'Shaughnessy at QuantC...
Combining the Best Stock Selection Factors by Patrick O'Shaughnessy at QuantC...Combining the Best Stock Selection Factors by Patrick O'Shaughnessy at QuantC...
Combining the Best Stock Selection Factors by Patrick O'Shaughnessy at QuantC...
 
Paradigms of trading strategies formulation
Paradigms of trading strategies formulationParadigms of trading strategies formulation
Paradigms of trading strategies formulation
 
Algorithmic trading
Algorithmic tradingAlgorithmic trading
Algorithmic trading
 
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...
 
"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...
 
"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...
 

Similaire à 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.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
 

Similaire à 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
 

Plus de 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
 

Plus de 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...
 

Dernier

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 

Dernier (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.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.