homebrewlibra 0.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- homebrewlibra-0.0.0/LICENSE.txt +13 -0
- homebrewlibra-0.0.0/PKG-INFO +24 -0
- homebrewlibra-0.0.0/README.md +6 -0
- homebrewlibra-0.0.0/homebrewlibra/NN_models/__init__.py +0 -0
- homebrewlibra-0.0.0/homebrewlibra/NN_models/model_design.py +94 -0
- homebrewlibra-0.0.0/homebrewlibra/NN_models/model_develop.py +384 -0
- homebrewlibra-0.0.0/homebrewlibra/NN_models/model_reporting.py +196 -0
- homebrewlibra-0.0.0/homebrewlibra/NN_models/model_training.py +89 -0
- homebrewlibra-0.0.0/homebrewlibra/data_tools/__init__.py +66 -0
- homebrewlibra-0.0.0/homebrewlibra/data_tools/model_data_preparation.py +173 -0
- homebrewlibra-0.0.0/homebrewlibra/data_tools/pars_args.py +157 -0
- homebrewlibra-0.0.0/homebrewlibra/gantt_chart/__init__.py +0 -0
- homebrewlibra-0.0.0/homebrewlibra/gantt_chart/gantt_chart.py +183 -0
- homebrewlibra-0.0.0/homebrewlibra/gantt_chart/gantt_chart2PDF.py +96 -0
- homebrewlibra-0.0.0/homebrewlibra/gantt_chart/gantt_chart_daily.py +66 -0
- homebrewlibra-0.0.0/homebrewlibra/gantt_chart/gantt_chart_m.py +108 -0
- homebrewlibra-0.0.0/homebrewlibra/gantt_chart/requirements.txt +3 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_console/__init__.py +11 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_csv/__init__.py +0 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_csv/csv_io_helper.py +58 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_csv/load_csv.py +35 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_data/__init__.py +0 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_data/get_columns.py +28 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_data/make_lag.py +25 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_data/make_normalize.py +43 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_data/set_default_index.py +31 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_date/__init__.py +1 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_date/monthly_date_ranges.py +96 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_exchange/__init__.py +0 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_exchange/exchange_io_helper.py +173 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_exchange/exchange_io_kraken.py +155 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_feather/__init__.py +0 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_feather/feather_io_helper.py +56 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_io/__init__.py +0 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_io/select_files.py +22 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_io/step_execution.py +39 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_json/__init__.py +2 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_json/json_io_helper.py +93 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_market/__init__.py +0 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_market/convert_timestamp_date.py +58 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_market/convert_trades_to_OHLCV.py +297 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_market/grouping_trades.py +501 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_market/market_sides.py +102 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_market/split_trades_to_sides.py +178 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_market/trades_fields.py +76 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_model/__init__.py +0 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_model/simple_01.py +27 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_plot/__init__.py +0 -0
- homebrewlibra-0.0.0/homebrewlibra/helper_plot/plot_tools.py +202 -0
- homebrewlibra-0.0.0/pyproject.toml +36 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Copyright (c) 2026, Alexey Glebov
|
|
2
|
+
|
|
3
|
+
All rights reserved.
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
|
6
|
+
|
|
7
|
+
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
|
8
|
+
|
|
9
|
+
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
|
10
|
+
|
|
11
|
+
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
|
12
|
+
|
|
13
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: homebrewlibra
|
|
3
|
+
Version: 0.0.0
|
|
4
|
+
Summary: A collection of packages designed to process and analyze market data
|
|
5
|
+
License-File: LICENSE.txt
|
|
6
|
+
Author: Alex Glebov
|
|
7
|
+
Author-email: alex.glebov@gmail.com
|
|
8
|
+
Requires-Python: >=3.12
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
13
|
+
Requires-Dist: matplotlib (>=3.10.8)
|
|
14
|
+
Requires-Dist: numpy (>=2.4.2)
|
|
15
|
+
Requires-Dist: pandas (>=3.0.1)
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
## Contributing
|
|
20
|
+
|
|
21
|
+
This is an admittedly small project. Still, if you have any contributions,
|
|
22
|
+
please [fork this project on github](https://github.com/Alex-Glebov/) and
|
|
23
|
+
send me a pull request.
|
|
24
|
+
|
|
File without changes
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
'''
|
|
2
|
+
Created on 3 Feb 2026
|
|
3
|
+
|
|
4
|
+
@author: alex
|
|
5
|
+
'''
|
|
6
|
+
#import pandas as pd
|
|
7
|
+
import numpy as np
|
|
8
|
+
from keras.layers import (
|
|
9
|
+
Dense,
|
|
10
|
+
Input,
|
|
11
|
+
Concatenate,
|
|
12
|
+
Conv1D,
|
|
13
|
+
Conv2D,
|
|
14
|
+
LSTM,
|
|
15
|
+
BatchNormalization,
|
|
16
|
+
Dropout,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from keras.models import Model
|
|
20
|
+
from projectconfig import __Model_Data__ as mdld
|
|
21
|
+
|
|
22
|
+
import logging
|
|
23
|
+
__logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
#def create_sequences(data, seq_length):
|
|
26
|
+
# xs = []
|
|
27
|
+
# for i in range(len(data) - seq_length):
|
|
28
|
+
# xs.append(data[i:(i + seq_length)])
|
|
29
|
+
# return np.array(xs)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def model_design(version=0, **kwargs )->Model: # batch, timesteps=0, features=1, targets=1, strides=1,
|
|
33
|
+
"""
|
|
34
|
+
X_shape = X_train.shape
|
|
35
|
+
Y_shape = 1 if Y_train.shape.__len__()==1 else Y_train.shape[:-1]
|
|
36
|
+
Model 0
|
|
37
|
+
"""
|
|
38
|
+
if version == '_Conv1D_':
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
# load from params override mdld default
|
|
42
|
+
# mdld.timesteps
|
|
43
|
+
# mdld.n_features
|
|
44
|
+
# mdld.kernel_size
|
|
45
|
+
# mdld.strides_length
|
|
46
|
+
# mdld.n_targets
|
|
47
|
+
|
|
48
|
+
inputs = Input(shape=(mdld.timesteps,mdld.n_features))#(batch,timesteps,X_shape[0]))
|
|
49
|
+
# Branch 1
|
|
50
|
+
branch1 = Conv1D(
|
|
51
|
+
filters=128,
|
|
52
|
+
kernel_size=mdld.kernel_size,
|
|
53
|
+
strides=mdld.strides_length,
|
|
54
|
+
activation="sigmoid",
|
|
55
|
+
padding='same',
|
|
56
|
+
name='branch1'
|
|
57
|
+
)(inputs)
|
|
58
|
+
branch1n = BatchNormalization()(branch1) # ā often helps Conv1D + LSTM combo
|
|
59
|
+
branch2 = LSTM(128, recurrent_dropout=0.2, return_sequences=True )(branch1n)
|
|
60
|
+
branch3 = LSTM(64, recurrent_dropout=0.2 )(branch2)
|
|
61
|
+
branch4 = Dense(64, activation='relu')(branch3)
|
|
62
|
+
branch4d = Dropout(0.2)(branch4) # ā helps generalization
|
|
63
|
+
outputs = Dense(mdld.n_targets, activation=None)(branch4d)
|
|
64
|
+
model = Model(inputs=inputs, outputs=outputs)
|
|
65
|
+
except BaseException as e:
|
|
66
|
+
__logger.exception(e)
|
|
67
|
+
"""
|
|
68
|
+
X_shape = X_train.shape[1]
|
|
69
|
+
Y_shape = 1 if Y_train.shape.__len__()==1 else Y_train.shape[1]
|
|
70
|
+
Model 0
|
|
71
|
+
"""
|
|
72
|
+
elif version == 0 :
|
|
73
|
+
raise(ValueError("need to check first this model"))
|
|
74
|
+
inputs = Input(shape=(mdld.n_features,))
|
|
75
|
+
# Branch 1
|
|
76
|
+
branch1 = Dense(256, activation='sigmoid')(inputs)
|
|
77
|
+
branch1 = Dense(128, activation='sigmoid')(branch1) # output shape: (batch, 64)
|
|
78
|
+
|
|
79
|
+
# Branch 2
|
|
80
|
+
branch2 = Dense(126, activation='tanh')(inputs)
|
|
81
|
+
branch2 = Dense(64, activation='tanh')(branch2) # output shape: (batch, 32)
|
|
82
|
+
|
|
83
|
+
# JOIN (concatenate) the two branches
|
|
84
|
+
merged = Concatenate()([branch1, branch2]) # shape: (batch, 64 + 32 = 96)
|
|
85
|
+
|
|
86
|
+
# Continue with merged as input
|
|
87
|
+
x = Dense(64, activation='relu')(merged)
|
|
88
|
+
outputs = Dense(mdld.n_targets, activation='sigmoid')(x)
|
|
89
|
+
model = Model(inputs=inputs, outputs=outputs)
|
|
90
|
+
# MODEL_VERSION='_Conv1D_'
|
|
91
|
+
else:
|
|
92
|
+
raise ValueError(f"Undefined version of model ")
|
|
93
|
+
|
|
94
|
+
return model
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
'''
|
|
2
|
+
Created on 30 Jan 2026
|
|
3
|
+
|
|
4
|
+
@author: alex
|
|
5
|
+
|
|
6
|
+
top levelfunction, called by All_Pairs_timeframes
|
|
7
|
+
'''
|
|
8
|
+
from pandas import DataFrame
|
|
9
|
+
import numpy as np
|
|
10
|
+
import keras
|
|
11
|
+
import tensorflow as tf
|
|
12
|
+
from keras.models import load_model
|
|
13
|
+
from keras.utils import timeseries_dataset_from_array
|
|
14
|
+
from sklearn.preprocessing._data import StandardScaler # install scikit-learn
|
|
15
|
+
|
|
16
|
+
from helper_csv.load_csv import load_csv
|
|
17
|
+
from data_tools.model_data_preparation import model_data_preparation,\
|
|
18
|
+
convert_y_pred
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
import joblib
|
|
21
|
+
|
|
22
|
+
from projectconfig import __Model_Data__ as mdld, data_path_mdl_templates
|
|
23
|
+
from NN_models.model_training import just_training
|
|
24
|
+
from NN_models.model_design import model_design
|
|
25
|
+
from NN_models.model_reporting import report_history, report_prediction,\
|
|
26
|
+
report_plot, report_plot_test
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
import logging
|
|
31
|
+
__logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
#model:Model =Model()
|
|
34
|
+
|
|
35
|
+
def model_preparation(ticker:str, timeframe:str, period:str, **kwargs)->None:
|
|
36
|
+
try:
|
|
37
|
+
#load data for model X_test, Y_test
|
|
38
|
+
context = globals() | locals() | kwargs
|
|
39
|
+
path_file = Path(context['data_path_src_templates'].format(**context)) # source of raw data
|
|
40
|
+
# local data
|
|
41
|
+
df = load_csv(path_file)
|
|
42
|
+
# do not load scalers
|
|
43
|
+
# normalize data
|
|
44
|
+
X_train, Y_train, scaler_x, scaler_y = model_data_preparation(
|
|
45
|
+
df,
|
|
46
|
+
modify_list=mdld.normalize_list,
|
|
47
|
+
**context # all details below
|
|
48
|
+
)
|
|
49
|
+
# create model
|
|
50
|
+
if isinstance(X_train,tf.data.Dataset):
|
|
51
|
+
for batch_x, batch_y in X_train.take(1):
|
|
52
|
+
X_shape = batch_x.shape
|
|
53
|
+
Y_shape = batch_y.shape
|
|
54
|
+
__logger.info(f"X batch shape (inputs) : {X_shape}") # usually (batch_size, sequence_length, features)
|
|
55
|
+
__logger.info(f"Y batch shape (targets) : {Y_shape}") # depends on your targets
|
|
56
|
+
break
|
|
57
|
+
model = model_design(version=mdld.MODEL_VERSION)
|
|
58
|
+
else:
|
|
59
|
+
features = X_train.shape[-1]
|
|
60
|
+
Y_shape = [1] if Y_train.shape.__len__()==1 else Y_train.shape
|
|
61
|
+
model = model_design(version=mdld.MODEL_VERSION,n_features=features)
|
|
62
|
+
# #compile model
|
|
63
|
+
# model.compile(
|
|
64
|
+
# optimizer = keras.optimizers.Adam(
|
|
65
|
+
# learning_rate=0.001, # ā use your original values!
|
|
66
|
+
# beta_1=0.9,
|
|
67
|
+
# beta_2=0.999,
|
|
68
|
+
# epsilon=1e-7,
|
|
69
|
+
# amsgrad=False
|
|
70
|
+
# ),
|
|
71
|
+
# metrics =['mse'],
|
|
72
|
+
# loss = 'mse',
|
|
73
|
+
# )
|
|
74
|
+
# save model
|
|
75
|
+
model.summary(print_fn=__logger.info, show_trainable=True)
|
|
76
|
+
context['type']='model'
|
|
77
|
+
context['MODEL_VERSION'] = mdld.MODEL_VERSION
|
|
78
|
+
path_data = Path(data_path_mdl_templates['model'].format(**context))
|
|
79
|
+
model.save(filepath=path_data,overwrite=True)
|
|
80
|
+
__logger.info(f"\nš¾ Model saved as '{path_data}'")
|
|
81
|
+
# save scalers
|
|
82
|
+
context['type']='scaler_x'
|
|
83
|
+
path_data = Path(data_path_mdl_templates['scaler'].format(**context))
|
|
84
|
+
joblib.dump(scaler_x, path_data, compress=9)
|
|
85
|
+
context['type']='scaler_y'
|
|
86
|
+
path_data = Path(data_path_mdl_templates['scaler'].format(**context))
|
|
87
|
+
joblib.dump(scaler_y, path_data, compress=9)
|
|
88
|
+
except ValueError as e:
|
|
89
|
+
__logger.exception(e,exc_info=True)
|
|
90
|
+
# save model
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
def model_training(ticker:str, timeframe:str, period:str, **kwargs)->None:
|
|
94
|
+
try:
|
|
95
|
+
#load compiled model
|
|
96
|
+
context = globals() | locals() | kwargs
|
|
97
|
+
|
|
98
|
+
context['type']='model'
|
|
99
|
+
context['MODEL_VERSION'] = mdld.MODEL_VERSION
|
|
100
|
+
context['file_format']='keras'
|
|
101
|
+
path_file_model = Path(data_path_mdl_templates['model'].format(**context))
|
|
102
|
+
model=load_model(path_file_model)
|
|
103
|
+
__logger.info(f"\nš¾ Model loaded from '{path_file_model}'")
|
|
104
|
+
model.summary(print_fn=__logger.info, show_trainable=True)
|
|
105
|
+
# load scalers
|
|
106
|
+
# CHECK LOADED PARAMS
|
|
107
|
+
|
|
108
|
+
#batch_size form pro
|
|
109
|
+
#n_features
|
|
110
|
+
#n_targets
|
|
111
|
+
#window_size
|
|
112
|
+
#sequence_stride
|
|
113
|
+
|
|
114
|
+
context['type']='scaler_x'
|
|
115
|
+
path_data = Path(data_path_mdl_templates['scaler'].format(**context))
|
|
116
|
+
scaler_x = joblib.load(path_data)
|
|
117
|
+
context['type']='scaler_y'
|
|
118
|
+
path_data = Path(data_path_mdl_templates['scaler'].format(**context))
|
|
119
|
+
scaler_y = joblib.load( path_data)
|
|
120
|
+
|
|
121
|
+
path_file = Path(context['data_path_src_templates'].format(**context))
|
|
122
|
+
df = load_csv(path_file)
|
|
123
|
+
X_train, Y_train, scaler_x, scaler_y = model_data_preparation(
|
|
124
|
+
df,
|
|
125
|
+
modify_list=mdld.normalize_list,
|
|
126
|
+
scaler_x=scaler_x, scaler_y= scaler_y,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
# training
|
|
130
|
+
context['period']=context['periods_dev'][0]
|
|
131
|
+
path_file = Path(context['data_path_src_templates'].format(**context))
|
|
132
|
+
df = load_csv(path_file)
|
|
133
|
+
X_Dev, Y_Dev, scaler_x, scaler_y = model_data_preparation(
|
|
134
|
+
df,
|
|
135
|
+
modify_list=mdld.normalize_list,
|
|
136
|
+
scaler_x=scaler_x, scaler_y= scaler_y,
|
|
137
|
+
)
|
|
138
|
+
context['scaler_y']=scaler_y
|
|
139
|
+
#compile model
|
|
140
|
+
model.compile(
|
|
141
|
+
optimizer = keras.optimizers.Adam(
|
|
142
|
+
learning_rate=0.001, # ā use your original values!
|
|
143
|
+
beta_1=0.9,
|
|
144
|
+
beta_2=0.999,
|
|
145
|
+
epsilon=1e-7,
|
|
146
|
+
amsgrad=False
|
|
147
|
+
),
|
|
148
|
+
metrics =[ keras.metrics.RootMeanSquaredError()], # 'mae', 'mse', , keras.metrics.R2Score()
|
|
149
|
+
loss = 'mse',
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
model,history = just_training(
|
|
153
|
+
model=model,
|
|
154
|
+
X=X_train,Y=Y_train,
|
|
155
|
+
X_dev=X_Dev,Y_dev=Y_Dev,
|
|
156
|
+
batch =context.get('batch_size',mdld.batch_size),
|
|
157
|
+
epochs=context.get('epochs',30)
|
|
158
|
+
|
|
159
|
+
)
|
|
160
|
+
# save trained model and history
|
|
161
|
+
|
|
162
|
+
model.save(filepath=path_file_model,overwrite=True)
|
|
163
|
+
context['type']='history'
|
|
164
|
+
context['period']=period
|
|
165
|
+
path_data = Path(data_path_mdl_templates['history'].format(**context))
|
|
166
|
+
joblib.dump(history, path_data, compress=9)
|
|
167
|
+
except BaseException as e:
|
|
168
|
+
__logger.fatal(e)
|
|
169
|
+
return None
|
|
170
|
+
|
|
171
|
+
def model_train_all(ticker:str, timeframe:str, period:str, **kwargs)->None:
|
|
172
|
+
try:
|
|
173
|
+
#load compiled model
|
|
174
|
+
context = globals() | locals() | kwargs
|
|
175
|
+
|
|
176
|
+
context['type']='model'
|
|
177
|
+
context['MODEL_VERSION'] = mdld.MODEL_VERSION
|
|
178
|
+
context['file_format']='keras'
|
|
179
|
+
path_file_model = Path(data_path_mdl_templates['model'].format(**context))
|
|
180
|
+
model=load_model(path_file_model)
|
|
181
|
+
__logger.info(f"\nš¾ Model loaded from '{path_file_model}'")
|
|
182
|
+
model.summary(print_fn=__logger.info, show_trainable=True)
|
|
183
|
+
# load scalers
|
|
184
|
+
# CHECK LOADED PARAMS
|
|
185
|
+
|
|
186
|
+
#batch_size form pro
|
|
187
|
+
#n_features
|
|
188
|
+
#n_targets
|
|
189
|
+
#window_size
|
|
190
|
+
#sequence_stride
|
|
191
|
+
|
|
192
|
+
context['type']='scaler_x'
|
|
193
|
+
path_data = Path(data_path_mdl_templates['scaler'].format(**context))
|
|
194
|
+
scaler_x = joblib.load(path_data)
|
|
195
|
+
context['type']='scaler_y'
|
|
196
|
+
path_data = Path(data_path_mdl_templates['scaler'].format(**context))
|
|
197
|
+
scaler_y = joblib.load( path_data)
|
|
198
|
+
|
|
199
|
+
path_file = Path(context['data_path_src_templates'].format(**context))
|
|
200
|
+
df = load_csv(path_file)
|
|
201
|
+
X_train, Y_train, scaler_x, scaler_y = model_data_preparation(
|
|
202
|
+
df,
|
|
203
|
+
modify_list=mdld.normalize_list,
|
|
204
|
+
scaler_x=scaler_x, scaler_y= scaler_y,
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
# training
|
|
208
|
+
context['period']=context['periods_dev'][0]
|
|
209
|
+
path_file = Path(context['data_path_src_templates'].format(**context))
|
|
210
|
+
df = load_csv(path_file)
|
|
211
|
+
X_Dev, Y_Dev, scaler_x, scaler_y = model_data_preparation(
|
|
212
|
+
df,
|
|
213
|
+
modify_list=mdld.normalize_list,
|
|
214
|
+
scaler_x=scaler_x, scaler_y= scaler_y,
|
|
215
|
+
)
|
|
216
|
+
context['scaler_y']=scaler_y
|
|
217
|
+
#compile model
|
|
218
|
+
model.compile(
|
|
219
|
+
optimizer = keras.optimizers.Adam(
|
|
220
|
+
learning_rate=0.001, # ā use your original values!
|
|
221
|
+
beta_1=0.9,
|
|
222
|
+
beta_2=0.999,
|
|
223
|
+
epsilon=1e-7,
|
|
224
|
+
amsgrad=False
|
|
225
|
+
),
|
|
226
|
+
metrics =[ keras.metrics.RootMeanSquaredError()], # 'mae', 'mse', , keras.metrics.R2Score()
|
|
227
|
+
loss = 'mse',
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
model,history = just_training(
|
|
231
|
+
model=model,
|
|
232
|
+
X=X_train,Y=Y_train,
|
|
233
|
+
X_dev=X_Dev,Y_dev=Y_Dev,
|
|
234
|
+
batch =context.get('batch_size',mdld.batch_size),
|
|
235
|
+
epochs=context.get('epochs',30)
|
|
236
|
+
|
|
237
|
+
)
|
|
238
|
+
# save trained model and history
|
|
239
|
+
|
|
240
|
+
model.save(filepath=path_file_model,overwrite=True)
|
|
241
|
+
context['type']='history'
|
|
242
|
+
context['period']=period
|
|
243
|
+
path_data = Path(data_path_mdl_templates['history'].format(**context))
|
|
244
|
+
joblib.dump(history, path_data, compress=9)
|
|
245
|
+
except BaseException as e:
|
|
246
|
+
__logger.fatal(e)
|
|
247
|
+
return None
|
|
248
|
+
|
|
249
|
+
def model_prediction(ticker:str, timeframe:str, period:str, **kwargs)->None:
|
|
250
|
+
|
|
251
|
+
try:
|
|
252
|
+
context = globals() | locals() | kwargs
|
|
253
|
+
# load scalers
|
|
254
|
+
context['MODEL_VERSION']=mdld.MODEL_VERSION
|
|
255
|
+
context['type']='scaler_x'
|
|
256
|
+
path_data = Path(data_path_mdl_templates['scaler'].format(**context))
|
|
257
|
+
scaler_x = joblib.load(path_data)
|
|
258
|
+
context['type']='scaler_y'
|
|
259
|
+
path_data = Path(data_path_mdl_templates['scaler'].format(**context))
|
|
260
|
+
scaler_y = joblib.load( path_data)
|
|
261
|
+
# load test data
|
|
262
|
+
|
|
263
|
+
context['period']=context['periods_test'][0] # load new data dor testing
|
|
264
|
+
path_file = Path(context['data_path_src_templates'].format(**context))
|
|
265
|
+
df = load_csv(path_file)
|
|
266
|
+
if df.index.name !='timestamp':
|
|
267
|
+
df.set_index('timestamp',inplace=True,drop=False)
|
|
268
|
+
Y_orig = df[mdld.Ynames]
|
|
269
|
+
|
|
270
|
+
# need to calc
|
|
271
|
+
# peaks_data = df['peaks'] # will be used in graph
|
|
272
|
+
# peaks_line_name= 'peaks_line'
|
|
273
|
+
# normalize test data
|
|
274
|
+
#
|
|
275
|
+
X_test, Y_test, scaler_x, scaler_y = model_data_preparation(
|
|
276
|
+
df,
|
|
277
|
+
modify_list=mdld.normalize_list,
|
|
278
|
+
scaler_x=scaler_x, scaler_y= scaler_y,
|
|
279
|
+
#no_Y_include=True,
|
|
280
|
+
batch_size=None
|
|
281
|
+
)
|
|
282
|
+
context['scaler_y']=scaler_y
|
|
283
|
+
context['period'] = period
|
|
284
|
+
context['type']='model'
|
|
285
|
+
context['file_format']='keras'
|
|
286
|
+
path_file = Path(data_path_mdl_templates['model'].format(**context))
|
|
287
|
+
model=load_model(path_file)
|
|
288
|
+
print(f"\nš¾ Model loaded from '{path_file}'")
|
|
289
|
+
|
|
290
|
+
print("š Evaluating model...")
|
|
291
|
+
Y_pred = model.predict(X_test)
|
|
292
|
+
if isinstance(X_test,tf.data.Dataset):
|
|
293
|
+
test_loss, test_acc = model.evaluate(X_test, Y_test, verbose=0)
|
|
294
|
+
else:
|
|
295
|
+
test_loss, test_acc = model.evaluate(X_test, verbose=0)
|
|
296
|
+
|
|
297
|
+
report_prediction(test_loss, test_acc, **kwargs)
|
|
298
|
+
|
|
299
|
+
except BaseException as e:
|
|
300
|
+
__logger.fatal(e)
|
|
301
|
+
return None
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def model_reporting(ticker:str, timeframe:str, period, **kwargs)->None:
|
|
306
|
+
# prep_data model_prepare model_train model_predict
|
|
307
|
+
try:
|
|
308
|
+
|
|
309
|
+
context = globals() | locals() | kwargs
|
|
310
|
+
context['MODEL_VERSION']=mdld.MODEL_VERSION
|
|
311
|
+
# load model
|
|
312
|
+
context['type']='model'
|
|
313
|
+
context['file_format']='keras'
|
|
314
|
+
path_file = Path(data_path_mdl_templates['model'].format(**context))
|
|
315
|
+
model=load_model(path_file)
|
|
316
|
+
print(f"\nš¾ Model loaded from '{path_file}'")
|
|
317
|
+
|
|
318
|
+
# report traning
|
|
319
|
+
context['type']='history'
|
|
320
|
+
path_data = Path(data_path_mdl_templates['history'].format(**context))
|
|
321
|
+
history = joblib.load(path_data)
|
|
322
|
+
#
|
|
323
|
+
#
|
|
324
|
+
report_history(history,**context)
|
|
325
|
+
#
|
|
326
|
+
context['type']='scaler_x'
|
|
327
|
+
path_data = Path(data_path_mdl_templates['scaler'].format(**context))
|
|
328
|
+
scaler_x = joblib.load(path_data)
|
|
329
|
+
context['type']='scaler_y'
|
|
330
|
+
path_data = Path(data_path_mdl_templates['scaler'].format(**context))
|
|
331
|
+
scaler_y = joblib.load( path_data)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
context['period']=context['periods_test'][0] # load new data dor testing
|
|
335
|
+
path_file = Path(context['data_path_src_templates'].format(**context))
|
|
336
|
+
df = load_csv(path_file)
|
|
337
|
+
# normally index setup at the model_data_preparation function
|
|
338
|
+
# df.set_index('timestamp',inplace=True,drop=True)
|
|
339
|
+
Y_orig = df[mdld.Ynames].to_numpy()
|
|
340
|
+
|
|
341
|
+
X_test, Y_test, scaler_x, scaler_y = model_data_preparation(
|
|
342
|
+
df,
|
|
343
|
+
modify_list=mdld.normalize_list,
|
|
344
|
+
scaler_x=scaler_x, scaler_y= scaler_y,
|
|
345
|
+
#no_Y_include=True,
|
|
346
|
+
batch_size=None,
|
|
347
|
+
**context
|
|
348
|
+
)
|
|
349
|
+
kwargs['scaler_y']=scaler_y
|
|
350
|
+
# test batches
|
|
351
|
+
# for batch in dataset:
|
|
352
|
+
# inputs, targets = batch
|
|
353
|
+
# assert np.array_equal(inputs[0], data[:10]) # First sequence: steps [0-9]
|
|
354
|
+
# # Corresponding target: step 10
|
|
355
|
+
# assert np.array_equal(targets[0], data[10])
|
|
356
|
+
# break
|
|
357
|
+
#
|
|
358
|
+
#
|
|
359
|
+
print("š Evaluating model...")
|
|
360
|
+
Y_pred = model.predict(X_test)
|
|
361
|
+
Y_pred = scaler_y.inverse_transform(Y_pred)
|
|
362
|
+
# report sourd data
|
|
363
|
+
report_plot_test(['price','peaks_line' ] ,df,**context )
|
|
364
|
+
i=0
|
|
365
|
+
for idx in mdld.Ynames:
|
|
366
|
+
report_plot_test([idx],df,{idx:Y_pred[:,i]},**context)
|
|
367
|
+
i+=1
|
|
368
|
+
p1= df['peaks']==1
|
|
369
|
+
p2= df['peaks']==-1
|
|
370
|
+
kwargs['_peak']=list(np.where(p1==True)[0])[1:-1]
|
|
371
|
+
kwargs['_valy']=list(np.where(p2==True)[0])[1:-1]
|
|
372
|
+
# kwargs['cross_below']=None
|
|
373
|
+
# kwargs['cross_above']=None
|
|
374
|
+
signal_ = convert_y_pred(Y_orig,**kwargs)
|
|
375
|
+
signals = convert_y_pred(Y_pred,**kwargs)
|
|
376
|
+
#
|
|
377
|
+
# so we have Y_test, Y_signal, Y_pred
|
|
378
|
+
#
|
|
379
|
+
context['Ynames']= mdld.Ynames
|
|
380
|
+
plt = report_plot(Y_pred,Y_orig,df,signals,**context)
|
|
381
|
+
# model_prepare model_train model_predict
|
|
382
|
+
except BaseException as e:
|
|
383
|
+
__logger.fatal(e)
|
|
384
|
+
return None
|