Created
January 25, 2023 22:07
-
-
Save andrew-rosca/7bdd6c422402e0da7c314eba0e68c172 to your computer and use it in GitHub Desktop.
Simple example of Backtrader strategy with inline data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import backtrader as bt | |
import pandas as pd | |
from io import StringIO | |
class TestStrategy(bt.Strategy): | |
def next(self): | |
if self.position.size == 0: | |
self.buy(size=10) | |
else: | |
self.sell(size=10) | |
def notify_order(self, order): | |
if order.status == order.Completed: | |
print(f"{order.ordtypename()} completed at price {order.executed.price}") | |
if __name__ == '__main__': | |
#make sure you use tabs as separators, not spaces in this input string, or change the separator in `read_csv` below | |
data =""" | |
datetime open close | |
2022-01-01 10.1 10.2 | |
2022-01-02 15.1 15.2 | |
2022-01-03 20.1 20.2 | |
""" | |
prices = StringIO(data) | |
df = pd.read_csv(prices, sep = '\t', parse_dates=True, index_col=0) | |
pricedata = bt.feeds.PandasData(dataname = df) | |
cerebro = bt.Cerebro() | |
cerebro.addstrategy(TestStrategy) | |
cerebro.adddata(pricedata) | |
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue()) | |
cerebro.run() | |
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue()) |
This is an example of how to output more detailed debug info:
def notify_order(self, order):
id = order.ref
created = bt.num2date(order.created.dt).strftime('%Y-%m-%d %H:%M')
status_name = order.Status[order.status]
ordtype_name = order.ordtypename()
exectype_name = order.ExecTypes[order.exectype]
order_header = f"#{id} {ordtype_name}: {status_name}: "
order_info = f"{order.size} @ {order.price}"
exec_info = f"{order.executed.size} @ {order.executed.price}"
if order.status == order.Completed:
print(f"{order_header}{exec_info}")
elif order.status in [order.Submitted, order.Accepted]:
print(f"{order_header}{order_info}")
else:
print(f"{order_header}")
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: