-
Notifications
You must be signed in to change notification settings - Fork 0
/
indicators.py
237 lines (179 loc) · 6.06 KB
/
indicators.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
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import os
import talib
import warnings
import pmdarima as pm
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from pmdarima import auto_arima
from functools import wraps
from os.path import isfile, join
from tqdm.notebook import tnrange
def plotSignal(func):
@wraps(func)
def wrapper(prices, signal, plot=False):
func(prices, signal)
if plot:
plt.rcParams['font.size'] = 16
fig = plt.figure(figsize=(16, 4))
ax = fig.add_axes([0, 0, 1, 1])
plt.plot(prices.index, signal['data'])
ax.set_title(func.__name__.upper())
ax.set_xlabel('Dates')
fig.autofmt_xdate(rotation=30)
ax.grid()
plt.show()
return wrapper
def useFile(func):
@wraps(func)
def wrapper(prices, signal):
# Set the filename to search for loading
directory = 'features/'
if signal['file'] is not None:
fn = signal['file']
else:
fn = directory + func.__name__ + '.npy'
# Load features if numpy file exists
if isfile(fn):
print(f'Loading {func.__name__} from {fn} ...')
signal['data'] = np.load(fn)
else:
func(prices, signal, func.__name__)
os.makedirs(directory, exist_ok=True)
np.save(fn, signal['data'])
return wrapper
def arima(price, window, desc):
pred = np.full(price.shape, np.nan)
for i in tnrange(window, price.shape[0], desc=desc):
train = price[i - window:i]
if np.any(np.isnan(train)):
continue
with warnings.catch_warnings():
# Uninvertible hessian
warnings.filterwarnings('ignore', 'Inverting')
# RuntimeWarning: invalid value encountered in true_divide
warnings.filterwarnings('ignore', 'invalid')
# RuntimeWarning: overflow encountered in exp
warnings.filterwarnings('ignore', 'overflow')
# ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals
# warnings.filterwarnings('ignore', 'Maximum')
# RuntimeWarning: divide by zero encountered in true_divide
warnings.filterwarnings('ignore', 'divide')
# Initialize model
model = auto_arima(train,
max_p=3,
max_q=3,
seasonal=False,
trace=False,
error_action='ignore',
suppress_warnings=True)
# Determine model parameters
model.fit(train)
order = model.get_params()['order']
# Fit and predict
model = pm.ARIMA(order=order)
model.fit(train)
pred[i] = model.predict(1)
return pred
@plotSignal
def sma(prices, signal):
"""
Simple Moving Average
"""
window = signal['params']['window']
signal['data'] = talib.SMA(prices['close'], window).to_numpy()[:, None]
@plotSignal
def wma(prices, signal):
"""
Weighted Moving Average
"""
window = signal['params']['window']
signal['data'] = talib.WMA(prices['close'], window).to_numpy()[:, None]
@plotSignal
def mom(prices, signal):
"""
Momentum
"""
window = signal['params']['window']
signal['data'] = talib.MOM(prices['close'], window).to_numpy()[:, None]
@plotSignal
def macd(prices, signal):
"""
Moving Average Convergence Divergence
"""
fast = signal['params']['fastperiod']
slow = signal['params']['slowperiod']
mavg = signal['params']['signalperiod']
macd, macdsignal, _ = talib.MACD(prices['close'], fast, slow, mavg)
signal['data'] = np.hstack(
[macd.to_numpy()[:, None],
macdsignal.to_numpy()[:, None]])
@plotSignal
def rsi(prices, signal):
"""
Relative Strength Index
"""
window = signal['params']['window']
signal['data'] = talib.RSI(prices['close'], window).to_numpy()[:, None]
@plotSignal
def stoch(prices, signal):
"""
Stochastics
"""
slowk, slowd = talib.STOCH(prices['high'], prices['low'], prices['close'])
signal['data'] = np.hstack(
[slowk.to_numpy()[:, None],
slowd.to_numpy()[:, None]])
@plotSignal
def willr(prices, signal):
"""
Williams R Oscillator
"""
window = signal['params']['window']
signal['data'] = talib.WILLR(prices['high'], prices['low'],
prices['close'], window).to_numpy()[:, None]
@plotSignal
def adosc(prices, signal):
"""
Accumulation / Distribution Oscillator
"""
signal['data'] = talib.ADOSC(prices['high'],
prices['low'],
prices['close'],
prices['volume'],
fastperiod=3,
slowperiod=10).to_numpy()[:, None]
@plotSignal
def ema(prices, signal):
"""
Exponential Moving Average
"""
window = signal['params']['window']
signal['data'] = talib.EMA(prices['close'], window).to_numpy()[:, None]
@plotSignal
@useFile
def arima_sma(prices, signal, name):
"""
ARIMA on Simple Moving Average
"""
sma_window = signal['params']['sma_window']
sma_close = talib.SMA(prices['close'], sma_window).to_numpy()[:, None]
signal['data'] = arima(sma_close, signal['params']['arima_window'], name)
@plotSignal
@useFile
def arima_wma(prices, signal, name):
"""
ARIMA on Weighted Moving Average
"""
wma_window = signal['params']['wma_window']
wma_close = talib.WMA(prices['close'], wma_window).to_numpy()[:, None]
signal['data'] = arima(wma_close, signal['params']['arima_window'], name)
@plotSignal
@useFile
def arima_ema(prices, signal, name):
"""
ARIMA on Exponential Moving Average
"""
ema_window = signal['params']['ema_window']
ema_close = talib.EMA(prices['close'], ema_window).to_numpy()[:, None]
signal['data'] = arima(ema_close, signal['params']['arima_window'], name)