-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbacktest.py
More file actions
94 lines (69 loc) · 2.74 KB
/
backtest.py
File metadata and controls
94 lines (69 loc) · 2.74 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from data_handler import DataHandler
from smabc import SimpleMovingAverageBinaryClassifier
class Trader:
def wanted_tickers(self):
""" Gets a list of tickers whose data should be passed to get_trades
Returns:
list<string>: List of tickers whose data should be passed to get_trades
"""
pass
def get_holdings(self, data, current_holdings):
""" Calculates which stocks to buy / sell
Args:
data ([type]): [description]
Returns:
[type]: [description]
"""
return {}
class BackTest:
def __init__(self, name, trader, initial_balance=100000):
self.data_handler = DataHandler(name)
self.data = pd.read_hdf(self.data_handler.filled_file)
self.trader = trader
self.balance = 10000
self.holdings = {}
def test(self):
self.data["value"] = np.zeros(len(self.data))
for i, row in self.data.iterrows():
wanted_tickers = self.trader.wanted_tickers()
columns = []
for ticker in wanted_tickers:
columns.extend([ticker + "_open", ticker + "_high", ticker + "_low", ticker + "_close", ticker + "_volume"])
wanted_df = self.data[columns][:i]
new_holdings = self.trader.get_holdings(wanted_df, self.holdings)
for key in self.holdings:
self.order(key, "sell", self.holdings[key], i)
self.data["value"][i] = self.balance
print(str(i) + str(round(self.balance, 2)), end="\r", flush=True)
for key in new_holdings:
share_price = self.data[ticker + "_open"][i]
amount = int(new_holdings[key] * self.balance / share_price)
self.order(key, "buy", amount, i)
def order(self, ticker, side, amount, index):
share_price = self.data[ticker + "_open"][index]
total_price = share_price * amount
if ticker not in self.holdings:
self.holdings[ticker] = 0
if side.lower() == "buy":
self.balance -= total_price
self.holdings[ticker] += amount
elif side.lower() == "sell":
self.balance += total_price
self.holdings[ticker] -= amount
class AAPLTrader(Trader):
def wanted_tickers(self):
return ["TSLA"]
def get_holdings(self, data, current_holdings):
return {"TSLA": 1}
if __name__ == "__main__":
name = "stocks_only"
# trader = SimpleMovingAverageBinaryClassifier(name)
trader = AAPLTrader()
test = BackTest(name, trader)
test.test()
test.data["value"].plot()
plt.show()