Gamestudio Links
Zorro Links
Newest Posts
IBKR datasave problem
by NewbieZorro. 06/11/25 15:11
Marking Exit trades
by jcl. 06/11/25 14:02
SGT_FW
by Aku_Aku. 06/02/25 17:54
The Perfect Adventure Game
by tian. 05/27/25 04:32
ADX values
by Yogpot. 05/25/25 15:11
Transfer of Lots between Algos?
by Jack_Zodiac. 05/25/25 09:30
AUM Magazine
Latest Screens
Stug 3 Stormartillery
Iljuschin 2
Galactic Strike X
Zeal-X2
Who's Online Now
0 registered members (), 357 guests, and 3 spiders.
Key: Admin, Global Mod, Mod
Newest Members
WardyJoubertIII, NewbieZorro, Squarei, tian, Yogpot
19139 Registered Users
Previous Thread
Next Thread
Print Thread
Rate Thread
Page 4 of 9 1 2 3 4 5 6 7 8 9
Multi-Factor Gaussian FX Strategy [Re: TipmyPip] #488292
07/06/24 15:56
07/06/24 15:56
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
Following more factors of correlation, and Market sentiments, we can also include factor exposure, market capitalization, and industry data from various data sources on the web :


Code
#include <default.c>

var alpha, beta;
var filt, filttr, hband, lband;
vars PriceClose, GaussianFiltered, GaussianFilteredTR;

// Define additional factor variables
vars FactorExposure, MarketCap, IndustryData;
var beta0, betaFactor, betaMktCap, betaIndustry;

// Initialize factors for each time period
void initFactors() {
  FactorExposure = series(0);
  MarketCap = series(0);
  IndustryData = series(0);
  
  // Set coefficients based on your model or optimization
  beta0 = 0.01;
  betaFactor = 0.02;
  betaMktCap = 0.03;
  betaIndustry = 0.04;
}

void init() {
  BarPeriod = 60; // 1-hour bars
  LookBack = 144; // Lookback period for the Gaussian filter

  PriceClose = series(priceClose());
  GaussianFiltered = series(0);
  GaussianFilteredTR = series(0);
  
  alpha = calculateAlpha(144, 4); // Sampling Period and Poles
  beta = (1 - cos(2 * PI / 144)) / (pow(1.414, 2 / 4) - 1);
  
  initFactors();
}

var calculateAlpha(int period, int poles) {
  var beta = (1 - cos(2 * PI / period)) / (pow(1.414, 2 / poles) - 1);
  return -beta + sqrt(beta * beta + 2 * beta);
}

void calculateGaussianFilter(vars src, int poles, int period) {
  vars filtSeries = series(0);
  vars filtSeriesTR = series(0);
  var lag = (period - 1) / (2 * poles);
  vars srcData = series(0);
  vars trData = series(0);
  
  for(int i = 0; i < Bar; i++) {
    if(i > lag) {
      srcData[i] = src[i] + (src[i] - src[i - lag]);
      trData[i] = TR() + (TR() - TR(lag));
    } else {
      srcData[i] = src[i];
      trData[i] = TR();
    }
  }
  
  for(int i = 0; i < Bar; i++) {
    filtSeries[i] = filt9x(alpha, srcData[i], 1, poles);
    filtSeriesTR[i] = filt9x(alpha, trData[i], 1, poles);
  }
  
  GaussianFiltered[0] = filtSeries[0];
  GaussianFilteredTR[0] = filtSeriesTR[0];
  
  hband = GaussianFiltered[0] + GaussianFilteredTR[0] * 1.414;
  lband = GaussianFiltered[0] - GaussianFilteredTR[0] * 1.414;
}

var filt9x(var a, var s, int i, int poles) {
  static vars f[10];
  var x = 1 - a;
  var filt = pow(a, i) * s + i * x * f[1] - (i >= 2 ? 36 * pow(x, 2) * f[2] : 0) + (i >= 3 ? 84 * pow(x, 3) * f[3] : 0)
            - (i >= 4 ? 126 * pow(x, 4) * f[4] : 0) + (i >= 5 ? 126 * pow(x, 5) * f[5] : 0) - (i >= 6 ? 84 * pow(x, 6) * f[6] : 0)
            + (i >= 7 ? 36 * pow(x, 7) * f[7] : 0) - (i >= 8 ? 9 * pow(x, 8) * f[8] : 0) + (i == 9 ? 1 * pow(x, 9) * f[9] : 0);
  
  for(int j = 9; j > 0; j--) {
    f[j] = f[j - 1];
  }
  f[0] = filt;
  
  return filt;
}

