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
95
96
97
98
99
100
101
|
from algo import Algo
from ema_algo import Ema_Algo
from api import fetch_chart_data
import datetime
import json
"""
Function that takes in data and returns a buy, sell, or hold singal per interval
"""
def backtest_algo(algo : Algo, timestamps, prices, init_offset=5, starting_money=10000):
# take a fraction of the OG data (or a set #)
assert len(timestamps) == len(prices)
assert init_offset < len(timestamps) # make sure enough data to start with
current_timestamps = timestamps[:init_offset]
current_prices = prices[:init_offset]
is_bought = 0.0 # not holding anything
current_liquid = 10000
shares_owned = 0
buy_data = []
sell_data = []
for i in range(init_offset, len(timestamps)):
# update prices array and run algo
current_timestamps.append(timestamps[i])
current_prices.append(prices[i])
current_signal = algo.detemine_signal(current_timestamps, current_prices)
cur_p = current_prices[-1]
cur_t = current_timestamps[-1]
if current_signal == 1.0: # signal is to buy
if is_bought == 0.0: # if we haven't bought, purchase
shares_owned = current_liquid / cur_p
current_liquid = 0
is_bought = 1.0
buy_data.append(i)
print("buy", shares_owned, current_liquid, datetime.datetime.fromtimestamp(timestamps[i]))
elif current_signal == 0.0: # signal sell all
if is_bought == 1.0: # if we have bought, sell!
current_liquid = shares_owned * cur_p
shares_owned = 0
is_bought = 0.0
sell_data.append(i)
print('sell', shares_owned, current_liquid, datetime.datetime.fromtimestamp(timestamps[i]))
# calculate total assets
assets = prices[-1] * shares_owned + current_liquid
percent_gain = 100 * (assets - starting_money) / starting_money
print(assets, percent_gain)
# create a json to store the reuslts
results = {
"timestamps" : timestamps,
"prices" : prices,
"buy_indices" : buy_data,
"sell_indices" : sell_data,
"percent_gain" : percent_gain,
"starting_assets" : starting_money,
"final_assets" : assets,
"algo_name" : algo.name,
"algo_graph_data" : algo.graph_data
}
return results
# store all algo name, buy, sell, price data, timestamps, into a json so it can be viewed as a trial
# caluclate some metrics (NOW: only how much money gained, how many trades, trades per day... etc)
pass
def test():
print("MAIN simulate.py")
ema_algo = Ema_Algo()
# get data
data = fetch_chart_data('SPY', '1y', '1d')
print(data.keys())
url_params = {
"ticker" : 'SPY',
"period" : '1yr',
"interval" : '1d',
}
results = backtest_algo(ema_algo, data['timestamps'], data['prices'], 13)
# write the data into a json to be viewed in a chart
trial_data = {
"chart_data" : data,
"url_params" : url_params,
"backtest_results" : results
}
fd = open('bt-recent.json', 'w')
fd.write(json.dumps(trial_data))
fd.close()
test()
|