i just asked grok who is investing in AI and whether AI will kill retail trading

Discussion in 'Artificial Intelligence' started by mute9003, May 26, 2025 at 11:42 AM.

  1. Dismiss Notice
  1. spy

    spy

    This just looks like a case of backtest overfitting. Did it say what the actual strategy is or are we just going with some painfully naive momentum play?
     
  2. MarkBrown

    MarkBrown

    i told it make it reversion to the mean only and use derivatives of velocity and make the trade frequency 2-10 days in duration.
     
    spy likes this.
  3. danielc1

    danielc1

    everything changes and nothing has changed: AI is the new moving average of our time in history, just with more parameters and just as lagging... unless... you know what good trading looks like, then it will give you leverage.
     
  4. spy

    spy

    Can it spit out a working implementation?
     
    MarkBrown likes this.
  5. By 50 years AI and power will be greatly consolidated. And a Universal Basic Income will be required. In 100 years or 200 years there'll essentially be a one world government, and one world currency. Bright future. The world will be an ant or bee colony with one Queen
     
  6. spy

    spy

    Can it format the code and place it in the proper tags so it renders nicely when browsing ET? Lol

    ;)
     
    HawaiianIceberg and MarkBrown like this.
  7. MarkBrown

    MarkBrown

    Code:
    written in C#
    
    
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using PowerLanguage.Function;
    
    namespace PowerLanguage.Strategy
    {
    [IOGMode(IOGMode.Enabled)]
    public class ctest1 : SignalObject
    {
    #region Strategy Parameters
    
    [Input]
    public int LookbackWindow { get; set; }
    
    [Input]
    public double SignalThreshold { get; set; }
    
    [Input]
    public int PositionSize { get; set; }
    
    [Input]
    public double TransactionCost { get; set; }
    
    [Input]
    public double RiskFactor { get; set; }
    
    [Input]
    public bool EnableQuantum { get; set; }
    
    [Input]
    public bool EnableBacterial { get; set; }
    
    [Input]
    public bool EnableFractional { get; set; }
    
    #endregion
    
    #region Private Variables
    
    private List<double> priceHistory;
    private List<double> signalHistory;
    private List<double> velocityHistory;
    private List<double> accelerationHistory;
    private List<double> jerkHistory;
    private List<double> snapHistory;
    
    private double currentCompositeSignal;
    private double previousCompositeSignal;
    private int currentPosition;
    
    // Performance tracking
    private double totalPnL;
    private double maxDrawdown;
    private double peakEquity;
    private int totalTrades;
    private int winningTrades;
    
    // Risk management
    private double shortTermVol;
    private double longTermVol;
    private double currentDrawdown;
    
    // Orders interface - separate entry and exit orders for frequent trading
    private IOrderMarket m_BuyOrder;
    private IOrderMarket m_SellOrder;
    private IOrderMarket m_ExitLongOrder;
    private IOrderMarket m_ExitShortOrder;
    
    // Position tracking for frequent trading
    private int barsInPosition;
    private int maxHoldingPeriod;
    private int minHoldingPeriod;
    
    #endregion
    
    #region Constructor
    
    public ctest1(object _ctx) : base(_ctx)
    {
    // AGGRESSIVE SETTINGS FOR GUARANTEED LONG/SHORT TRADES
    LookbackWindow = 10; // Very short for quick mean reversion
    SignalThreshold = 0.005; // Extremely sensitive threshold
    PositionSize = 1;
    TransactionCost = 0.001;
    RiskFactor = 1.0;
    EnableQuantum = false; // Disable complex signals initially
    EnableBacterial = false; // Use only simple mean reversion
    EnableFractional = false;
    
    // Trading frequency controls
    maxHoldingPeriod = 12; // Shorter holding period
    minHoldingPeriod = 3; // Shorter minimum hold
    }
    
    #endregion
    
    #region Initialization
    
    protected override void Create()
    {
    // Initialize collections
    priceHistory = new List<double>();
    signalHistory = new List<double>();
    velocityHistory = new List<double>();
    accelerationHistory = new List<double>();
    jerkHistory = new List<double>();
    snapHistory = new List<double>();
    
    // Initialize variables
    currentCompositeSignal = 0;
    previousCompositeSignal = 0;
    currentPosition = 0;
    totalPnL = 0;
    maxDrawdown = 0;
    peakEquity = 0;
    totalTrades = 0;
    winningTrades = 0;
    
    // Initialize order interface - all 4 order types for active trading
    m_BuyOrder = OrderCreator.MarketNextBar(new SOrderParameters(Contracts.Default, EOrderAction.Buy));
    m_SellOrder = OrderCreator.MarketNextBar(new SOrderParameters(Contracts.Default, EOrderAction.SellShort));
    m_ExitLongOrder = OrderCreator.MarketNextBar(new SOrderParameters(Contracts.Default, EOrderAction.Sell));
    m_ExitShortOrder = OrderCreator.MarketNextBar(new SOrderParameters(Contracts.Default, EOrderAction.BuyToCover));
    
    // Initialize position tracking
    barsInPosition = 0;
    }
    
    #endregion
    
    #region Main Strategy Logic
    
    protected override void CalcBar()
    {
    // Update price history
    UpdatePriceHistory();
    
    // Need minimum bars for calculations - optimized for INTC
    if (priceHistory.Count < 5) // Very low minimum for volatile stock
    return;
    
    // Calculate velocity derivatives
    CalculateVelocityDerivatives();
    
    // Generate composite signal
    currentCompositeSignal = GenerateCompositeSignal();
    
    // Apply risk management
    double riskAdjustedSignal = ApplyRiskManagement(currentCompositeSignal);
    
    // Generate trading decision
    int tradingSignal = GenerateTradingDecision(riskAdjustedSignal);
    
    // Execute trades
    ExecuteTrade(tradingSignal);
    
    // Update performance metrics
    UpdatePerformanceMetrics();
    
    // Store signal for next bar
    previousCompositeSignal = currentCompositeSignal;
    signalHistory.Add(currentCompositeSignal);
    
    // Maintain history size
    MaintainHistorySize();
    
    // Output debug information
    OutputDebugInfo(tradingSignal, riskAdjustedSignal);
    }
    
    #endregion
    
    #region Core Algorithm Components
    
    private void UpdatePriceHistory()
    {
    priceHistory.Add(Bars.Close[0]);
    
    // Maintain maximum history size
    if (priceHistory.Count > LookbackWindow * 2)
    {
    priceHistory.RemoveAt(0);
    }
    }
    
    private void CalculateVelocityDerivatives()
    {
    if (priceHistory.Count < 5) return;
    
    var recentPrices = TakeLast(priceHistory, Math.Min(priceHistory.Count, LookbackWindow));
    
    // Calculate velocity (1st derivative)
    var velocity = CalculateGradient(recentPrices);
    if (velocity.Count > 0)
    velocityHistory.Add(velocity[velocity.Count - 1]);
    
    // Calculate acceleration (2nd derivative)
    if (velocityHistory.Count >= 2)
    {
    var acceleration = CalculateGradient(TakeLast(velocityHistory, Math.Min(velocityHistory.Count, 50)));
    if (acceleration.Count > 0)
    accelerationHistory.Add(acceleration[acceleration.Count - 1]);
    }
    
    // Calculate jerk (3rd derivative)
    if (accelerationHistory.Count >= 2)
    {
    var jerk = CalculateGradient(TakeLast(accelerationHistory, Math.Min(accelerationHistory.Count, 30)));
    if (jerk.Count > 0)
    jerkHistory.Add(jerk[jerk.Count - 1]);
    }
    
    // Calculate snap (4th derivative)
    if (jerkHistory.Count >= 2)
    {
    var snap = CalculateGradient(TakeLast(jerkHistory, Math.Min(jerkHistory.Count, 20)));
    if (snap.Count > 0)
    snapHistory.Add(snap[snap.Count - 1]);
    }
    }
    
    private List<double> CalculateGradient(List<double> data)
    {
    var gradient = new List<double>();
    
    if (data.Count < 2) return gradient;
    
    // Forward difference for first point
    gradient.Add(data[1] - data[0]);
    
    // Central difference for middle points
    for (int i = 1; i < data.Count - 1; i++)
    {
    gradient.Add((data[i + 1] - data[i - 1]) / 2.0);
    }
    
    // Backward difference for last point
    gradient.Add(data[data.Count - 1] - data[data.Count - 2]);
    
    return gradient;
    }
    
    private double GenerateCompositeSignal()
    {
    var recentPrices = TakeLast(priceHistory, Math.Min(priceHistory.Count, LookbackWindow));
    
    if (recentPrices.Count < 5) return 0;
    
    // SIMPLE MEAN REVERSION SIGNAL - This will fix the long/short imbalance
    double currentPrice = recentPrices[recentPrices.Count - 1];
    double meanPrice = Average(recentPrices);
    
    // Primary mean reversion signal:
    // POSITIVE when price > mean (should SHORT)
    // NEGATIVE when price < mean (should LONG)
    double primarySignal = (currentPrice - meanPrice) / meanPrice;
    
    // Scale the signal to make it more sensitive
    primarySignal = primarySignal * 10; // Amplify for better sensitivity
    
    // Debug output to see signal components
    if (Bars.CurrentBar % 5 == 0)
    {
    Output.WriteLine($"SIGNAL DEBUG - Price: {currentPrice:F2}, Mean: {meanPrice:F2}, " +
    $"Primary: {primarySignal:F4}");
    }
    
    return primarySignal;
    }
    
    #endregion
    
    #region Risk Management
    
    private double ApplyRiskManagement(double signal)
    {
    // Minimal risk management for INTC - just pass through the signal
    return signal * RiskFactor;
    }
    
    #endregion
    
    #region Trading Execution
    
    private int GenerateTradingDecision(double riskAdjustedSignal)
    {
    // FORCE EXIT after maximum holding period
    if (currentPosition != 0 && barsInPosition >= maxHoldingPeriod)
    {
    Output.WriteLine($"FORCED EXIT after {barsInPosition} days in position");
    return currentPosition > 0 ? -2 : 2; // Force exit long or short
    }
    
    // FORCE EXIT if signal reverses strongly after minimum hold period
    if (currentPosition != 0 && barsInPosition >= minHoldingPeriod)
    {
    if (currentPosition > 0 && riskAdjustedSignal > SignalThreshold * 2) // Long position, strong sell signal
    {
    Output.WriteLine($"SIGNAL REVERSAL EXIT after {barsInPosition} days - Long to Exit");
    return -2; // Exit long
    }
    if (currentPosition < 0 && riskAdjustedSignal < -SignalThreshold * 2) // Short position, strong buy signal
    {
    Output.WriteLine($"SIGNAL REVERSAL EXIT after {barsInPosition} days - Short to Exit");
    return 2; // Exit short
    }
    }
    
    // NEW ENTRY SIGNALS (only when flat)
    if (currentPosition == 0)
    {
    // MEAN REVERSION LOGIC:
    // Buy when signal is NEGATIVE (price below mean - expect reversion UP)
    // Sell when signal is POSITIVE (price above mean - expect reversion DOWN)
    
    if (riskAdjustedSignal < -SignalThreshold)
    {
    Output.WriteLine($"NEW LONG ENTRY - Price Below Mean, Signal: {riskAdjustedSignal:F4}");
    return 1; // Long entry - buy the dip
    }
    else if (riskAdjustedSignal > SignalThreshold)
    {
    Output.WriteLine($"NEW SHORT ENTRY - Price Above Mean, Signal: {riskAdjustedSignal:F4}");
    return -1; // Short entry - sell the spike
    }
    }
    
    return 0; // Hold current position
    }
    
    private void ExecuteTrade(int tradingSignal)
    {
    // Update bars in position counter
    if (currentPosition != 0)
    {
    barsInPosition++;
    }
    
    // Execute based on trading signal
    switch (tradingSignal)
    {
    case 1: // Buy (Long Entry)
    if (currentPosition <= 0)
    {
    m_BuyOrder.Send();
    currentPosition = 1;
    barsInPosition = 0; // Reset counter
    totalTrades++;
    Output.WriteLine($"*** LONG ENTRY at Bar {Bars.CurrentBar}, Price: {Bars.Close[0]:F2} ***");
    }
    break;
    
    case -1: // Sell Short (Short Entry)
    if (currentPosition >= 0)
    {
    m_SellOrder.Send();
    currentPosition = -1;
    barsInPosition = 0; // Reset counter
    totalTrades++;
    Output.WriteLine($"*** SHORT ENTRY at Bar {Bars.CurrentBar}, Price: {Bars.Close[0]:F2} ***");
    }
    break;
    
    case -2: // Exit Long Position
    if (currentPosition > 0)
    {
    m_ExitLongOrder.Send();
    Output.WriteLine($"*** EXIT LONG at Bar {Bars.CurrentBar}, Price: {Bars.Close[0]:F2}, Held {barsInPosition} days ***");
    currentPosition = 0;
    barsInPosition = 0;
    totalTrades++;
    }
    break;
    
    case 2: // Exit Short Position
    if (currentPosition < 0)
    {
    m_ExitShortOrder.Send();
    Output.WriteLine($"*** EXIT SHORT at Bar {Bars.CurrentBar}, Price: {Bars.Close[0]:F2}, Held {barsInPosition} days ***");
    currentPosition = 0;
    barsInPosition = 0;
    totalTrades++;
    }
    break;
    }
    }
    
    #endregion
    
    #region Performance Tracking
    
    private void UpdatePerformanceMetrics()
    {
    // Basic performance tracking
    if (Bars.CurrentBar > 1)
    {
    double currentPrice = Bars.Close[0];
    double previousPrice = Bars.Close[1];
    
    // Simple equity calculation
    double priceChange = currentPrice - previousPrice;
    
    if (priceChange > peakEquity)
    {
    peakEquity = priceChange;
    }
    
    double drawdown = peakEquity > 0 ? (priceChange - peakEquity) / peakEquity : 0;
    if (drawdown < maxDrawdown)
    {
    maxDrawdown = drawdown;
    }
    }
    }
    
    #endregion
    
    #region Utility Functions
    
    private double CalculateStandardDeviation(List<double> values)
    {
    if (values.Count < 2) return 0;
    
    double mean = Average(values);
    double sumSquares = 0;
    for (int i = 0; i < values.Count; i++)
    {
    sumSquares += Math.Pow(values - mean, 2);
    }
    return Math.Sqrt(sumSquares / (values.Count - 1));
    }
    
    private double Average(List<double> values)
    {
    if (values.Count == 0) return 0;
    
    double sum = 0;
    for (int i = 0; i < values.Count; i++)
    {
    sum += values;
    }
    return sum / values.Count;
    }
    
    private double MaxValue(List<double> values)
    {
    if (values.Count == 0) return 0;
    
    double max = values[0];
    for (int i = 1; i < values.Count; i++)
    {
    if (values > max)
    max = values;
    }
    return max;
    }
    
    private double MinValue(List<double> values)
    {
    if (values.Count == 0) return 0;
    
    double min = values[0];
    for (int i = 1; i < values.Count; i++)
    {
    if (values < min)
    min = values;
    }
    return min;
    }
    
    private List<double> TakeLast(List<double> source, int count)
    {
    if (source.Count <= count)
    return new List<double>(source);
    
    var result = new List<double>();
    for (int i = source.Count - count; i < source.Count; i++)
    {
    result.Add(source);
    }
    return result;
    }
    
    private void MaintainHistorySize()
    {
    const int maxHistorySize = 100; // Reduced size
    
    if (velocityHistory.Count > maxHistorySize)
    velocityHistory.RemoveAt(0);
    
    if (accelerationHistory.Count > maxHistorySize)
    accelerationHistory.RemoveAt(0);
    
    if (jerkHistory.Count > maxHistorySize)
    jerkHistory.RemoveAt(0);
    
    if (snapHistory.Count > maxHistorySize)
    snapHistory.RemoveAt(0);
    
    if (signalHistory.Count > maxHistorySize)
    signalHistory.RemoveAt(0);
    }
    
    private void OutputDebugInfo(int tradingSignal, double riskAdjustedSignal)
    {
    // Output EVERY bar to debug the signal issue
    if (Bars.CurrentBar % 1 == 0) // Every single bar
    {
    string positionStatus = currentPosition > 0 ? $"LONG ({barsInPosition} days)" :
    currentPosition < 0 ? $"SHORT ({barsInPosition} days)" : "FLAT";
    
    double currentPrice = Bars.Close[0];
    double meanPrice = priceHistory.Count > 5 ? Average(TakeLast(priceHistory, Math.Min(LookbackWindow, priceHistory.Count))) : currentPrice;
    string priceVsMean = currentPrice > meanPrice ? "ABOVE" : "BELOW";
    double priceDiff = ((currentPrice - meanPrice) / meanPrice) * 100;
    
    Output.WriteLine($"Bar {Bars.CurrentBar}: Price {currentPrice:F2} ({priceVsMean} mean by {priceDiff:F2}%), " +
    $"Signal {riskAdjustedSignal:F6}, Threshold ±{SignalThreshold:F6}, {GetActionName(tradingSignal)}, {positionStatus}");
    
    // Show exactly what should happen
    if (currentPosition == 0)
    {
    if (riskAdjustedSignal < -SignalThreshold)
    {
    Output.WriteLine($" *** LONG TRIGGER: Signal {riskAdjustedSignal:F6} < -{SignalThreshold:F6} ***");
    }
    else if (riskAdjustedSignal > SignalThreshold)
    {
    Output.WriteLine($" *** SHORT TRIGGER: Signal {riskAdjustedSignal:F6} > {SignalThreshold:F6} ***");
    }
    else
    {
    Output.WriteLine($" No trigger: Signal {riskAdjustedSignal:F6} between ±{SignalThreshold:F6}");
    }
    }
    }
    }
    
    private string GetActionName(int signal)
    {
    switch (signal)
    {
    case 1: return "LONG ENTRY";
    case -1: return "SHORT ENTRY";
    case 2: return "EXIT SHORT";
    case -2: return "EXIT LONG";
    default: return "HOLD";
    }
    }
    
    #endregion
    }
    }
     
    Last edited: May 26, 2025 at 3:52 PM
  8. spy

    spy

    Yep, I know. I meant inserted into the ET comment as a "code block" so that it looks sexy...
    sample.jpg
     
    MarkBrown likes this.
  9. wxytrader

    wxytrader

    Screenshot_20250526-125735.png
     
  10. After all that head banging wizardry merlin analysis programming automation God code...you're happy to generate 3% a year....:confused: That's an Elite level of trading,,
    Downnnn With Thaaaa Brooooown
     
    Last edited: May 26, 2025 at 4:10 PM