-
Notifications
You must be signed in to change notification settings - Fork 1
/
searchModelGAKknnMAABBAABCAAB.R
365 lines (315 loc) · 11.5 KB
/
searchModelGAKknnMAABBAABCAAB.R
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# Title : Daily generalized aspects / planet Y activation count KNN regression model
# with GA feature selection that maximize Rsquared on train data to fit for
# daily price percent change estimation.
# Purpose : Based on ModelLD this model has some variations:
# 1) Planets MO, ME, VE, SU fast planets applying to all planets except ME, SU.
# 2) CV folds to 5 with 5 repeats for weak learners, folds to 5 with 10 repeats for ensamble.
# 3) Split to 80/20 proportion.
# 4) Validate fit using Actbin daily price change (buy / sell) instead of Effect
# 5) GA feature detection that fit to maximize Rsquared train data.
# 6) Fit 5 weak learners for diff percent change.
# 7) Ensamble weak learnets to fit for Actbin to predict categorical (buy / sell) signal.
# 8) Optimize weak learners for RMSE.
# 9) GA feature selection popSize = 50 and iter = 10.
# 10) GA KKNN K search in range 5-10.
# 11) Fit using multi train sample mean metric penalized by standard deviation.
# 12) GA search orb limit 2-3 degrees.
# 13) Z diff percent cut to 3.
# 14) Remove pxSelect from GA search.
library(boot)
library(caret)
library(psych)
library(gbm)
library(ModelMetrics)
library(zeallot)
source("./analysis.r")
source("./indicatorPlots.r")
modelId <- "ensamble-gakknn-MAABBAABCAAB"
zdiffPercentCut <- 3
maPriceFsPeriod <- 2
maPriceSlPeriod <- 3
trainDataStartDate <- as.Date("2010-01-01")
trainDataEndDate <- as.Date("2020-08-15")
testDataStartDate <- as.Date("2020-09-01")
gaPopSize <- 50
gaMaxIter <- 10
gaParamsNum <- 9
wlCVFolds <- 5
wlCVRepeats <- 5
enCVFolds <- 5
enCVRepeats <- 10
pxSelectAll <- c(
'MO',
'ME',
'VE',
'SU'
)
pySelectAll <- c(
#'ME',
'VE',
#'SU',
'MA',
#'CE',
#'VS',
'JU',
'SA',
#'NN',
#'CH',
'UR',
'NE',
'PL'
)
aspectsSelectAll <- c(
0,
30,
45,
60,
90,
103,
120,
135,
150,
180
)
idCols <- c('Date', 'Hour')
setModernMixAspectsSet1()
setPlanetsMOMEVESUMACEVSJUNNSAURCHNEPL()
hourlyPlanets <<- openHourlyPlanets('planets_12', clear = F)
dailyAspectsRows <- dailyHourlyAspectsTablePrepare(hourlyPlanets, idCols, 4)
control <- trainControl(
method = "repeatedcv",
number = wlCVFolds,
repeats = wlCVRepeats,
savePredictions = "all",
verboseIter = F,
allowParallel = T,
trim = F
)
searchModel <- function(symbol) {
cat("\nProcessing", symbol, "model search...\n")
securityData <- mainOpenSecurity(
symbol, maPriceFsPeriod, maPriceSlPeriod,
"%Y-%m-%d", trainDataStartDate, trainDataEndDate
)
# Filter the extreme outliers.
cat(paste("Original days observations rows:", nrow(securityData)), "\n")
securityData <- securityData[abs(zdiffPercent) <= zdiffPercentCut]
hist(securityData$diffPercent)
cat(paste("Post filter days observations rows:", nrow(securityData)), "\n\n")
prepareModelData <- function(params) {
c(pxSelect, pySelect, orbLimit, kMax) %<-% params
dailyAspects <- prepareDailyAspectsCountPlanetYActivationCount(
dailyAspectsRows, orbLimit, pxSelect, pySelect, aspectsSelectAll
)
if (is.null(dailyAspects)) {
return(NULL)
}
aspectView <- merge(
securityData[, c('Date', 'diffPercent', 'Actbin', 'Eff')],
dailyAspects, by = "Date"
)
trainIndex <- createDataPartition(aspectView$diffPercent, p = 0.80, list = FALSE)
aspectViewTrain <- aspectView[trainIndex,]
aspectViewValidate <- aspectView[-trainIndex,]
useFeatures <- names(dailyAspects)[-1]
selectCols <- c('diffPercent', useFeatures)
return(
list(
train = aspectViewTrain[, ..selectCols],
validate = aspectViewValidate[, ..selectCols]
)
)
}
modelTrain <- function(params) {
c(pxSelect, pySelect, orbLimit, kMax) %<-% params
cat("Using PX:", pxSelect, "- PY:", pySelect, "- AORB: ", orbLimit, "- kMax: ", kMax, "\n")
modelData <- prepareModelData(params)
if (is.null(modelData)) {
cat("Skip solution, invalid GA solution params\n\n")
return(NULL)
}
fitModel <- train(
formula(diffPercent ~ .),
data = modelData$train,
method = "kknn",
metric = "RMSE",
trControl = control,
tuneGrid = expand.grid(
kmax = kMax,
distance = 2,
kernel = "optimal"
)
)
return(fitModel)
}
parseSolutionParameters <- function(solution) {
pxSelect <- pxSelectAll
orbLimit <- solution[1]
kMax <- solution[2]
pySelect <- pySelectAll[solution[3:gaParamsNum] == 1]
return(list(
pxSelect = pxSelect,
pySelect = pySelect,
orbLimit = orbLimit,
kMax = kMax
))
}
testModelFit <- function(fitModel, params) {
allFitMetrics <- c()
for (i in 1:5) {
# Validate data predictions with different train partitions.
modelData <- prepareModelData(params)
validateDiffPercentPred <- predict(fitModel, modelData$validate, type = "raw")
validateMAE <- mae(modelData$validate$diffPercent, validateDiffPercentPred)
validateRMSE <- rmse(modelData$validate$diffPercent, validateDiffPercentPred)
validateR2 <- cor(modelData$validate$diffPercent, validateDiffPercentPred)^2
cat("Validate", i, "MAE:", validateMAE, "RMSE:", validateRMSE, "R2:", validateR2, "\n")
allFitMetrics <- c(allFitMetrics, validateR2)
}
fitMetric <- mean(allFitMetrics) / (1 + sd(allFitMetrics))
cat("Final fit metric:", fitMetric, "\n\n")
return(fitMetric)
}
findRelevantFeatures <- function(solution) {
params <- parseSolutionParameters(solution)
fitModel <- modelTrain(params)
# Invalid GA parameters that failed fit, penalize with high negative value.
if (is.null(fitModel)) {
return(-1)
}
fitMetric <- testModelFit(fitModel, params)
return(fitMetric)
}
solutionModelTrain <- function(params) {
# Different partition for each weak learner train
trainIndex <- createDataPartition(securityData$diffPercent, p = 0.80, list = FALSE)
securityDataTrain <- securityData[trainIndex,]
securityDataValidate <- securityData[-trainIndex,]
fitModel <- modelTrain(params)
return(fitModel)
}
cat("\nProcessing GA features selection\n")
gar <- ga(
"real-valued",
fitness = findRelevantFeatures,
lower = c(2, 5, rep(0, gaParamsNum-1)),
upper = c(3, 10, rep(1, gaParamsNum-1)),
popSize = gaPopSize, maxiter = gaMaxIter, run = gaMaxIter,
selection = gaint_rwSelection, mutation = gaint_raMutation,
crossover = gaint_spCrossover, population = gaint_Population,
elitism = base::max(1, round(gaPopSize * 0.3)),
pmutation = 0.4, pcrossover = 0.3,
parallel = F, monitor = gaMonitor, keepBest = T
)
cat("\n")
summary(gar) %>% print()
cat("\nProcessing weak learners train\n")
params <- parseSolutionParameters(gar@solution)
fitModel1 <- solutionModelTrain(params)
fitModel2 <- solutionModelTrain(params)
fitModel3 <- solutionModelTrain(params)
fitModel4 <- solutionModelTrain(params)
fitModel5 <- solutionModelTrain(params)
c(pxSelect, pySelect, orbLimit, kMax) %<-% params
dailyAspects <- prepareDailyAspectsCountPlanetYActivationCount(
dailyAspectsRows, orbLimit, pxSelect, pySelect, aspectsSelectAll
)
aspectView <- merge(
securityData[, c('Date', 'diffPercent', 'Actbin', 'Eff')],
dailyAspects, by = "Date"
)
# Predict outcomes for all weak learner models.
aspectView$DiffPred1 <- predict(fitModel1, aspectView, type = "raw")
aspectView$DiffPred2 <- predict(fitModel2, aspectView, type = "raw")
aspectView$DiffPred3 <- predict(fitModel3, aspectView, type = "raw")
aspectView$DiffPred4 <- predict(fitModel4, aspectView, type = "raw")
aspectView$DiffPred5 <- predict(fitModel5, aspectView, type = "raw")
# Ensamble model data partition.
trainIndex <- createDataPartition(aspectView$Actbin, p = 0.80, list = FALSE)
aspectViewTrain <- aspectView[trainIndex,]
aspectViewValidate <- aspectView[-trainIndex,]
cat("\nProcessing ensamble train\n")
probCols <- c("DiffPred1", "DiffPred2", "DiffPred3", "DiffPred4", "DiffPred5")
topModel <- train(
x = aspectViewTrain[, ..probCols],
y = aspectViewTrain$Actbin,
method = "gbm",
metric = "Kappa",
trControl = trainControl(
method = "repeatedcv",
number = enCVFolds,
repeats = enCVRepeats,
savePredictions = "all",
classProbs = T,
verboseIter = F,
allowParallel = T,
trim = F
),
tuneLength = 3,
verbose = F
)
topModel %>% summary() %>% print()
# Validate data predictions.
aspectViewValidate$EffPred <- predict(topModel, aspectViewValidate, type = "raw")
cat("\n", symbol, "MODEL VALIDATE RESULT:\n")
table(
actual = aspectViewValidate$Actbin,
predicted = aspectViewValidate$EffPred
) %>%
caret::confusionMatrix() %>%
print()
# Reserved data for validation.
securityDataTest <- mainOpenSecurity(
symbol, maPriceFsPeriod, maPriceSlPeriod,
"%Y-%m-%d", testDataStartDate
)
aspectViewTest <- merge(
securityDataTest[, c('Date', 'Actbin', 'Eff')],
dailyAspects,
by = "Date"
)
# Predict outcomes for all weak learner models.
aspectViewTest$DiffPred1 <- predict(fitModel1, aspectViewTest, type = "raw")
aspectViewTest$DiffPred2 <- predict(fitModel2, aspectViewTest, type = "raw")
aspectViewTest$DiffPred3 <- predict(fitModel3, aspectViewTest, type = "raw")
aspectViewTest$DiffPred4 <- predict(fitModel4, aspectViewTest, type = "raw")
aspectViewTest$DiffPred5 <- predict(fitModel5, aspectViewTest, type = "raw")
# Final ensamble prediction.
aspectViewTest$EffPred <- predict(topModel, aspectViewTest, type = "raw")
cat("\n", symbol, "MODEL TEST RESULT:\n")
testResult <- table(
actualclass = aspectViewTest$Actbin,
predictedclass = aspectViewTest$EffPred
) %>% caret::confusionMatrix()
print(testResult)
# Full data set prediction.
dailyAspects$DiffPred1 <- predict(fitModel1, dailyAspects, type = "raw")
dailyAspects$DiffPred2 <- predict(fitModel2, dailyAspects, type = "raw")
dailyAspects$DiffPred3 <- predict(fitModel3, dailyAspects, type = "raw")
dailyAspects$DiffPred4 <- predict(fitModel4, dailyAspects, type = "raw")
dailyAspects$DiffPred5 <- predict(fitModel5, dailyAspects, type = "raw")
# Ensamble buy probability and class prediction.
dailyAspects$BuyProb <- predict(topModel, dailyAspects, type = "prob")$buy
dailyAspects$EffPred <- predict(topModel, dailyAspects, type = "raw")
# Round probabilities.
dailyAspects[, DiffPred1 := format(DiffPred1, format = "f", big.mark = ",", digits = 2)]
dailyAspects[, DiffPred2 := format(DiffPred2, format = "f", big.mark = ",", digits = 2)]
dailyAspects[, DiffPred3 := format(DiffPred3, format = "f", big.mark = ",", digits = 2)]
dailyAspects[, DiffPred4 := format(DiffPred4, format = "f", big.mark = ",", digits = 2)]
dailyAspects[, DiffPred5 := format(DiffPred5, format = "f", big.mark = ",", digits = 2)]
dailyAspects[, BuyProb := format(BuyProb, format = "f", big.mark = ",", digits = 2)]
aspectsCols <- names(aspectView)[-seq(2, 4)]
exportCols <- c(aspectsCols, "EffPred")
fwrite(dailyAspects[, ..exportCols], paste("./predictions/", symbol, "-predict-", modelId, ".csv", sep = ""))
return(
list(symbol = symbol, results = testResult)
)
}
listFilePath <- npath(paste("./symbols/working.csv", sep = ""))
symbolsList <- read.csv(listFilePath, header = F, stringsAsFactors = F)
testResults <- lapply(symbolsList$V1, searchModel)
cat("\nMODEL SEARCH SUMMARY:\n\n")
for (idx in 1:length(testResults)) {
cat(testResults[[idx]]$symbol, "TEST RESULT:\n")
print(testResults[[idx]]$results)
}