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 Strategies with Interactive Brokers using Python

Contenu connexe

Tendances

How to build a trading system
How to build a trading systemHow to build a trading system
How to build a trading systemFXstreet.com
 
"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
 
DIY Quant Strategies on Quantopian
DIY Quant Strategies on QuantopianDIY Quant Strategies on Quantopian
DIY Quant Strategies on QuantopianJess Stauth
 
"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
 
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
 
QuantConnect - Introduction to Pairs Trading
QuantConnect - Introduction to Pairs TradingQuantConnect - Introduction to Pairs Trading
QuantConnect - Introduction to Pairs TradingQuantConnect
 
"A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ...
"A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ..."A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ...
"A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ...Quantopian
 
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
 
Pairs Trading
Pairs TradingPairs Trading
Pairs Tradingnattyvirk
 
"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
 
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
 
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
 
Magic Breakout Forex Trading Strategy PDF eBook
Magic Breakout Forex Trading Strategy PDF eBookMagic Breakout Forex Trading Strategy PDF eBook
Magic Breakout Forex Trading Strategy PDF eBookeforexcourse web
 
Scalping in Day Trading
Scalping in Day TradingScalping in Day Trading
Scalping in Day TradingInvestingTips
 
"How to Run a Quantitative Trading Business in China with Python" by Xiaoyou ...
"How to Run a Quantitative Trading Business in China with Python" by Xiaoyou ..."How to Run a Quantitative Trading Business in China with Python" by Xiaoyou ...
"How to Run a Quantitative Trading Business in China with Python" by Xiaoyou ...Quantopian
 

Tendances (20)

How to build a trading system
How to build a trading systemHow to build a trading system
How to build a trading system
 
"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...
 
DIY Quant Strategies on Quantopian
DIY Quant Strategies on QuantopianDIY Quant Strategies on Quantopian
DIY Quant Strategies on Quantopian
 
"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...
 
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...
 
QuantConnect - Introduction to Pairs Trading
QuantConnect - Introduction to Pairs TradingQuantConnect - Introduction to Pairs Trading
QuantConnect - Introduction to Pairs Trading
 
"A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ...
"A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ..."A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ...
"A Framework-Based Approach to Building Quantitative Trading Systems" by Dr. ...
 
Statistical arbitrage
Statistical arbitrageStatistical arbitrage
Statistical arbitrage
 
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
 
Pairs Trading
Pairs TradingPairs Trading
Pairs Trading
 
QuantConnect - Options Backtesting
QuantConnect - Options BacktestingQuantConnect - Options Backtesting
QuantConnect - Options Backtesting
 
"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...
 
How to Become a Professional Trader
How to Become a Professional TraderHow to Become a Professional Trader
How to Become a Professional Trader
 
Trading Strategies
Trading StrategiesTrading Strategies
Trading Strategies
 
Algorithmic Trading
Algorithmic TradingAlgorithmic Trading
Algorithmic Trading
 
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
 
Magic Breakout Forex Trading Strategy PDF eBook
Magic Breakout Forex Trading Strategy PDF eBookMagic Breakout Forex Trading Strategy PDF eBook
Magic Breakout Forex Trading Strategy PDF eBook
 
Scalping in Day Trading
Scalping in Day TradingScalping in Day Trading
Scalping in Day Trading
 
"How to Run a Quantitative Trading Business in China with Python" by Xiaoyou ...
"How to Run a Quantitative Trading Business in China with Python" by Xiaoyou ..."How to Run a Quantitative Trading Business in China with Python" by Xiaoyou ...
"How to Run a Quantitative Trading Business in China with Python" by Xiaoyou ...
 
Trading plan
Trading planTrading plan
Trading plan
 

Similaire à Backtesting and Live Trading Strategies with Interactive Brokers using Python

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

Similaire à Backtesting and Live Trading Strategies with Interactive Brokers using Python (20)

Write bulletproof trigger code
Write bulletproof trigger codeWrite bulletproof trigger code
Write bulletproof trigger code
 
Cis 115 Education Redefined-snaptutorial.com
Cis 115 Education Redefined-snaptutorial.comCis 115 Education Redefined-snaptutorial.com
Cis 115 Education Redefined-snaptutorial.com
 
Sales force certification-lab
Sales force certification-labSales force certification-lab
Sales force certification-lab
 
Apex code Benchmarking
Apex code BenchmarkingApex code Benchmarking
Apex code Benchmarking
 
SplunkSummit 2015 - Security Ninjitsu
SplunkSummit 2015 - Security NinjitsuSplunkSummit 2015 - Security Ninjitsu
SplunkSummit 2015 - Security Ninjitsu
 
Baltimore MuleSoft Meetup #8
Baltimore MuleSoft Meetup #8Baltimore MuleSoft Meetup #8
Baltimore MuleSoft Meetup #8
 
Sales force certification-lab
Sales force certification-labSales force certification-lab
Sales force certification-lab
 
Dropwizard with MongoDB and Google Cloud
Dropwizard with MongoDB and Google CloudDropwizard with MongoDB and Google Cloud
Dropwizard with MongoDB and Google Cloud
 
Introduction to trader bots with Python
Introduction to trader bots with PythonIntroduction to trader bots with Python
Introduction to trader bots with Python
 
Database training for developers
Database training for developersDatabase training for developers
Database training for developers
 
Trading: How to attain maximum advantage while trading?
Trading: How to attain maximum advantage while trading?Trading: How to attain maximum advantage while trading?
Trading: How to attain maximum advantage while trading?
 
Scaling AutoML-Driven Anomaly Detection With Luminaire
Scaling AutoML-Driven Anomaly Detection With LuminaireScaling AutoML-Driven Anomaly Detection With Luminaire
Scaling AutoML-Driven Anomaly Detection With Luminaire
 
WSO2 Complex Event Processor
WSO2 Complex Event ProcessorWSO2 Complex Event Processor
WSO2 Complex Event Processor
 
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

Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxleah joy valeriano
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 

Dernier (20)

Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 

Backtesting and Live Trading Strategies with Interactive Brokers using Python

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