Skip to content

Instantly share code, notes, and snippets.

@andrew-rosca
Created January 25, 2023 22:07
Show Gist options
  • Save andrew-rosca/7bdd6c422402e0da7c314eba0e68c172 to your computer and use it in GitHub Desktop.
Save andrew-rosca/7bdd6c422402e0da7c314eba0e68c172 to your computer and use it in GitHub Desktop.
Simple example of Backtrader strategy with inline data
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())
@andrew-rosca
Copy link
Author

andrew-rosca commented Jan 25, 2023

Output:

Starting Portfolio Value: 10000.00
Buy completed at price 15.1
Sell completed at price 20.1
Final Portfolio Value: 10050.00

@andrew-rosca
Copy link
Author

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