Introducing Alpaca Backtrader Integration
Alpaca and our users grow with open source
One of the great things in the algo trading is that you don’t have to build everything from scratch. The open source community has evolved in software space exponentially, and the potential of its power is unlimited. At Alpaca, I’m talking with great people and getting insights what’s available everyday, but today, I wanted to share our initial version of Alpaca Backtrader integration library.
What is Backtrader anyway?
Backtrader is an open source algo trading framework in pure Python developed by Daniel Rodriguez as his own project and has been active for last few years. It follows the perfect example of open source project, with full transparency, github-centric project management, well-described online manual and growing community.
The framework is time-series driven style, and as far as you supply time-series data, it works pretty well with any kind of asset classes. Also there are a number of useful built-in indicator calculators as well as very flexible strategy building blocks such as position sizers and performance analysis. It also comes with graphical plotting functionality using matplotlib with full customization.
The best part of it is almost all functionalities are extensible, and you can feed different source of data, your own style of position sizing, custom indicators etc. Last but not least, the framework works seamlessly between backtesting and live trading. What it means is that you can easily test your trading strategy with the historical data and go live with a few changes to apply the strategy.
Alpaca Backtrader API
As the framework is fully extensible, Alpaca’s approach to this great framework is to stay away from the core source code, but maintain our own integration piece on top of it. You can find the integration library at PyPI as alpaca-backtrader-api today, and we continue to develop and release our effort over the time.
This model has a great advantage that Alpaca’s integration can frequently updated without worrying about breaking the Backtrader core system. As other open source libraries we maintain, all kind of feedback and feature requests are welcomed, and you can even send pull requests if you find is easier and beneficial to others too.
Tutorial
Sounds great, now what? Yes, I don’t just talk about great things, but I do write some code. While I’m still new to Backtrader, there is the beginner’s guide to Alpaca Backtrader integration.
This example we go through today is a very simple moving average crossover strategy. We work on a single stock AAPL at minute level. When the short moving average (10) crosses over the long moving average (30), we buy it, and when the long one crosses over the short, we shell it.
First thing, install. You can install alpaca-backtrader-api
using pip
today.
$ pip install alpaca-backtrader-api
This comes with all dependencies including backtrader itself and Alpaca Python SDK (alpaca-trade-api). I usually use pipenv to avoid dependency conflicts with other projects in my local machine but it is optional.
Once it’s installed, put a file named main.py
and start from importing modules.
import backtrader as bt
import alpaca_backtrader_api
import pandas as pd
This imports Backtrader core, Alpaca integration and Pandas.
Our strategy looks as simple as this.
class SmaCross(bt.SignalStrategy):
def __init__(self):
sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30)
crossover = bt.ind.CrossOver(sma1, sma2)
self.signal_add(bt.SIGNAL_LONG, crossover)
What it says is we calculate two simple moving averages on the underlying price data, SMA10 and SMA30, and when crossover occurs, take a long position. Very intuitive and nothing is complicated.
Given the strategy in hand, let’s setup backtrader for backtesting.
cerebro = bt.Cerebro()
cerebro.addstrategy(SmaCross)cerebro.broker.setcash(100000)
cerebro.broker.setcommission(commission=0.0)
cerebro.addsizer(bt.sizers.PercentSizer, percents=20)
cerebro
is something you create as the backtrader instance. You add strategy to it and set some broker configuration. Yes, if you are backtesting for Alpaca, the commission should be 0.0! The lines above also include the position sizing logic which is to say we buy AAPL as much as 20% of the total value.
Now, for backtesting data, we get the data from Alpaca API. To do so, create an instance of AlpacaStore
class.
DataFactory = store.getdata
data0 = DataFactory(
dataname='AAPL',
timeframe=bt.TimeFrame.TFrame("Minutes"),
fromdate=pd.Timestamp('2018-11-15'),
todate=pd.Timestamp('2018-11-17'),
historical=True)
cerebro.adddata(data0)
AlpacaStore
can then derive the data feeder as DataFactory
and here you give the symbol name and from-to date. Note you give this historical=True
flag to tell the underlying layer we are doing backtesting.
This completes the setup, and now you can kick of backtesting!
cerebro.run()
print(‘Final Portfolio Value: %.2f’ % cerebro.broker.getvalue())
cerebro.plot()
Yes, it’s that simple! Finally, do not forget to have your API key from Alpaca (if not yet, sign up from here). Set environment variables as follows.
$ export APCA_API_KEY_ID=xxx
$ export APCA_API_SECRET_KEY=yyy
If you are using paper trading API key, you should also set the base URL.
$ export APCA_API_BASE_URL=https://paper-api.alpaca.markets
Then run your script from the terminal by
$ python main.py
You will see the final value of your asset in the terminal. In order to make the plot, you may need to install matplotlib
addionally.
$ pip install matplotlib
Then this final plot()
call will open a new window like below.
You can visually confirm when it enters and exists the position with the time-series data.
Live Trading
Ok, let’s say you are happy with this result. What you want to do now is to run this in live. All you need to do is to change the “historical=True” to False and set broker to Alpaca.
broker = store.getbroker()
cerebro.setbroker(broker)data0 = DataFactory(
dataname='AAPL',
timeframe=bt.TimeFrame.TFrame("Minutes"),
)
cerebro.adddata(data0)cerebro.run(exactbars=1)
Then run the same command.
$ python main.py
The full source code is hosted in Gist.
Conclusion
I introduced Backtrader, Alpaca’s integration and the basic tutorial of how to use the integration. Like I said at the beginning, the great thing about this is you don’t have to build everything from scratch, but rather you just focus on your own trading idea. Backtrader has everything you need to build things like indicator based algorithms, so you can start off right away.
And again, we always welcome any feedback from your experience. Try it today, and give us more feedback! You can ask questions and give feedback in our Slack community as well.
Technology and services are offered by AlpacaDB, Inc. Brokerage services are provided by Alpaca Securities LLC (alpaca.markets), member FINRA/SIPC. Alpaca Securities LLC is a wholly-owned subsidiary of AlpacaDB, Inc.
You can find us @AlpacaHQ, if you use twitter.