bool crossOver(vars data, var level) {
  return (data[1] < level && data[0] >= level);
}

bool crossUnder(vars data, var level) {
  return (data[1] > level && data[0] <= level);
}

// Predict returns based on factors
var predictReturn() {
  var predictedReturn = beta0 + betaFactor * FactorExposure[0] + betaMktCap * MarketCap[0] + betaIndustry * IndustryData[0];
  return predictedReturn;
}

void run() {
  if(is(INITRUN)) {
    init();
  }

  calculateGaussianFilter(PriceClose, 4, 144);
  
  bool longCondition = crossOver(priceClose(), hband) && predictReturn() > 0;
  bool closeAllCondition = crossUnder(priceClose(), hband) || predictReturn() < 0;

  if (longCondition) {
    enterLong();
  }

  if (closeAllCondition) {
    exitLong();
  }
}

Last edited by TipmyPip; 07/06/24 15:58.
Gaussian Bands Strategy [Re: TipmyPip] #488293
07/06/24 17:16
07/06/24 17:16
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
Here is another version for the Gaussian Filter Strategy, while it can be considered non-linear under multi-correlation factors of overlapping data :


Code
#include <default.c>

// Variables
var alpha, beta;
var filt, filttr, hband, lband;
vars PriceClose, GaussianFiltered, GaussianFilteredTR;
vars UpperBand, LowerBand;

// Initialization
void init() {
  BarPeriod = 60; // 1-hour bars
  LookBack = 144; // Lookback period for the Gaussian filter

  PriceClose = series(priceClose());
  GaussianFiltered = series(0);
  GaussianFilteredTR = series(0);
  UpperBand = series(0);
  LowerBand = series(0);

  alpha = calculateAlpha(144, 4); // Sampling Period and Poles
  beta = (1 - cos(2 * PI / 144)) / (pow(1.414, 2 / 4) - 1);
}

// Calculate Alpha
var calculateAlpha(int period, int poles) {
  var beta = (1 - cos(2 * PI / period)) / (pow(1.414, 2 / poles) - 1);
  return -beta + sqrt(beta * beta + 2 * beta);
}

// Modified Gaussian Filter with Bands
var filt9x_with_bands(var a, var s, int poles, var deviationMultiplier, var* upperBand, var* lowerBand) {
  static vars f[10]; // Array to store previous filter values
  var x = 1 - a;
  var filt = s * a;

  // Precompute powers of x to avoid redundant calculations
  var x2 = x * x;
  var x3 = x2 * x;
  var x4 = x3 * x;
  var x5 = x4 * x;
  var x6 = x5 * x;
  var x7 = x6 * x;
  var x8 = x7 * x;
  var x9 = x8 * x;

  // Calculate the filter value iteratively
  for (int i = 1; i <= poles; i++) {
    switch (i) {
      case 1:
        filt += x * f[i];
        break;
      case 2:
        filt -= 36 * x2 * f[i];
        break;
      case 3:
        filt += 84 * x3 * f[i];
        break;
      case 4:
        filt -= 126 * x4 * f[i];
        break;
      case 5:
        filt += 126 * x5 * f[i];
        break;
      case 6:
        filt -= 84 * x6 * f[i];
        break;
      case 7:
        filt += 36 * x7 * f[i];
        break;
      case 8:
        filt -= 9 * x8 * f[i];
        break;
      case 9:
        filt += x9 * f[i];
        break;
    }
  }

  // Shift the previous values in the array
  for (int j = 9; j > 0; j--) {
    f[j] = f[j - 1];
  }
  f[0] = filt;

  // Calculate standard deviation of filter values
  var sum = 0, mean = 0, count = 10;
  for (int j = 0; j < count; j++) {
    sum += f[j];
  }
  mean = sum / count;

  var varianceSum = 0;
  for (int j = 0; j < count; j++) {
    varianceSum += (f[j] - mean) * (f[j] - mean);
  }
  var stddev = sqrt(varianceSum / count);

  // Calculate upper and lower bands
  *upperBand = filt + deviationMultiplier * stddev;
  *lowerBand = filt - deviationMultiplier * stddev;

  return filt;
}

