-
Notifications
You must be signed in to change notification settings - Fork 0
/
buy_and_hold_backtest.py
70 lines (60 loc) · 2.07 KB
/
buy_and_hold_backtest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import datetime
from qstrader import settings
from qstrader.strategy.base import AbstractStrategy
from qstrader.event import SignalEvent, EventType
from qstrader.compat import queue
from qstrader.trading_session import TradingSession
class BuyAndHoldStrategy(AbstractStrategy):
"""
A testing strategy that simply purchases (longs) an asset
upon first receipt of the relevant bar event and
then holds until the completion of a backtest.
"""
def __init__(
self, ticker, events_queue,
base_quantity=100
):
self.ticker = ticker
self.events_queue = events_queue
self.base_quantity = base_quantity
self.bars = 0
self.invested = False
def calculate_signals(self, event):
if (
event.type in [EventType.BAR, EventType.TICK] and
event.ticker == self.ticker
):
if not self.invested and self.bars == 0:
signal = SignalEvent(
self.ticker, "BOT",
suggested_quantity=self.base_quantity
)
self.events_queue.put(signal)
self.invested = True
self.bars += 1
def run(config, testing, tickers, filename):
# Backtest information
title = ['Buy and Hold Example on %s' % tickers[0]]
initial_equity = 10000.0
start_date = datetime.datetime(2000, 1, 1)
end_date = datetime.datetime(2014, 1, 1)
# Use the Buy and Hold Strategy
events_queue = queue.Queue()
strategy = BuyAndHoldStrategy(tickers[0], events_queue)
# Set up the backtest
backtest = TradingSession(
config, strategy, tickers,
initial_equity, start_date, end_date,
events_queue, title=title
)
results = backtest.start_trading(testing=testing, filename=filename)
return results
if __name__ == "__main__":
# Configuration data
testing = False
config = settings.from_file(
settings.DEFAULT_CONFIG_FILENAME, testing
)
tickers = ["AAPL"]
filename = 'Buy and Hold Backtest'
run(config, testing, tickers, filename)