|
|
neural function for Python to [Train]
#487842
10/11/23 19:14
10/11/23 19:14
|
Joined: Aug 2023
Posts: 19
izorro
OP
Newbie
|
OP
Newbie
Joined: Aug 2023
Posts: 19
|
In the python-bridge documentation it is mentioned a neural function will be provided in a future zorro release. Would be nice to have it soon. In the mean time I am trying to set it up (most likely incorrectly), and would appreciate some help. Zorro manual, FH/RW blogs - they all lean towards R  This is what im coming up so far with. I have not properly tested yet. I just want someone who had been this route to confirm i am going in the correct direction. The python script.
import numpy as np
from tensorflow import keras
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.optimizers import RMSprop
models = []
def neural_train(model, XY):
X = np.array(XY.iloc[:, :-1])
Y = XY.iloc[:, -1].apply(lambda x: 1 if x > 0 else 0)
model = keras.models.Sequential()
model.add(Dense(30, activation='relu', input_shape=(X.shape[1],)))
model.add(Dropout(0.2))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer=RMSprop(),
metrics=['accuracy'])
model.fit(X, Y, epochs=20, batch_size=20, validation_split=0, shuffle=False)
models.append(model)
def neural_predict(model, X):
if isinstance(X, list):
X = np.array(X)
elif isinstance(X, np.ndarray) and X.ndim == 1:
X = X.reshape(1, -1)
Y = models[model].predict(X)
return [1 if y > 0.5 else 0 for y in Y]
def neural_save(name):
serialized_models = [model.to_json() for model in models]
with open(name, 'w') as file:
for serialized_model in serialized_models:
file.write(serialized_model + '\n')
def neural_load(name):
global models
models = []
with open(name, 'r') as file:
for line in file:
model = keras.models.model_from_json(line.strip())
models.append(model)
def neural_init():
np.random.seed(365)
global models
models = []
# Example usage:
# neural_init()
# neural_train(0, XY)
# result = neural_predict(0, X)
# neural_save('models.txt')
# neural_load('models.txt')
The `neural` function
var neural(int Status, int model, int NumSignals, void* Data)
{
if(!wait(0)) return 0;
// open a Python script with the same name as the strategy script
if(Status == NEURAL_INIT) {
if(!pyStart(strf("%s.py",Script),1)) return 0;
pyX("neural_init()");
return 1;
}
// export batch training samples and call the Python training function
if(Status == NEURAL_TRAIN) {
string name = strf("Data\\signals%i.csv",Core);
file_write(name,Data,0);
pyX(strf("XY = pandas.read_csv('%s%s',header = None)",slash(ZorroFolder),slash(name)));
pySet("AlgoVar",AlgoVar,8);
if(!pyX(strf("neural_train(%i,XY)",model+1)))
return 0;
return 1;
}
// predict the target with the Python predict function
if(Status == NEURAL_PREDICT) {
pySet("AlgoVar",AlgoVar,8);
pySet("X",(double*)Data,NumSignals);
pyX(strf("Y = neural_predict(%i,X)",model+1));
return pyVar("Y[0]");
}
// save all trained models
if(Status == NEURAL_SAVE) {
print(TO_ANY,"\nStore %s",strrchr(Data,'\\')+1);
return pyX(strf("neural_save('%s')",slash(Data)));
}
// load all trained models
if(Status == NEURAL_LOAD) {
printf("\nLoad %s",strrchr(Data,'\\')+1);
return pyX(strf("neural_load('%s')",slash(Data)));
}
return 1;
}
|
|
|
|