// Gaussian Filter Calculation
void calculateGaussianFilter(vars src, int poles, int period) {
  vars filtSeries = series(0);
  vars filtSeriesTR = series(0);
  var lag = (period - 1) / (2 * poles);
  vars srcData = series(0);
  vars trData = series(0);
  
  for(int i = 0; i < Bar; i++) {
    if(i > lag) {
      srcData[i] = src[i] + (src[i] - src[i - lag]);
      trData[i] = TR() + (TR() - TR(lag));
    } else {
      srcData[i] = src[i];
      trData[i] = TR();
    }
  }
  
  for(int i = 0; i < Bar; i++) {
    var upper, lower;
    filtSeries[i] = filt9x_with_bands(alpha, srcData[i], poles, 1.414, &upper, &lower);
    filtSeriesTR[i] = filt9x_with_bands(alpha, trData[i], poles, 1.414, &upper, &lower);
    UpperBand[i] = upper;
    LowerBand[i] = lower;
  }
  
  GaussianFiltered[0] = filtSeries[0];
  GaussianFilteredTR[0] = filtSeriesTR[0];
  
  hband = UpperBand[0];
  lband = LowerBand[0];
}

// CrossOver and CrossUnder Functions
bool crossOver(vars data, var level) {
  return (data[1] < level && data[0] >= level);
}

bool crossUnder(vars data, var level) {
  return (data[1] > level && data[0] <= level);
}

// Main Trading Logic
void run() {
  if(is(INITRUN)) {
    init();
  }

  calculateGaussianFilter(PriceClose, 4, 144);
  
  bool longCondition = crossOver(priceClose(), hband);
  bool closeAllCondition = crossUnder(priceClose(), lband);

  if (longCondition) {
    enterLong();
  }

  if (closeAllCondition) {
    exitLong();
  }
}

Gaussian Decision Tree Hedging Strategy [Re: TipmyPip] #488305
07/11/24 05:43
07/11/24 05:43
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
This trading strategy leverages advanced signal processing and machine learning techniques to make informed trading decisions. We employ a Gaussian filter, which smooths the price series by reducing noise, and derive key indicators from it. These indicators include the filtered price and its bands, calculated by a non-recursive method. The signals are generated by comparing the filtered price to its bands, and identifying potential entry and exit points.

To enhance decision-making, we integrate a decision tree algorithm. This machine learning model is trained on historical signals, capturing complex patterns and relationships in the data. The model predicts future price movements, guiding long and short positions. By combining signal processing with machine learning, the strategy aims to exploit market inefficiencies and improve trading performance.

Code
#include <default.c>

// Variables
var alpha, beta;
var filt, filttr, hband, lband;
vars PriceClose, GaussianFiltered, GaussianFilteredTR;
vars UpperBand, LowerBand;

// Initialization
void init() {
    BarPeriod = 60; // 1-hour bars
    LookBack = 150; // Lookback period for the Gaussian filter

    PriceClose = series(priceClose());
    GaussianFiltered = series(0);
    GaussianFilteredTR = series(0);
    UpperBand = series(0);
    LowerBand = series(0);

    alpha = calculateAlpha(144, 4); // Sampling Period and Poles
    beta = (1 - cos(2 * PI / 144)) / (pow(1.414, 2 / 4) - 1);

    adviseLong(DTREE, 0, NULL, 0); // Initialize the Decision Tree model
}

// Calculate Alpha
var calculateAlpha(int period, int poles) {
    var beta = (1 - cos(2 * PI / period)) / (pow(1.414, 2 / poles) - 1);
    return -beta + sqrt(beta * beta + 2 * beta);
}

// Modified Gaussian Filter with Bands
var filt9x_with_bands(var a, var s, int poles, var deviationMultiplier, var* upperBand, var* lowerBand) {
    static vars f[10]; // Array to store previous filter values
    var x = 1 - a;
    var filt = s * a;

    // Precompute powers of x to avoid redundant calculations
    var x2 = x * x;
    var x3 = x2 * x;
    var x4 = x3 * x;
    var x5 = x4 * x;
    var x6 = x5 * x;
    var x7 = x6 * x;
    var x8 = x7 * x;
    var x9 = x8 * x;

    // Calculate the filter value iteratively
    for (int i = 1; i <= poles; i++) {
        switch (i) {
            case 1:
                filt += x * f[i];
                break;
            case 2:
                filt -= 36 * x2 * f[i];
                break;
            case 3:
                filt += 84 * x3 * f[i];
                break;
            case 4:
                filt -= 126 * x4 * f[i];
                break;
            case 5:
                filt += 126 * x5 * f[i];
                break;
            case 6:
                filt -= 84 * x6 * f[i];
                break;
            case 7:
                filt += 36 * x7 * f[i];
                break;
            case 8:
                filt -= 9 * x8 * f[i];
                break;
            case 9:
                filt += x9 * f[i];
                break;
        }
    }

    // Shift the previous values in the array
    for (int j = 9; j > 0; j--) {
        f[j] = f[j - 1];
    }
    f[0] = filt;

    // Calculate standard deviation of filter values
    var sum = 0, mean = 0, count = 10;
    for (int j = 0; j < count; j++) {
        sum += f[j];
    }
    mean = sum / count;

    var varianceSum = 0;
    for (int j = 0; j < count; j++) {
        varianceSum += (f[j] - mean) * (f[j] - mean);
    }
    var stddev = sqrt(varianceSum / count);

    // Calculate upper and lower bands
    *upperBand = filt + deviationMultiplier * stddev;
    *lowerBand = filt - deviationMultiplier * stddev;

    return filt;
}

// Gaussian Filter Calculation
void calculateGaussianFilter(vars src, int poles, int period) {
    vars filtSeries = series(0);
    vars filtSeriesTR = series(0);
    var lag = (period - 1) / (2 * poles);
    vars srcData = series(0);
    vars trData = series(0);
    
    for (int i = 0; i < Bar; i++) {
        if (i > lag) {
            srcData[i] = src[i] + (src[i] - src[i - lag]);
            trData[i] = TR() + (TR() - TR(lag));
        } else {
            srcData[i] = src[i];
            trData[i] = TR();
        }
    }
    
    for (int i = 0; i < Bar; i++) {
        var upper, lower;
        filtSeries[i] = filt9x_with_bands(alpha, srcData[i], poles, 1.414, &upper, &lower);
        filtSeriesTR[i] = filt9x_with_bands(alpha, trData[i], poles, 1.414, &upper, &lower);
        UpperBand[i] = upper;
        LowerBand[i] = lower;
    }
    
    GaussianFiltered[0] = filtSeries[0];
    GaussianFilteredTR[0] = filtSeriesTR[0];
    
    hband = UpperBand[0];
    lband = LowerBand[0];
}

// Main Trading Logic
void run() {
    BarPeriod = 60; // 1-hour bars
    LookBack = 150; // Lookback period
    TradesPerBar = 2;

    if (Train) {
        Hedge = 2; // Hedge during training
    }

    set(RULES | TESTNOW); // Set rules and test mode

    if (is(INITRUN)) {
        init();
    }

    calculateGaussianFilter(PriceClose, 4, 144);

    // Generate some signals from GaussianFiltered in the -100..100 range
    var Signals[2]; 
    Signals[0] = (GaussianFiltered[0] - GaussianFilteredTR[0]) / PIP;
    Signals[1] = 100 * FisherN(priceClose(), 100);

    // Train and trade the signals using the decision tree model
    if (adviseLong(DTREE, 0, Signals, 2) > 0)
        enterLong();
    if (adviseShort(DTREE, 0, Signals, 2) > 0)
        enterShort();
}

