lecrapaud 0.2.1__py3-none-any.whl → 0.3.0__py3-none-any.whl

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.

Potentially problematic release.


This version of lecrapaud might be problematic. Click here for more details.

lecrapaud/training.py DELETED
@@ -1,239 +0,0 @@
1
- import logging
2
- import joblib
3
- from pathlib import Path
4
- import os
5
-
6
- from lecrapaud.experiment import create_dataset
7
- from lecrapaud.feature_engineering import (
8
- feature_engineering,
9
- encode_categorical_features,
10
- add_pca_features,
11
- summarize_dataframe,
12
- )
13
- from lecrapaud.feature_selection import (
14
- feature_selection,
15
- train_val_test_split,
16
- train_val_test_split_time_series,
17
- scale_data,
18
- reshape_time_series,
19
- )
20
- from lecrapaud.model_selection import model_selection
21
- from lecrapaud.search_space import all_models
22
- from lecrapaud.directory_management import tmp_dir
23
- from lecrapaud.db import Dataset
24
- from lecrapaud.utils import logger
25
- from lecrapaud.config import PYTHON_ENV
26
-
27
-
28
- # Parameters
29
- columns_date = ["DATE"]
30
- columns_te_groupby = [["SECTOR", "DATE"], ["SUBINDUSTRY", "DATE"]]
31
- columns_te_target = ["RET", "VOLUME", "RESIDUAL_RET", "RELATIVE_VOLUME"] + [
32
- f"{ind}_{p}"
33
- for p in [9, 14, 21, 50]
34
- for ind in [
35
- "CUMUL_RET",
36
- "SMA",
37
- "EMA",
38
- "VOLATILITY",
39
- "ATR",
40
- "ADX",
41
- "%K",
42
- "RSI",
43
- "MFI",
44
- ]
45
- ]
46
- target_clf = [2, 4, 6, 8, 9, 10, 11]
47
- column_ordinal = ["STOCK"]
48
- column_binary = ["SECTOR", "SUBINDUSTRY", "LOCATION"]
49
- columns_pca = []
50
- target_numbers = range(1, 15)
51
- date_column = "DATE"
52
- group_column = "STOCK"
53
-
54
-
55
- def run_training(
56
- get_data_function: function,
57
- get_data_params: dict = None,
58
- time_series: bool = False,
59
- dataset_id=None,
60
- years_of_data=2,
61
- list_of_groups=None,
62
- percentile=15,
63
- corr_threshold=80,
64
- max_features=20,
65
- max_timesteps=120,
66
- targets_numbers=range(1, 15),
67
- models_idx=range(len(all_models)),
68
- number_of_trials=20,
69
- perform_hyperoptimization=True,
70
- perform_crossval=False,
71
- clean_dir=False,
72
- preserve_model=False,
73
- session_name="test",
74
- ):
75
- logging.captureWarnings(True)
76
-
77
- if any(all_models[i].get("recurrent") for i in models_idx) and not time_series:
78
- ValueError(
79
- "You need to set time_series to true to use recurrent model, or remove recurrent models from models_idx chosen"
80
- )
81
-
82
- if dataset_id is None:
83
- # Get the data
84
- logger.info("Getting data...")
85
- data = get_data_function(**get_data_params)
86
-
87
- # # preprocess & feature engineering => Should be in get_data_function
88
- # logger.info("Preprocessing...")
89
- # preprocessed_data = preprocessing(data, for_training=True, save_as_csv=True)
90
-
91
- logger.info(f"Feature engineering for {session_name}...")
92
- data_for_training = feature_engineering(
93
- data,
94
- columns_date=columns_date,
95
- columns_te_groupby=columns_te_groupby,
96
- columns_te_target=columns_te_target,
97
- )
98
-
99
- # Split
100
- if time_series:
101
- train, val, test = train_val_test_split_time_series(data_for_training)
102
- else:
103
- train, val, test = train_val_test_split(
104
- data, stratify_col=f"target_{target_numbers[0]}"
105
- ) # TODO: only stratifying first target for now
106
-
107
- # Create Dataset / Experiment (TODO: should be defined sooner)
108
- dataset = create_dataset(
109
- train, val, test, corr_threshold, percentile, max_features
110
- )
111
- dataset_dir = dataset.path
112
- dataset_id = dataset.id
113
- data_dir = f"{dataset_dir}/data"
114
- preprocessing_dir = f"{dataset_dir}/preprocessing"
115
- os.makedirs(data_dir, exist_ok=True)
116
- os.makedirs(preprocessing_dir, exist_ok=True)
117
-
118
- # PCA
119
- train, pcas = add_pca_features(train, columns_pca)
120
- val, _ = add_pca_features(val, columns_pca, pcas=pcas)
121
- test, _ = add_pca_features(test, columns_pca, pcas=pcas)
122
-
123
- if PYTHON_ENV != "Test":
124
- joblib.dump(pcas, f"{preprocessing_dir}/pca.pkl")
125
-
126
- # Encoding
127
- train, transformer = encode_categorical_features(
128
- train, column_ordinal=column_ordinal, column_binary=column_binary
129
- )
130
- val, _ = encode_categorical_features(
131
- val,
132
- column_ordinal=column_ordinal,
133
- column_binary=column_binary,
134
- transformer=transformer,
135
- )
136
- test, _ = encode_categorical_features(
137
- test,
138
- column_ordinal=column_ordinal,
139
- column_binary=column_binary,
140
- transformer=transformer,
141
- )
142
-
143
- if PYTHON_ENV != "Test":
144
- joblib.dump(data_for_training, f"{data_dir}/full.pkl")
145
- joblib.dump(transformer, f"{preprocessing_dir}/column_transformer.pkl")
146
- summary = summarize_dataframe(train)
147
- summary.to_csv(f"{dataset_dir}/feature_summary.csv", index=False)
148
-
149
- # feature selection
150
- logger.info("Feature Selection...")
151
- for target_number in targets_numbers:
152
- feature_selection(
153
- dataset_id=dataset_id,
154
- train=train,
155
- target_number=target_number,
156
- single_process=True,
157
- )
158
-
159
- dataset = Dataset.get(dataset_id)
160
- all_features = dataset.get_all_features()
161
- columns_to_keep = all_features + [f"TARGET_{i}" for i in target_numbers]
162
-
163
- duplicates = [
164
- col for col in set(columns_to_keep) if columns_to_keep.count(col) > 1
165
- ]
166
- if duplicates:
167
- raise ValueError(f"Doublons détectés dans columns_to_keep: {duplicates}")
168
-
169
- train = train[columns_to_keep]
170
- val = val[columns_to_keep]
171
- test = test[columns_to_keep]
172
-
173
- # save data
174
- if PYTHON_ENV != "Test":
175
- joblib.dump(train[columns_to_keep], f"{data_dir}/train.pkl")
176
- joblib.dump(val[columns_to_keep], f"{data_dir}/val.pkl")
177
- joblib.dump(test[columns_to_keep], f"{data_dir}/test.pkl")
178
-
179
- # scaling features
180
- if any(t not in target_clf for t in target_numbers) and any(
181
- all_models[i].get("need_scaling") for i in models_idx
182
- ):
183
- logger.info("Scaling features...")
184
- train_scaled, scaler_x, scalers_y = scale_data(
185
- train, save_dir=preprocessing_dir
186
- )
187
- val_scaled, _, _ = scale_data(
188
- val, save_dir=preprocessing_dir, scaler_x=scaler_x, scalers_y=scalers_y
189
- )
190
- test_scaled, _, _ = scale_data(
191
- test, save_dir=preprocessing_dir, scaler_x=scaler_x, scalers_y=scalers_y
192
- )
193
- else:
194
- train_scaled = None
195
- val_scaled = None
196
- test_scaled = None
197
-
198
- # save data
199
- if PYTHON_ENV != "Test":
200
- joblib.dump(train_scaled, f"{data_dir}/train_scaled.pkl")
201
- joblib.dump(val_scaled, f"{data_dir}/val_scaled.pkl")
202
- joblib.dump(test_scaled, f"{data_dir}/test_scaled.pkl")
203
-
204
- data = {
205
- "train": train,
206
- "val": val,
207
- "test": test,
208
- "train_scaled": train_scaled,
209
- "val_scaled": val_scaled,
210
- "test_scaled": test_scaled,
211
- "scalers_y": scalers_y,
212
- }
213
-
214
- # reshape data for time series
215
- reshaped_data = None
216
- if any(all_models[i].get("recurrent") for i in models_idx) and time_series:
217
- # reshaping data for recurrent models
218
- logger.info("Reshaping data for recurrent models...")
219
- reshaped_data = reshape_time_series(
220
- train_scaled, val_scaled, test_scaled, all_features, timesteps=max_timesteps
221
- )
222
-
223
- # model selection and hyperoptimization
224
- logger.info("Model Selection and Hyperoptimization...")
225
- for target_number in target_numbers:
226
- model_selection(
227
- dataset_id=dataset_id,
228
- models_idx=models_idx,
229
- target_number=target_number,
230
- session_name=session_name,
231
- perform_hyperoptimization=perform_hyperoptimization,
232
- perform_crossval=perform_crossval,
233
- number_of_trials=number_of_trials,
234
- plot=False,
235
- clean_dir=clean_dir,
236
- preserve_model=preserve_model,
237
- reshaped_data=reshaped_data,
238
- data=(data or None),
239
- )
File without changes