Stock/ETF/futures auto-trading code in R for use with Interactive Brokers' IBAPI
Why automate all your trading or portfolio rebalancing? Because I think it may improve your performance over the long run due to lower costs, obtaining better fills with IBALGO, increases strategy responsiveness to new data, and less human error. At the very least, automating your trading/rebalancing can set you free from having to manually enter trades.
This is the auto-trading code that I presented at R Finance 2018 in Chicago on June 2. It works with any backtesting platform because the code only requires 3 inputs - two, simple dataframes and one integer:
- the new, recommended allocation that's generated by your signal, backtest, AI, etc
- the current allocation including number of shares for each security (i.e. your current portfolio) that is downloaded via IBAPI
- your net liquidation value that's available to you to trade - also downloaded via IBAPI
You need 4 things to make autotrade.R work:
- Interactive Broker's API installed
- Python 3.6 installed
- Reticulate package
- ib_insync - a Python module to interface with IBAPI more easily
Once autotrade.R is working for you, then complete trading automation can occur by scheduling your scripts.
This is just a starter script to get you going. More code is needed to handle your unique trading situation - for example to handle expiring contracts or to add a new, different stock/ETF that was not part of the original dataframe of available symbols to trade or even just to avoid receiving an error if your current portfolio happens to hold no securities at all. However at its basic, autotrade.R will work as-is without additional code modifications.
I have tested a more developed version of the autotrade.R code below that traded the futures markets every hour on the hour; the result was that 100% of the trades occurred as planned and without any errors.
Based on Andrew Lo's paper, this is just a quick and dirty way to determine the variance of your empirical Sharpe Ratio without having to bootstrap.
DISCLAIMER: IF YOU USE ANY PART OF THIS AUTO-TRADING CODE, YOU ASSUME ALL RISK ASSOCIATED WITH ITS USE WHICH MAY INCLUDE BUT IS NOT LIMITED TO TOTAL LOSS OF PRICIPAL OR MORE.
PROVIDED AS-IS. FOR EDUCATIONAL USE ONLY. NOT FOR PRODUCTION USE. DO NOT USE FOR LIVE TRADING.