MyIntelligenceAgency / Lean

Lean Algorithmic Trading Engine by QuantConnect (C#, Python, F#)
https://lean.io
Apache License 2.0
0 stars 33 forks source link

Request final #33

Closed mnavaratnam closed 8 months ago

mnavaratnam commented 8 months ago

Description

Related Issue

Motivation and Context

Requires Documentation Change

How Has This Been Tested?

Types of changes

Checklist:

mnavaratnam commented 8 months ago

Bonjour Monsieur,

Le code a été poussé il y a quelques jours, mais nous avons décidé de ne pas inclure la version finale que nous avons modifiée hier. En effet, des erreurs persistent et empêchent une compilation réussie. Nous avons pris soin de commenter les parties ajoutées et de signaler l'apparition des erreurs. Nous vous remercions de prendre en considération ces ajustements. Nous regrettons les désagréments occasionnés et apprécions votre compréhension. Capture d'écran 2023-12-22 082015 Capture d'écran 2023-12-22 082202

jsboige commented 8 months ago

Bonjour, je n'ai pas compris cette PR où vous avez cassé votre algorithme en remplaçant la méthode Initialize par OnData qui n'a rien à voir. J'ai remis la méthode Initialize pour qu'il s'exécute, mais il ne trade pas.

mnavaratnam commented 8 months ago

Bonjour Monsieur, l'erreur est apparu qu'hier alors qu'il tradait avant. Je vous joins le code quand ca fonctionner.Le code (mais y a toujours le même problème : /*

using QuantConnect.Algorithm.Framework.Alphas; using QuantConnect.Algorithm.Framework.Execution; using QuantConnect.Algorithm.Framework.Portfolio; using QuantConnect.Algorithm.Framework.Risk; using QuantConnect.Algorithm.Framework.Selection; using QuantConnect.Data; using QuantConnect.Data.UniverseSelection; using QuantConnect.Indicators; using QuantConnect.Orders.Fees; using System; using System.Collections.Generic; using System.Linq;

namespace QuantConnect.Algorithm.CSharp.Alphas { ///

/// This alpha aims to capture the mean-reversion effect of ETFs during lunch-break by ranking 20 ETFs /// on their return between the close of the previous day to 12:00 the day after and predicting mean-reversion /// in price during lunch-break. /// /// Source: Lunina, V. (June 2011). The Intraday Dynamics of Stock Returns and Trading Activity: Evidence from OMXS 30 (Master's Essay, Lund University). /// Retrieved from http://lup.lub.lu.se/luur/download?func=downloadFile&recordOId=1973850&fileOId=1973852 /// /// This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open sourced so the community and client funds can see an example of an alpha. /// public class MeanReversionLunchBreakAlpha : QCAlgorithm {

    public override void Initialize()
    {
        SetStartDate(2018, 1, 1);
        // SetEndDate(2020, 1, 1);
        SetCash(2000000);

        AddEquity("SPY");
        AddEquity("AAPL");
        AddEquity("GOOG");
        AddEquity("CAC40");

        // Ajouter du Bitcoin
        //AddCrypto("BTCUSD");  // BTCUSD est le symbole du Bitcoin (il peut y avoir des symboles différents selon la source)
        //AddData<Bitcoin>("BTC");
        // Répartition égale entre les actifs
        var spySymbol = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA);
        var aaplSymbol = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
        var googSymbol = QuantConnect.Symbol.Create("GOOG", SecurityType.Equity, Market.USA);
        var cac40Symbol = QuantConnect.Symbol.Create("CAC40", SecurityType.Equity, Market.USA);
        //var btcSymbol = QuantConnect.Symbol.Create("BTCUSD", SecurityType.Crypto, Market.USA);

        SetHoldings(spySymbol, 1.0 / 4);  // 2 millions * 1/5
        SetHoldings(aaplSymbol, 1.0 / 4);  // 2 millions * 1/5
        SetHoldings(googSymbol, 1.0 / 4);  // 2 millions * 1/5
        SetHoldings(cac40Symbol, 1.0 / 4);  // 2 millions * 1/5
       // SetHoldings(btcSymbol, 1.0 / 5);  // 2 millions * 1/5

        // Set zero transaction fees
        SetSecurityInitializer(security => security.FeeModel = new ConstantFeeModel(0));

        // Utilisez les données horaires pour la simplicité
        UniverseSettings.Resolution = Resolution.Daily;

        // Utilisez MeanReversionLunchBreakAlphaModel pour établir des prévisions
        SetAlpha(new MeanReversionLunchBreakAlphaModel());

        // Pesez également les actifs dans le portefeuille, basé sur les prévisions
        SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());

        // Modèle d'exécution immédiate
        SetExecution(new ImmediateExecutionModel());

        // Modèle de gestion des risques nul
        SetRiskManagement(new NullRiskManagementModel());
        SetWarmup(TimeSpan.FromDays(30)); // or adjust the number of days as needed

    }

    /// <summary>
    /// Uses the price return between the close of previous day to 12:00 the day after to
    /// predict mean-reversion of stock price during lunch break and creates direction prediction
    /// for insights accordingly.
    /// </summary>
    private class MeanReversionLunchBreakAlphaModel : AlphaModel
    {
        private const Resolution _resolution = Resolution.Hour;
        private readonly TimeSpan _predictionInterval;
        private readonly Dictionary<Symbol, SymbolData> _symbolDataBySymbol;

        public MeanReversionLunchBreakAlphaModel(int lookback = 1)
        {
            _predictionInterval = _resolution.ToTimeSpan().Multiply(lookback);
            _symbolDataBySymbol = new Dictionary<Symbol, SymbolData>();
        }

        /*     public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data)
             {
                 foreach (var kvp in _symbolDataBySymbol)
                 {
                     if (data.Bars.ContainsKey(kvp.Key))
                     {
                         var bar = data.Bars.GetValue(kvp.Key);
                         kvp.Value.Update(bar.EndTime, bar.Close);
                     }
                 }

                 return algorithm.Time.Hour == 12
                     ? _symbolDataBySymbol.Select(kvp => kvp.Value.Insight)
                     : Enumerable.Empty<Insight>();
             }*/
        public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data)
        {
            foreach (var kvp in _symbolDataBySymbol)
            {
                if (data.ContainsKey(kvp.Key) && data[kvp.Key] != null && data[kvp.Key].Bars.Count > 0)
                {
                    var bar = data.Bars.GetValue(kvp.Key);

                    // Display the price of the security in the debug console
                    algorithm.Debug($"Price of {kvp.Key}: {bar.Close}");

                    kvp.Value.Update(bar.EndTime, bar.Close);
                }
            }

            return algorithm.Time.Hour == 12
                ? _symbolDataBySymbol.Select(kvp => kvp.Value.Insight)
                : Enumerable.Empty<Insight>();
        }

        public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
        {
            foreach (var security in changes.RemovedSecurities)
            {
                if (_symbolDataBySymbol.ContainsKey(security.Symbol))
                {
                    _symbolDataBySymbol.Remove(security.Symbol);
                }
            }

            // Retrieve price history for all securities in the security universe
            // and update the indicators in the SymbolData object
            var symbols = changes.AddedSecurities.Select(x => x.Symbol);
            var history = algorithm.History(symbols, 1, _resolution);
            if (symbols.Count() > 0 && history.Count() == 0)
            {
                algorithm.Debug($"No data on {algorithm.Time}");
            }

            history.PushThrough(bar =>
            {
                SymbolData symbolData;
                if (!_symbolDataBySymbol.TryGetValue(bar.Symbol, out symbolData))
                {
                    symbolData = new SymbolData(bar.Symbol, _predictionInterval);
                }
                symbolData.Update(bar.EndTime, bar.Price);
                _symbolDataBySymbol[bar.Symbol] = symbolData;
            });
        }

        /// <summary>
        /// Contains data specific to a symbol required by this model
        /// </summary>
        private class SymbolData
        {
            // Mean value of returns for magnitude prediction
            private readonly SimpleMovingAverage _meanOfPriceChange = new RateOfChangePercent(1).SMA(3);
            // Price change from close price the previous day
            private readonly RateOfChangePercent _priceChange = new RateOfChangePercent(3);

            private readonly Symbol _symbol;
            private readonly TimeSpan _period;

            public Insight Insight
            {
                get
                {
                    // Emit "down" insight for the securities that increased in value and
                    // emit "up" insight for securities that have decreased in value
                    var direction = _priceChange.Current.Value > 0 ? InsightDirection.Down : InsightDirection.Up;

                    var magnitude = Convert.ToDouble(Math.Abs(_meanOfPriceChange));
                    return Insight.Price(_symbol, _period, direction, magnitude);
                }
            }

            public SymbolData(Symbol symbol, TimeSpan period)
            {
                _symbol = symbol;
                _period = period;
            }

            public bool Update(DateTime time, decimal value)
            {
                return _meanOfPriceChange.Update(time, value) &
                    _priceChange.Update(time, value);
            }
        }
    }
}

}