-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathstrategy4_context.lookback=1_logistics-regresion.py
66 lines (54 loc) · 2.51 KB
/
strategy4_context.lookback=1_logistics-regresion.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
#from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LogisticRegression
from sklearn.qda import QDA
from sklearn import tree
#from sklearn.neural_network import MLPClassifier
import numpy as np
import pandas as pd
def initialize(context):
context.assets = sid(8554) # Trade SPY
context.model = LogisticRegression()
context.lookback = 4 # Look back
context.history_range = 400
# Generate a new model every week
schedule_function(create_model, date_rules.week_start(),time_rules.market_open(minutes=1))
# Trade at the start of every day
schedule_function(trade, date_rules.week_end(), time_rules.market_open(minutes=1))
def create_model(context, data):
# Get the relevant daily prices
recent_prices = data.history(context.assets, 'price',context.history_range, '1d')
context.ma_50 =recent_prices.values[-50:].mean()
context.ma_200 = recent_prices.values[-200:].mean()
#print context.ma_50
#print context.ma_200
time_lags = pd.DataFrame(index=recent_prices.index)
time_lags['price']=recent_prices.values
time_lags['returns']=(time_lags['price'].pct_change()).fillna(0.0001)
time_lags['lag1'] = (time_lags['returns'].shift(1)).fillna(0.0001)
time_lags['lag2'] = (time_lags['returns'].shift(2)).fillna(0.0001)
time_lags['direction'] = np.sign(time_lags['returns'])
X = time_lags[['lag1','lag2']] # Independent, or input variables
Y = time_lags['direction'] # Dependent, or output variable
# print X
#print X
context.model.fit(X, Y) # Generate our model
#print context.model.predict(X)
def trade(context, data):
if context.model: # Check if our model is generated
# Get recent prices
new_recent_prices = data.history(context.assets,'price', context.lookback, '1d')
time_lags = pd.DataFrame(index=new_recent_prices.index)
time_lags['price']=new_recent_prices.values
time_lags['returns']=(time_lags['price'].pct_change()).fillna(0.0001)
time_lags['lag1'] = (time_lags['returns'].shift(1)).fillna(0.0001)
X = time_lags[['returns','lag1']]
prediction = context.model.predict(X)
print prediction
if prediction > 0 and context.ma_50 > context.ma_200:
order_target_percent(context.assets, 1.0)
elif prediction < 0 and context.ma_50 < context.ma_200:
order_target_percent(context.assets, -1.0)
else:
pass
def handle_data(context, data):
pass