Last edited by TipmyPip; 07/11/24 05:45.
Gaussian-Enhanced Hybrid Ensemble Strategy [Re: TipmyPip] #488318
07/20/24 05:00
07/20/24 05:00
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
The following is an optimized version of the Gaussian Filter Strategy, which includes Decision Trees, and Neural Networks to monitor error correction within the signals.

This code combines decision trees and neural networks to enhance previous versions of the implementation. It initializes and trains both models, uses Gaussian filters for signal processing, and employs a meta-model neural network to integrate their predictions for final trading actions, aiming to reduce errors and improve trading performance in a systematic, data-driven manner.

Code
#include <default.c>

// Variables
var alpha, beta;
var filt, filttr, hband, lband;
vars PriceClose, GaussianFiltered, GaussianFilteredTR;
vars UpperBand, LowerBand;
var Signals[2];
var MetaSignals[2]; // Signals for the meta-model

// Initialization
void init() {
    BarPeriod = 60; // 1-hour bars
    LookBack = 150; // Lookback period for the Gaussian filter

    PriceClose = series(priceClose());
    GaussianFiltered = series(0);
    GaussianFilteredTR = series(0);
    UpperBand = series(0);
    LowerBand = series(0);

    alpha = calculateAlpha(144, 4); // Sampling Period and Poles
    beta = (1 - cos(2 * PI / 144)) / (pow(1.414, 2 / 4) - 1);

    adviseLong(DTREE, 0, NULL, 0); // Initialize the Decision Tree model
    adviseLong(NN, 0, NULL, 0); // Initialize the Neural Network model
    adviseLong(NN, 1, NULL, 0); // Initialize the Meta-Model Neural Network
}

// Calculate Alpha
var calculateAlpha(int period, int poles) {
    var beta = (1 - cos(2 * PI / period)) / (pow(1.414, 2 / poles) - 1);
    return -beta + sqrt(beta * beta + 2 * beta);
}

// Optimized Gaussian Filter with Bands
var filt9x_with_bands(var a, var s, int poles, var deviationMultiplier, var* upperBand, var* lowerBand) {
    static vars f[10]; // Array to store previous filter values
    var x = 1 - a;
    var filt = s * a;

    // Precompute powers of x to avoid redundant calculations
    var x_powers[10];
    x_powers[1] = x;
    for (int i = 2; i <= 9; i++) {
        x_powers[i] = x_powers[i - 1] * x;
    }

    // Calculate the filter value iteratively
    var coefficients[10] = {0, 1, -36, 84, -126, 126, -84, 36, -9, 1};
    for (int i = 1; i <= poles; i++) {
        filt += coefficients[i] * x_powers[i] * f[i];
    }

    // Shift the previous values in the array
    for (int j = 9; j > 0; j--) {
        f[j] = f[j - 1];
    }
    f[0] = filt;

    // Calculate mean and variance in a single pass
    var sum = 0, varianceSum = 0, count = 10;
    for (int j = 0; j < count; j++) {
        sum += f[j];
    }
    var mean = sum / count;

    for (int j = 0; j < count; j++) {
        varianceSum += (f[j] - mean) * (f[j] - mean);
    }
    var stddev = sqrt(varianceSum / count);

    // Calculate upper and lower bands
    *upperBand = filt + deviationMultiplier * stddev;
    *lowerBand = filt - deviationMultiplier * stddev;

    return filt;
}

// Gaussian Filter Calculation
void calculateGaussianFilter(vars src, int poles, int period) {
    vars filtSeries = series(0);
    vars filtSeriesTR = series(0);
    var lag = (period - 1) / (2 * poles);
    vars srcData = series(0);
    vars trData = series(0);
    
    for (int i = 0; i < Bar; i++) {
        if (i > lag) {
            srcData[i] = src[i] + (src[i] - src[i - lag]);
            trData[i] = TR() + (TR() - TR(lag));
        } else {
            srcData[i] = src[i];
            trData[i] = TR();
        }
    }
    
    for (int i = 0; i < Bar; i++) {
        var upper, lower;
        filtSeries[i] = filt9x_with_bands(alpha, srcData[i], poles, 1.414, &upper, &lower);
        filtSeriesTR[i] = filt9x_with_bands(alpha, trData[i], poles, 1.414, &upper, &lower);
        UpperBand[i] = upper;
        LowerBand[i] = lower;
    }
    
    GaussianFiltered[0] = filtSeries[0];
    GaussianFilteredTR[0] = filtSeriesTR[0];
    
    hband = UpperBand[0];
    lband = LowerBand[0];
}

