-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtsmom.py
More file actions
157 lines (93 loc) · 4.86 KB
/
Copy pathtsmom.py
File metadata and controls
157 lines (93 loc) · 4.86 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
from turing_quant_models import Turing_quant_models
class tsmom (Turing_quant_models):
def __init__(self, df):
Turing_quant_models.__init__(self, df)
def ml_signal(self, model, prices, lags=[3, 6, 12]):
"""
Return predict and signal construction (long or short)
"""
signal = []
for i in prices.columns:
# converting Series to DataFrame to do the feature engineering
stock = pd.DataFrame(prices[i].copy())
# renaming target variable
stock.columns = ["y"]
X = []
y = []
# adding lagged columns
for i in lags:
stock["lag_{}".format(i)] = stock.y.pct_change(i).fillna(0)
y = stock[-24:-2].dropna().y # target
X = stock[-24:-2].dropna().drop(['y'], axis=1) # features
try:
model.fit(X, y)
X_pred = stock.iloc[-1,1:]
y_pred = model.predict([X_pred])
sign = np.where(y_pred/stock.y.iloc[-1] - 1 > 0, 1, -1)
signal.append(sign[0])
except:
signal.append(0)
print(signal)
return signal
def signal(self, df, date, passive, method="momentum"):
"""
Função que constrói o sinal para diversos metodos, sendo o tradicional: momentum
"""
num_assets = len(df.iloc[-1])
signal = []
if passive:
signal = np.ones(num_assets)
else:
if method == "momentum":
returns = df.pct_change(21 * 12).resample('BM').last().ffill()[:date]
signal = np.where(returns.iloc[-1] > 0, 1, -1)
elif method == "momentum_lagged":
returns_12 = df.pct_change(21 * 12).resample('BM').last().ffill()[:date]
returns_6 = df.pct_change(21 * 6).resample('BM').last().ffill()[:date]
returns_3 = df.pct_change(21 * 3).resample('BM').last().ffill()[:date]
momentum_mean = (returns_12.iloc[-1] + returns_6.iloc[-1] + returns_3.iloc[-1]) / 3
signal = np.where(momentum_mean > 0, 1, -1)
elif method == "linear_regression":
prices = df.resample('BM').last().ffill()[:date]
lr = LinearRegression()
signal = self.ml_signal(lr, prices)
elif method == "decision_tree":
prices = df.resample('BM').last().ffill()[:date]
dt = DecisionTreeRegressor()
signal = self.ml_signal(dt, prices)
elif method == "random_forest":
prices = df.resample('BM').last().ffill()[:date]
rf = RandomForestRegressor()
signal = self.ml_signal(rf, prices)
return signal
def tsmom(self, df, returns_monthly, vol_monthly, date, method='momentum', risk=0.4, passive=False, momentum_window=12):
position = self.signal(df, date, passive, method)
weights = (risk / vol_monthly.iloc[date-1])
weights /= len(weights)
portfolio = position * weights
return (1+np.dot(portfolio, returns_monthly.iloc[date]))
def backtesting(self, start_date, years, vol, method, plot=True):
returns_model = [] # retorno do TSMOM
returns_baseline = [] # retorno passivo
start = start_date
years = years
end = 12*(int(start/12) + years)
for i in range(start, end):
self.printProgressBar (i-start, end-start-1)
returns_model.append(self.tsmom(self.close_df, self.returns_monthly,
self.vol_monthly, i))
returns_baseline.append(self.tsmom(self.close_df, self.returns_monthly,
self.vol_monthly, i, passive=True))
returns_model = pd.DataFrame(returns_model)
returns_baseline = pd.DataFrame(returns_baseline)
returns_model.index = self.returns_monthly.iloc[start:end].index
returns_baseline.index = self.returns_monthly.iloc[start:end].index
if plot:
self.plot_backtesting(
returns_model, returns_baseline, "TSMOM", "Long only", "Cumulative returns")