-
Notifications
You must be signed in to change notification settings - Fork 0
/
simulation.py
64 lines (51 loc) · 2.09 KB
/
simulation.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
import sklearn
from sklearn.model_selection import train_test_split
import pickle
from os import path
from sys import argv
from time import sleep
from build_model import save_best_model
from data.load import load_processed
def load_model(symbol: str, update=False) -> sklearn.tree.DecisionTreeClassifier:
model_path = path.join('classifiers', f'{symbol}.pickle')
if update or not path.exists(model_path):
save_best_model(symbol)
return pickle.load(open(model_path, 'rb'))
def simulate_profits_for(df, clf, X_test, position_percent=10):
cash = 1000
stock = 0
predictions = clf.predict(X_test)
for curr_price, prediction in zip(X_test['close'], predictions):
if prediction == 1: # We should buy
investment = cash / position_percent
cash -= investment
stock += investment / curr_price
print(
f"BUYING {investment / curr_price} for {investment}. Cash: {cash} | Stock: {stock}")
else: # We should sell
withdrawal = stock / position_percent
stock -= withdrawal
cash += withdrawal * curr_price
print(
f"SELLING {withdrawal * curr_price} for {withdrawal}. Cash: {cash} | Stock: {stock}")
sleep(0.1)
print('Number of trades:', len(predictions))
print(cash, stock, 'portfolio value:', cash + stock*curr_price)
return cash + stock*curr_price
def find_best_position_percent(df, clf, X_test):
optimal_percent = 1
largest_gains = float('-inf')
for percent in range(1, 101):
profit = simulate_profits_for(df, clf, X_test, percent)
print(f'Profit when trading at {percent}%: {profit}')
if profit > largest_gains:
largest_gains = profit
optimal_percent = percent
return optimal_percent, largest_gains
if __name__ == '__main__':
symbol = argv[1]
df = load_processed(symbol)
clf = load_model(symbol, update=True)
X_test = df[int(len(df)*0.75):].drop('PREDICTION', axis=1)
resulting_portfolio = simulate_profits_for(df, clf, X_test)
print(resulting_portfolio)