// Meta-Model for Combining Predictions using Neural Network
var metaModel(var dtreePrediction, var nnPrediction) {
    MetaSignals[0] = dtreePrediction;
    MetaSignals[1] = nnPrediction;
    return advise(NN, 1, MetaSignals, 2); // Use another neural network (NN) model as meta-model
}

// Main Trading Logic
void run() {
    BarPeriod = 60; // 1-hour bars
    LookBack = 150; // Lookback period
    TradesPerBar = 2;

    if (Train) {
        Hedge = 2; // Hedge during training
    }

    set(RULES | TESTNOW); // Set rules and test mode

    if (is(INITRUN)) {
        init();
    }

    calculateGaussianFilter(PriceClose, 4, 144);

    // Generate some signals from GaussianFiltered in the -100..100 range
    Signals[0] = (GaussianFiltered[0] - GaussianFilteredTR[0]) / PIP;
    Signals[1] = 100 * FisherN(priceClose(), 100);

    // Train and trade the signals using decision tree and neural network models
    var dtreePrediction = advise(DTREE, 0, Signals, 2);
    var nnPrediction = advise(NN, 0, Signals, 2);

    var finalDecision = metaModel(dtreePrediction, nnPrediction);
    
    if (finalDecision > 0)
        enterLong();
    else if (finalDecision < 0)
        enterShort();
    else {
        if (isLong()) exitLong();
        if (isShort()) exitShort();
    }
}

Re: Gaussian-Enhanced Hybrid Ensemble Strategy [Re: TipmyPip] #488319
07/20/24 06:46
07/20/24 06:46
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
I must confess, my fascination with automation knows no bounds. While resolving coding problems can be a daunting task, the correct implementation of automation can significantly simplify much of this work.

Imagine the incredible efficiency we could achieve by quickly resolving problems and eliminating the need for error corrections in our code. This would not only save us time but also enrich our lives by allowing us to focus on more creative and fulfilling pursuits.

It's true that addressing errors in automated code generation can be a slow process. However, developing and debugging code manually without automation demands just as much effort and time.

My enthusiasm for automation is matched by my eagerness to share its benefits with others. Please forgive my insistence, but I wholeheartedly encourage you to embrace automation as I have. Together, we can transform our manual trading tasks into streamlined, automated solutions. :-) Hahahah!

I surely, will need to many errors, in my code, But if anyone, feels like sharing any solutions, or ideas, please do.

Last edited by TipmyPip; 07/22/24 19:04.
Re: Gaussian-Enhanced Hybrid Ensemble Strategy [Re: TipmyPip] #488397
10/01/24 10:42
10/01/24 10:42
Joined: Dec 2016
Posts: 74
F
firecrest Offline
Junior Member
firecrest  Offline
Junior Member
F

Joined: Dec 2016
Posts: 74
Thanks @TipmyPip, Is there any simple code that makes consistent money? Even annual return of 10% is great.

Re: Gaussian-Enhanced Hybrid Ensemble Strategy [Re: firecrest] #488399
10/04/24 19:33
10/04/24 19:33
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
Well, that is what you need to work on, and simple code doesn't exist for 10%, you need to use, test, and retest.

Re: Gaussian-Enhanced Hybrid Ensemble Strategy [Re: TipmyPip] #488428
11/07/24 07:53
11/07/24 07:53
Joined: Dec 2016
Posts: 74
F
firecrest Offline
Junior Member
firecrest  Offline
Junior Member
F

Joined: Dec 2016
Posts: 74
I was wondering if there are any codes can beat buy and hold of SPY well. Thanks for the input and i will test it out.

Re: Gaussian-Enhanced Hybrid Ensemble Strategy [Re: firecrest] #488429
11/09/24 16:42
11/09/24 16:42
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
Let me give you an example of answers from ZorroGPT:

Train the PyTorch Model Separately
First, you’ll use PyTorch to train your DRL model based on historical data. After training, save the model so Zorro can use it for predictions.

