Zorro can indeed use PyTorch directly if you configure it to run Python scripts through the pynet.cpp interface. This method allows you to train and use a PyTorch model directly from Zorro without needing to write a separate data passing script. Here’s how to do it using Zorro’s pynet.cpp and a Python script with PyTorch:
Install Required Python Libraries:
Make sure you have Python 64-bit installed.
Install the necessary libraries by running:
pip3 install torch numpy math
Open Zorro.ini and set the PythonPath64 variable to the path of your Python installation. For example:
PythonPath64 = "C:\Users\YourName\AppData\Local\Programs\Python\Python312"
Write a PyTorch Model Script:
In the same directory as your Zorro script, create a Python file with the same name as your Zorro strategy file, but with a .py extension (e.g., if your Zorro script is MyStrategy.c, name the Python file MyStrategy.py).
This Python script will contain the PyTorch model, functions for prediction, and optionally for training.
import torch
import torch.nn as nn
import numpy as np
class TradingModel(nn.Module):
def __init__(self, input_size, hidden_size):
super(TradingModel, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.relu(self.fc1(x))
x = self.sigmoid(self.fc2(x))
return x
# Initialize the model with input size and hidden layer size
model = TradingModel(input_size=8, hidden_size=256) # Adjust based on your input features
# Load trained model weights if available
try:
model.load_state_dict(torch.load("model.pth"))
model.eval()
except FileNotFoundError:
print("Model weights file not found. Train the model first.")
def predict(input_data):
input_tensor = torch.tensor(input_data, dtype=torch.float32)
with torch.no_grad():
prediction = model(input_tensor)
return prediction.item()
Using pynet.cpp to Call Python from Zorro:
pynet.cpp allows Zorro to call Python functions, making it possible to run PyTorch directly for predictions.
To use the model in Zorro, write the lite-C code that sends data to predict in your Python script, fetches the result, and executes trades based on the output.
function run()
{
vars InputData = series(priceClose());
double Data[8]; // Adjust based on your input features
for(int i = 0; i < 8; i++)
Data[i] = InputData[i]; // Gather recent data for model input
// Call the predict function in MyStrategy.py
python("Y = predict", Data, 8); // Sends data to the Python function `predict`
var prediction = python("Y"); // Retrieve the prediction result from Python
// Trade decision based on prediction
if(prediction > 0.5) enterLong();
else enterShort();
}
Compile and Run with Zorro:
Use the 64-bit version of Zorro to run this script, as pynet.cpp requires a 64-bit Python setup.
This setup calls the predict function in the MyStrategy.py script, passing Data as input, and receives Y, which is used to decide whether to enter a long or short position.
Explanation of the Code
Zorro’s python() Command: python() is used to send and retrieve data between Zorro and Python.
Trade Logic: Based on the prediction returned by python("Y"), the script enters a long or short position.
Model Reusability: You can save and load the trained model in the Python script, so Zorro will use the latest saved model for predictions.
This setup provides a clean integration that allows Zorro to use a PyTorch model directly for predictions without needing extra data transfer scripts.
Please note : these scripts are 80% logical and need to be refined so that it will work well. While deeper experimentation is always needed to make a trading strategy perfect.