Code
import torch
from torch import nn, optim

# Example DRL Model (Adjust according to your architecture)
class TradingModel(nn.Module):
    def __init__(self):
        super(TradingModel, self).__init__()
        self.fc1 = nn.Linear(NumSignals, Neurons)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(Neurons, 1)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        x = self.relu(self.fc1(x))
        x = self.sigmoid(self.fc2(x))
        return x

# Training function
def train_model(data_path, model_save_path):
    data = np.loadtxt(data_path, delimiter=',')  # Load data from CSV
    X, y = data[:, :-1], data[:, -1]
    X = torch.tensor(X, dtype=torch.float32)
    y = torch.tensor(y, dtype=torch.float32).view(-1, 1)

    model = TradingModel()
    criterion = nn.BCELoss()
    optimizer = optim.Adam(model.parameters(), lr=Rate)

    for epoch in range(Epochs):
        optimizer.zero_grad()
        predictions = model(X)
        loss = criterion(predictions, y)
        loss.backward()
        optimizer.step()

    # Save model for use in Zorro
    torch.save(model.state_dict(), model_save_path)


Train the model on your historical data and save it:

Code
train_model("Data/Signals.csv", "model.pth")


2. Load and Use the Model in Zorro is possible but with different code:
Since Zorro cannot directly run PyTorch, you’ll need to create a separate Python script (e.g., predict.py) that:

Loads the trained model.
Receives data from Zorro for predictions.
Outputs the prediction results back to Zorro.

Code
import torch
import numpy as np
from TradingModel import TradingModel  # Import your model class

# Initialize model
model = TradingModel()
model.load_state_dict(torch.load("model.pth"))  # Load saved model
model.eval()  # Set model to evaluation mode

def predict(input_data):
    input_tensor = torch.tensor(input_data, dtype=torch.float32)
    with torch.no_grad():
        prediction = model(input_tensor)
    return prediction.item()

# Example usage for testing
# Replace [0.5, 1.2, -0.7, ...] with real data passed from Zorro
print(predict([0.5, 1.2, -0.7, ...]))  # Output a prediction for testing


3. Integrate Prediction with Zorro in lite-C Code
In your Zorro script, the neural function will send input data to predict.py, retrieve the prediction result, and make trading decisions based on this prediction.
To link Zorro with Python, you’ll use Zorro’s Rx() function to run the predict.py script and get the result back.

Code
function run()
{
    vars InputData = series(priceClose());
    double Data[NumSignals];
    for(int i = 0; i < NumSignals; i++)
        Data[i] = InputData[i];  // Gather recent data for model input

    // Save input data to CSV format expected by predict.py
    file_write("Data\\input_data.csv", Data, 0);

    // Call Python predict script and retrieve prediction
    Rx("Y <- predict('Data/input_data.csv')");
    var prediction = Rd("Y[1]"); // Assuming Y[1] holds the prediction result

    // Based on prediction, send buy or sell order
    if(prediction > 0.5)
        enterLong();  // Buy if prediction is above 0.5 threshold
    else
        enterShort(); // Sell if prediction is 0.5 or below
}


Now, there might be some errors, which you will need to ask ZorroGPT how do resolve them, let me assure you that it took me at least 40-80 exchanges of error handling to create the Gaussian Band indicator, of which I am still not sure the values are working properly in all time frames.

Last edited by TipmyPip; 11/09/24 16:47.
PyTorch DRL with ZorroGPT [Re: TipmyPip] #488430
11/09/24 16:52
11/09/24 16:52
Joined: Sep 2017
Posts: 147
T
TipmyPip Offline OP
Member
TipmyPip  Offline OP
Member
T

Joined: Sep 2017
Posts: 147
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:

Code
pip3 install torch numpy math


Open Zorro.ini and set the PythonPath64 variable to the path of your Python installation. For example:

Code
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.

Code
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.

Code
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.

Last edited by TipmyPip; 11/09/24 16:54.
Page 4 of 9 1 2 3 4 5 6 7 8 9

Moderated by  Petra 

Powered by UBB.threads™ PHP Forum Software 7.7.1