Exemplo n.º 1
0
        public override void Initialize()
        {
            SetStartDate(2007, 6, 1);
            SetEndDate(DateTime.Now.Date.AddDays(-1));
            SetCash(10000);

            AddSecurity(SecurityType.Equity, spy, Resolution.Minute);

            foreach (var security in securities)
            {
                AddSecurity(SecurityType.Equity, security, Resolution.Minute);
                Securities[security].SetLeverage(8m);
            }

            Schedule.On(DateRules.Every(DayOfWeek.Tuesday), TimeRules.At(11, 0), () =>
            {
                foreach (var security in hedges.Where(s => Securities[s].Price > 0m))
                {
                    SetHoldings(security, _leverage * 1.06m / (hedges.Where(s => Securities[s].Price > 0m).Count()));
                }

                foreach (var security in riskyAssets.Where(s => Securities[s].Price > 0m))
                {
                    SetHoldings(security, _leverage * 0.27m / (riskyAssets.Where(s => Securities[s].Price > 0m).Count()));
                }
            });
        }
Exemplo n.º 2
0
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            SetStartDate(2013, 10, 07);  //Set Start Date
            SetEndDate(2013, 10, 11);    //Set End Date
            SetCash(100000);             //Set Strategy Cash
            // Find more symbols here: http://quantconnect.com/data
            AddSecurity(SecurityType.Equity, "SPY", Resolution.Minute);

            // events are scheduled using date and time rules
            // date rules specify on what dates and event will fire
            // time rules specify at what time on thos dates the event will fire

            // schedule an event to fire at a specific date/time
            Schedule.On(DateRules.On(2013, 10, 7), TimeRules.At(13, 0), () =>
            {
                Log("SpecificTime: Fired at : " + Time);
            });

            // schedule an event to fire every trading day for a security
            // the time rule here tells it to fire 10 minutes after SPY's market open
            Schedule.On(DateRules.EveryDay("SPY"), TimeRules.AfterMarketOpen("SPY", 10), () =>
            {
                Log("EveryDay.SPY 10 min after open: Fired at: " + Time);
            });

            // schedule an event to fire every trading day for a security
            // the time rule here tells it to fire 10 minutes before SPY's market close
            Schedule.On(DateRules.EveryDay("SPY"), TimeRules.BeforeMarketClose("SPY", 10), () =>
            {
                Log("EveryDay.SPY 10 min before close: Fired at: " + Time);
            });

            // schedule an event to fire on certain days of the week
            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Friday), TimeRules.At(12, 0), () =>
            {
                Log("Mon/Fri at 12pm: Fired at: " + Time);
            });


            // the scheduling methods return the ScheduledEvent object which can be used for other things
            // here I set the event up to check the portfolio value every 10 minutes, and liquidate if we have too many losses
            Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromMinutes(10)), () =>
            {
                // if we have over 1000 dollars in unrealized losses, liquidate
                if (Portfolio.TotalUnrealizedProfit < -1000)
                {
                    Log("Liquidated due to unrealized losses at: " + Time);
                    Liquidate();
                }
            });

            // schedule an event to fire at the beginning of the month, the symbol is optional if
            // specified, it will fire the first trading day for that symbol of the month, if not specified
            // it will fire on the first day of the month
            Schedule.On(DateRules.MonthStart("SPY"), TimeRules.AfterMarketOpen("SPY"), () =>
            {
                // good spot for rebalancing code?
            });
        }
Exemplo n.º 3
0
        public override void Initialize()
        {
            SetStartDate(2013, 10, 07);  //Set Start Date
            SetEndDate(2013, 10, 11);    //Set End Date
            SetCash(2500000);
            SetCash("TRY", 111000, 1);   //Set Strategy Cash
            security = AddSecurity(SecurityType.Equity, BIST_SECURITY_NAME, Resolution.Second);


            Schedule.On(DateRules.On(2016, 05, 11), TimeRules.At(11, 38), () =>
            {
                Log("SpecificTime: Fired at : " + Time);
            });

            // schedule an event to fire every trading day for a security
            // the time rule here tells it to fire 10 minutes after SPY's market open
            Schedule.On(DateRules.EveryDay(BIST_SECURITY_NAME), TimeRules.AfterMarketOpen(BIST_SECURITY_NAME, 10), () =>
            {
                Log("EveryDay.GARAN 10 min after open: Fired at: " + Time);
            });

            // schedule an event to fire every trading day for a security
            // the time rule here tells it to fire 10 minutes before SPY's market close
            Schedule.On(DateRules.EveryDay(BIST_SECURITY_NAME), TimeRules.BeforeMarketClose(BIST_SECURITY_NAME, 10), () =>
            {
                Log("EveryDay.GARAN 10 min before close: Fired at: " + Time);
            });

            // schedule an event to fire on certain days of the week
            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Friday), TimeRules.At(12, 0), () =>
            {
                Log("Mon/Fri at 12pm: Fired at: " + Time);
            });


            // the scheduling methods return the ScheduledEvent object which can be used for other things
            // here I set the event up to check the portfolio value every 10 minutes, and liquidate if we have too many losses
            Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromMinutes(10)), () =>
            {
                Log("EveryDay 10 min Fired at: " + Time);
                // if we have over 1000 dollars in unrealized losses, liquidate
                if (Portfolio.TotalUnrealizedProfit < -1000)
                {
                    Log("Liquidated due to unrealized losses at: " + Time);
                    Liquidate();
                }
            });

            //SetBrokerageModel(BrokerageName.TEB);

            //QuantConnect.Securities.Security sec = AddSecurity(SecurityType.Equity, SECURITY_NAME, Resolution.Second);

            //security.DataFilter = new CustomDataFilter(); //Securities[securityName].DataFilter = new CustomDataFilter();
            //sec.FeeModel = new QuantConnect.Orders.Fees.TEBFeeModel(0);
            //sec.FillModel = new QuantConnect.Orders.Fills.TEBFillModel();
            //sec.MarginModel = new QuantConnect.Securities.TEBSecurityMarginModel(1m);
            //sec.SlippageModel = new QuantConnect.Orders.Slippage.TEBSlippageModel(0m);
        }
        public override void Initialize()
        {
            SetStartDate(2013, 10, 7);
            SetEndDate(2013, 10, 14);

            AddEquity("SPY", Resolution.Daily);

            // Set TrainingMethod to be executed immediately
            Train(TrainingMethod);

            // Set TrainingMethod to be executed at 8:00 am every Sunday
            Train(DateRules.Every(DayOfWeek.Sunday), TimeRules.At(8, 0), TrainingMethod);
        }
Exemplo n.º 5
0
        public override void Initialize()
        {
            SetStartDate(2013, 10, 07);
            SetEndDate(2013, 10, 11);
            SetCash(100000);

            var symbol = AddEquity("SPY").Symbol;

            ROC(symbol, 1, Resolution.Daily).Updated += (s, e) => _window.Add((double)e.Value);

            Schedule.On(DateRules.Every(DayOfWeek.Monday),
                        TimeRules.AfterMarketOpen(symbol, 10),
                        TrainAndTrade);

            SetWarmUp(_window.Size, Resolution.Daily);
        }
        public override void Initialize()
        {
            UniverseSettings.Resolution = Resolution.Hour;

            SetStartDate(2017, 01, 01);
            SetEndDate(2017, 02, 01);

            // selection will run on mon/tues/thurs at 00:00/12:00
            SetUniverseSelection(new ScheduledUniverseSelectionModel(
                                     DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Thursday),
                                     TimeRules.Every(TimeSpan.FromHours(12)),
                                     SelectSymbols
                                     ));

            SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromDays(1)));
            SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            UniverseSettings.Resolution = Resolution.Daily;

            SetStartDate(2015, 1, 1);
            SetEndDate(2017, 1, 1);

            Settings.RebalancePortfolioOnInsightChanges  = false;
            Settings.RebalancePortfolioOnSecurityChanges = false;

            SetUniverseSelection(new CustomUniverseSelectionModel(
                                     "CustomUniverseSelectionModel",
                                     time => new List <string> {
                "AAPL", "IBM", "FB", "SPY"
            }
                                     ));
            SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromMinutes(20), 0.025, null));
            SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel(DateRules.Every(DayOfWeek.Wednesday)));
            SetExecution(new ImmediateExecutionModel());
        }
Exemplo n.º 8
0
        public override void Initialize()
        {
            UniverseSettings.Resolution = Resolution.Hour;

            // Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
            // Commented so regression algorithm is more sensitive
            //Settings.MinimumOrderMarginPortfolioPercentage = 0.005m;

            SetStartDate(2017, 01, 01);
            SetEndDate(2017, 02, 01);

            // selection will run on mon/tues/thurs at 00:00/12:00
            SetUniverseSelection(new ScheduledUniverseSelectionModel(
                                     DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Thursday),
                                     TimeRules.Every(TimeSpan.FromHours(12)),
                                     SelectSymbols
                                     ));

            SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromDays(1)));
            SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
        }
        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            UniverseSettings.Resolution = Resolution.Daily;

            // Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
            // Commented so regression algorithm is more sensitive
            //Settings.MinimumOrderMarginPortfolioPercentage = 0.005m;

            SetStartDate(2015, 1, 1);
            SetEndDate(2017, 1, 1);

            Settings.RebalancePortfolioOnInsightChanges  = false;
            Settings.RebalancePortfolioOnSecurityChanges = false;

            SetUniverseSelection(new CustomUniverseSelectionModel(
                                     "CustomUniverseSelectionModel",
                                     time => new List <string> {
                "AAPL", "IBM", "FB", "SPY"
            }
                                     ));
            SetAlpha(new ConstantAlphaModel(InsightType.Price, InsightDirection.Up, TimeSpan.FromMinutes(20), 0.025, null));
            SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel(DateRules.Every(DayOfWeek.Wednesday)));
            SetExecution(new ImmediateExecutionModel());
        }
Exemplo n.º 10
0
        public override void Initialize()
        {
            SetStartDate(2016, 1, 1);
            SetEndDate(2017, 1, 1);
            SetCash(3000);

            SetBrokerageMessageHandler(new CustomBrokerageMessageHandler(this));

            foreach (var symbol in Symbols)
            {
                AddForex(symbol, _dataResolution, Market.Oanda, false, 1m);

                Securities[symbol].TransactionModel = new OandaTransactionModel();
                //Securities[symbol].SlippageModel = new ConstantSlippageModel(0m);
                SetBrokerageModel(BrokerageName.OandaBrokerage);

                /******** LONG TERM TREND ********/
                var dailyConsolidator = new QuoteBarConsolidator(TimeSpan.FromDays(1));
                var alma = new ExponentialMovingAverage(symbol, 10);

                RegisterIndicator(symbol, alma, dailyConsolidator);
                SubscriptionManager.AddConsolidator(symbol, dailyConsolidator);

                /******** SHORT TERM TRADING ********/
                var consolidator     = new QuoteBarConsolidator(TimeSpan.FromMinutes(15));
                var schaffTrendCycle = new SchaffTrendCycle(symbol);
                var atr = new AverageTrueRange(symbol, 10);
                var adx = new AverageDirectionalIndex(symbol, 10);

                RegisterIndicator(symbol, schaffTrendCycle, consolidator);
                RegisterIndicator(symbol, atr, consolidator);
                RegisterIndicator(symbol, adx, consolidator);

                /****** ALMA Fibonacci ******/
                var alma5   = new ArnaudLegouxMovingAverage(symbol, 5);
                var alma8   = new ArnaudLegouxMovingAverage(symbol, 8);
                var alma13  = new ArnaudLegouxMovingAverage(symbol, 13);
                var alma21  = new ArnaudLegouxMovingAverage(symbol, 21);
                var alma34  = new ArnaudLegouxMovingAverage(symbol, 34);
                var alma55  = new ArnaudLegouxMovingAverage(symbol, 55);
                var alma89  = new ArnaudLegouxMovingAverage(symbol, 89);
                var alma144 = new ArnaudLegouxMovingAverage(symbol, 144);

                RegisterIndicator(symbol, alma5, consolidator);
                RegisterIndicator(symbol, alma8, consolidator);
                RegisterIndicator(symbol, alma13, consolidator);
                RegisterIndicator(symbol, alma21, consolidator);
                RegisterIndicator(symbol, alma34, consolidator);
                RegisterIndicator(symbol, alma55, consolidator);
                RegisterIndicator(symbol, alma89, consolidator);
                RegisterIndicator(symbol, alma144, consolidator);

                SubscriptionManager.AddConsolidator(symbol, consolidator);

                var signal = new SVMBaselineSignal(
                    dailyConsolidator, alma,
                    consolidator, alma5, alma8, alma13, alma21, alma34, alma55, alma89, alma144, schaffTrendCycle, atr, adx,
                    Portfolio[symbol], Securities[symbol], this
                    );

                var std = ATR(symbol, 100, MovingAverageType.DoubleExponential, _dataResolution);

                /******** HISTORY ********/
                var history = History <QuoteBar>(symbol, TimeSpan.FromDays(100), _dataResolution);

                foreach (var bar in history)
                {
                    std.Update(bar);
                    consolidator.Update(bar);
                    dailyConsolidator.Update(bar);
                }

                if (_store)
                {
                    var header = new string[] { "Time", "ALMA_5", "ALMA_8", "ALMA_13", "ALMA_21", "ALMA_34", "ALMA_55", "ALMA_89", "ALMA_144" };
                    Storage.CreateFile($"C:\\Users\\M\\Desktop\\{symbol}_ALMA.csv", header);

                    consolidator.DataConsolidated += (sender, args) =>
                    {
                        var line = new object[] { Storage.ToUTCTimestamp(args.Time), alma5.Current.Value, alma8.Current.Value, alma13.Current.Value,
                                                  alma21.Current.Value, alma34.Current.Value, alma55.Current.Value, alma89.Current.Value, alma144.Current.Value };
                        Storage.AppendToFile($"C:\\Users\\M\\Desktop\\{symbol}_ALMA.csv", line);
                    };
                }

                Securities[symbol].VolatilityModel = new AverageTrueRangeVolatilityModel(std);
                _tradingAssets.Add(symbol,
                                   new TradingAsset(Securities[symbol],
                                                    new OneShotTrigger(signal),
                                                    new ProfitTargetSignalExit(null, _targetProfitLoss),
                                                    _maximumTradeRisk,
                                                    _maximumTradeSize,
                                                    this
                                                    ));

                //_tradingAssets[symbol].IsTradable = true;

                var h = new object[] { "Time", "Signal", "Price" };
                Storage.CreateFile($"C:\\Users\\M\\Desktop\\{symbol}_ALMA_Signal.csv", h);
            }

            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday),
                        TimeRules.At(7, 0, TimeZones.London), () =>
            {
                var tradeableDay = TradingCalendar.GetTradingDay().BusinessDay;
                if (tradeableDay)
                {
                    foreach (var s in Symbols)
                    {
                        _tradingAssets[s].IsTradable = true;
                    }
                }
            });

            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday),
                        TimeRules.At(20, 0, TimeZones.London), () =>
            {
                foreach (var s in Symbols)
                {
                    //_tradingAssets[s].IsTradable = false;
                }
            });

            Schedule.On(DateRules.Every(DayOfWeek.Friday),
                        TimeRules.BeforeMarketClose(Symbols.First(), 240), () =>
            {
                foreach (var s in Symbols)
                {
                    //_tradingAssets[s].IsTradable = false;
                }
            });

            Schedule.On(DateRules.Every(DayOfWeek.Friday),
                        TimeRules.BeforeMarketClose(Symbols.First(), 180), () =>
            {
                foreach (var s in Symbols)
                {
                    //_tradingAssets[s].Liquidate();
                    //_tradingAssets[s].IsTradable = false;
                }
            });

            /******** CHARTING ********/

            /*Chart price = new Chart("Daily Price");
             * price.AddSeries(new Series("Price", SeriesType.Candle, 0));
             * price.AddSeries(new Series("MA", SeriesType.Line, 0));
             * price.AddSeries(new Series("Slope", SeriesType.Line, 1));
             * price.AddSeries(new Series("STC", SeriesType.Line, 2));
             * AddChart(price);
             *
             * Chart ma = new Chart("MA");
             * ma.AddSeries(new Series("HMA", SeriesType.Line, 0));
             * ma.AddSeries(new Series("FAMA", SeriesType.Line, 1));
             * AddChart(ma);
             *
             * Chart lsma = new Chart("LSMA");
             * lsma.AddSeries(new Series("Slope", SeriesType.Line, 0));
             * AddChart(lsma);*/

            Chart plotter = new Chart("Plotter");

            plotter.AddSeries(new Series("Close", SeriesType.Line, 0));
            plotter.AddSeries(new Series("EMA", SeriesType.Line, 1));
            plotter.AddSeries(new Series("Buy", SeriesType.Scatter, "", Color.Green, ScatterMarkerSymbol.Triangle));
            plotter.AddSeries(new Series("Sell", SeriesType.Scatter, "", Color.Red, ScatterMarkerSymbol.TriangleDown));
            //plotter.AddSeries(new Series("Stopped", SeriesType.Scatter, "", Color.Yellow, ScatterMarkerSymbol.Diamond));
            plotter.AddSeries(new Series("Diff", SeriesType.Bar, 2));
            plotter.AddSeries(new Series("Slope", SeriesType.Line, 3));
            plotter.AddSeries(new Series("STC", SeriesType.Line, 4));
            plotter.AddSeries(new Series("STOCH", SeriesType.Line, 5));
            plotter.AddSeries(new Series("Prediction", SeriesType.Bar, 6));
            plotter.AddSeries(new Series("Signal", SeriesType.Bar, 7));
            AddChart(plotter);
        }
Exemplo n.º 11
0
        public override void Initialize()
        {
            SetStartDate(2007, 4, 1);
            SetEndDate(DateTime.Now);
            SetCash(2000);

            SetBenchmark(SecurityType.Forex, "EURUSD");

            //Add as many securities as you like. All the data will be passed into the event handler:
            foreach (var symbol in _symbols)
            {
                AddSecurity(SecurityType.Forex, symbol, _dataResolution);
                //Securities[symbol].FeeModel = new ConstantFeeModel(0.04m);
                Securities[symbol].FeeModel         = new FxcmFeeModel();
                Securities[symbol].SlippageModel    = new SpreadSlippageModel();
                Securities[symbol].TransactionModel = new FxcmTransactionModel();
                //Securities[symbol].SetLeverage(50.0m);
                SetBrokerageModel(BrokerageName.FxcmBrokerage);

                Schedule.On(DateRules.Every(DayOfWeek.Sunday, DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday),
                            TimeRules.AfterMarketOpen(symbol, -60d), () =>
                {
                    Securities[symbol].IsTradable = false;
                    // make untradeable
                });

                Schedule.On(DateRules.Every(DayOfWeek.Sunday, DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday),
                            TimeRules.AfterMarketOpen(symbol, 120d), () =>
                {
                    // make tradeable
                });

                Schedule.On(DateRules.Every(DayOfWeek.Friday), TimeRules.BeforeMarketClose(symbol, -60d), () =>
                {
                    Liquidate();
                    // make untradeable
                });

                _vwaps.Add(symbol, VWAP(symbol, 30));

                var rsi = RSI(symbol, 30, MovingAverageType.Exponential, _dataResolution);

                var momersion = MOMERSION(symbol, 10, 30, _dataResolution);

                var williams = WILR(symbol, 60, _dataResolution);

                var ind = SMA(symbol, 10, _dataResolution, x => rsi);

                var adx = ADX(symbol, 30, _dataResolution);

                var psar = PSAR(symbol, 0.02M, 0.02M, 0.2M, _dataResolution);

                var fisher = new FisherTransform(symbol, 30);

                var stoch1 = STO(symbol, 30, 30, 60);
                var stoch2 = new Stochastic(symbol, 30, 30, 60);

                var rocp = ROCP(symbol, 30, _dataResolution);

                var tradeBarHistory = History(symbol, TimeSpan.FromDays(2), _dataResolution);

                foreach (var tradeBar in tradeBarHistory)
                {
                    _vwaps[symbol].Update(tradeBar);
                }

                Securities[symbol].VolatilityModel = new ThreeSigmaVolatilityModel(STD(symbol, 390, _dataResolution));
                _tradingAssets.Add(symbol,
                                   new TradingAsset(Securities[symbol],
                                                    new OneShotTrigger(new VwapSignal(_vwaps[symbol], Portfolio[symbol])),
                                                    new ProfitTargetSignalExit(null, TargetProfitLossRatio),
                                                    RiskPerTrade,
                                                    MaximumTradeSize,
                                                    this
                                                    ));
            }
        }
Exemplo n.º 12
0
        // TODO: check volatilitymodel https://github.com/QuantConnect/Lean/blob/master/Common/Securities/RelativeStandardDeviationVolatilityModel.cs
        public override void Initialize()
        {
            SetStartDate(2016, 1, 1);
            SetEndDate(2016, 4, 1);
            SetCash(3000);

            SetBrokerageMessageHandler(new CustomBrokerageMessageHandler(this));

            var allInputs  = new List <double[]>();
            var allOutputs = new List <int>();
            var allWeights = new List <double>();

            foreach (var symbol in Symbols)
            {
                AddForex(symbol, _dataResolution, Market.Oanda, false, 1m);

                Securities[symbol].TransactionModel = new OandaTransactionModel();
                //Securities[symbol].SlippageModel = new ConstantSlippageModel(0m);
                SetBrokerageModel(BrokerageName.OandaBrokerage);

                /************ TRAINING ************/
                var trainingResolution = Resolution.Minute;

                /*var slowT = HMA(symbol, 28, trainingResolution, Field.Close);
                 * var slowSlopeT = new InstantTrend(symbol, 5).Of(slowT);
                 * var returnT = LOGR(symbol, 3, trainingResolution, Field.Close);
                 * var returnSlopeT = LSMA(symbol, 5, trainingResolution).Of(returnT);*/

                var consolidatorT = new QuoteBarConsolidator(TimeSpan.FromMinutes(15));
                var stochT        = new Stochastic(symbol, 14, 3, 3);
                var stochTMA      = new HullMovingAverage(symbol, 3).Of(stochT);
                var emaT          = new ExponentialMovingAverage(symbol, 40);
                RegisterIndicator(symbol, stochT, consolidatorT);
                RegisterIndicator(symbol, emaT, consolidatorT);
                SubscriptionManager.AddConsolidator(symbol, consolidatorT);

                var historyT = History <QuoteBar>(symbol, TimeSpan.FromDays(500), trainingResolution);

                var quoteBars     = new List <QuoteBar>();
                var stochs        = new List <double>();
                var rollingStochs = new RollingWindow <double>(1000);
                var stochsMA      = new List <double>();
                var emas          = new List <double>();
                var stochCount    = new List <double>();
                var stochAverage  = new List <double>();

                //consolidatorT.DataConsolidated += (sender, args) => quoteBars.Add(args);
                stochTMA.Updated += (sender, args) =>
                {
                    if (!stochTMA.IsReady || !emaT.IsReady)
                    {
                        return;
                    }

                    quoteBars.Add((QuoteBar)consolidatorT.Consolidated);
                    stochs.Add((double)stochT.Current.Value);
                    rollingStochs.Add((double)args.Value);
                    stochsMA.Add((double)args.Value);
                    emas.Add((double)emaT.Current.Value);

                    var filtered = rollingStochs.TakeWhile((s) => args.Value > 50 ? s > 50 : args.Value < 50 ? s < 50 : false);
                    stochCount.Add(filtered.Count());

                    try
                    {
                        stochAverage.Add(filtered.Average());
                    }
                    catch (Exception ex)
                    {
                        stochAverage.Add(0);
                    }
                };

                foreach (var bar in historyT)
                {
                    consolidatorT.Update(bar);
                }

                Console.WriteLine("{0} {1} {2} {3} {4}", quoteBars.Count, stochs.Count, stochCount.Count, stochAverage.Count, emas.Count);

                var inputs  = new List <double[]>();
                var outputs = new List <int>();
                var weights = new List <double>();

                for (var i = 1; i < quoteBars.Count; i++)
                {
                    var longTarget  = quoteBars[i].Close + (30m / 10000m);
                    var longStop    = quoteBars[i].Close - (10m / 10000m);
                    var shortTarget = quoteBars[i].Close - (30m / 10000m);
                    var shortStop   = quoteBars[i].Close + (10m / 10000m);

                    var longSetup  = stochs[i] >= 35 && stochsMA[i] > stochsMA[i - 1] && (double)quoteBars[i].Close > emas[i];
                    var shortSetup = stochs[i] <= 65 && stochs[i] > 0 && stochsMA[i] < stochsMA[i - 1] && (double)quoteBars[i].Close < emas[i];

                    if (!longSetup && !shortSetup)
                    {
                        continue;
                    }

                    for (var j = i + 1; j < quoteBars.Count; j++)
                    {
                        var current = quoteBars[j];
                        if (current.High >= longTarget && current.Low > longStop && longSetup)
                        {
                            inputs.Add(new double[] { stochAverage[i], stochCount[i], (double)quoteBars[i].Close / emas[i] });
                            outputs.Add(1);

                            var profit = current.High - quoteBars[i].Close;

                            /*for (var k = j + 1; k < quoteBars.Count; k++)
                             * {
                             *
                             * }*/
                            weights.Add((double)(1m - (50m / 10000m) / profit));

                            //i = j;
                            break;
                        }
                        else if (current.Low <= shortTarget && current.High < shortStop && shortSetup)
                        {
                            inputs.Add(new double[] { stochAverage[i], stochCount[i], (double)quoteBars[i].Close / emas[i] });
                            outputs.Add(0);

                            var profit = quoteBars[i].Close - current.Low;

                            /*for (var k = j + 1; k < quoteBars.Count; k++)
                             * {
                             *
                             * }*/
                            weights.Add((double)(1m - (50m / 10000m) / profit));
                            //i = j;
                            break;
                        }
                        else if ((current.Low <= longStop && longSetup) || (current.High >= shortStop && shortSetup))
                        {
                            //inputs.Add(new double[] { stochAverage[i] / stochs[i], stochCount[i], stochAverage[i] });
                            //outputs.Add(2);
                            //i = j;
                            break;
                        }

                        /*else if (j - i > 4 * 8)
                         * {
                         *  inputs.Add(new double[] { stochs[i], stochCount[i], stochAverage[i] });
                         *  outputs.Add(0);
                         *  //i = j;
                         *  break;
                         * }*/
                    }
                }

                allInputs.AddRange(inputs);
                allOutputs.AddRange(outputs);
                allWeights.AddRange(weights);

                for (var i = 0; i < inputs.Count; i++)
                {
                    //Console.WriteLine("Input: " + inputs[i][0] + " " + inputs[i][1] + " " + inputs[i][2] + " Output: " + outputs[i]);
                }

                var none = outputs.Where((o) => o == 2).Count();
                var sell = outputs.Where((o) => o == 0).Count();
                var buy  = outputs.Where((o) => o == 1).Count();

                Console.WriteLine("Total: {0} None: {1} Short: {2} Long: {3}", outputs.Count, none, sell, buy);

                /************ HMA ************/

                /*var slow = HMA(symbol, 28, trainingResolution, Field.Close);
                 * var slowSlope = new InstantTrend(symbol, 5).Of(slow);
                 * var logReturns = LOGR(symbol, 3, trainingResolution, Field.Close);
                 * var returnSlope = LSMA(symbol, 5, trainingResolution).Of(logReturns);*/

                var consolidator = new QuoteBarConsolidator(TimeSpan.FromMinutes(15));
                var stoch        = new Stochastic(symbol, 14, 3, 3);
                var stochMA      = new HullMovingAverage(symbol, 2).Of(stoch);
                var ema          = new ExponentialMovingAverage(symbol, 40);
                var rolling      = new RollingWindow <double>(1000);
                RegisterIndicator(symbol, stoch, consolidator);
                RegisterIndicator(symbol, ema, consolidator);
                SubscriptionManager.AddConsolidator(symbol, consolidator);

                _stoch[symbol] = stoch;
                _ema[symbol]   = ema;

                stochMA.Updated += (sender, args) =>
                {
                    rolling.Add((double)args.Value);

                    if (Securities[symbol].Price > 0)
                    {
                        //Plot("Plotter", "Price", Securities["EURUSD"].Price);
                        Plot("Indicator", "STO", rolling[0]);
                    }
                };

                var std = ATR(symbol, 100, MovingAverageType.DoubleExponential, _dataResolution);

                var history = History <QuoteBar>(symbol, TimeSpan.FromDays(20), trainingResolution);

                foreach (var bar in history)
                {
                    //slow.Update(bar.EndTime, bar.Close);
                    //logReturns.Update(bar.EndTime, bar.Close);
                    std.Update(bar);
                    consolidator.Update(bar);
                }

                var signal = new SVMSignal(consolidator, stoch, stochMA, rolling, ema, Portfolio[symbol], this);
                signal.TrainSVM(inputs, outputs, weights);
                //signal.TrainNN(inputs, outputs, weights);

                Securities[symbol].VolatilityModel = new AverageTrueRangeVolatilityModel(std);
                _tradingAssets.Add(symbol,
                                   new TradingAsset(Securities[symbol],
                                                    new OneShotTrigger(signal),
                                                    new ProfitTargetSignalExit(null, _targetProfitLoss),
                                                    _maximumTradeRisk,
                                                    _maximumTradeSize,
                                                    this
                                                    ));
            }

            foreach (var symbol in Symbols)
            {
                //_tradingAssets[symbol].Retrain(allInputs, allOutputs, allWeights);
            }

            //AddData<DailyFx>("DFX", Resolution.Second, TimeZones.Utc);

            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday),
                        TimeRules.At(7, 0, TimeZones.London), () =>
            {
                var tradeableDay = TradingCalendar.GetTradingDay().BusinessDay;
                if (tradeableDay)
                {
                    foreach (var s in Symbols)
                    {
                        _tradingAssets[s].IsTradable = true;
                    }
                }
            });

            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday),
                        TimeRules.At(18, 0, TimeZones.London), () =>
            {
                foreach (var s in Symbols)
                {
                    _tradingAssets[s].IsTradable = false;
                }
            });

            Schedule.On(DateRules.Every(DayOfWeek.Friday),
                        TimeRules.BeforeMarketClose(Symbols.First(), 60), () =>
            {
                foreach (var s in Symbols)
                {
                    _tradingAssets[s].Liquidate();
                }
            });

            Chart plotter = new Chart("Plotter");

            plotter.AddSeries(new Series("Price", SeriesType.Line, 0));
            plotter.AddSeries(new Series("EMA", SeriesType.Line, 0));
            plotter.AddSeries(new Series("Buy", SeriesType.Scatter, "", Color.Green, ScatterMarkerSymbol.Triangle));
            plotter.AddSeries(new Series("Sell", SeriesType.Scatter, "", Color.Red, ScatterMarkerSymbol.TriangleDown));
            plotter.AddSeries(new Series("Stopped", SeriesType.Scatter, "", Color.Yellow, ScatterMarkerSymbol.Diamond));
            plotter.AddSeries(new Series("Prediction", SeriesType.Bar, 1));
            plotter.AddSeries(new Series("Probability", SeriesType.Bar, 2));
            AddChart(plotter);

            Chart indicator = new Chart("Indicator");

            indicator.AddSeries(new Series("STO", SeriesType.Line, 0));
            AddChart(indicator);

            Chart prediction = new Chart("Prediction");

            prediction.AddSeries(new Series("Pred", SeriesType.Bar, 0));
            AddChart(prediction);

            Chart probability = new Chart("Probability");

            probability.AddSeries(new Series("Prob", SeriesType.Bar, 0));
            AddChart(probability);
        }
Exemplo n.º 13
0
        // TODO: check volatilitymodel https://github.com/QuantConnect/Lean/blob/master/Common/Securities/RelativeStandardDeviationVolatilityModel.cs
        public override void Initialize()
        {
            SetStartDate(2016, 1, 1);
            SetEndDate(2017, 1, 1);
            SetCash(3000);

            SetBrokerageMessageHandler(new CustomBrokerageMessageHandler(this));

            foreach (var symbol in Symbols)
            {
                AddForex(symbol, _dataResolution, Market.Oanda, false, 1m);

                Securities[symbol].TransactionModel = new OandaTransactionModel();
                //Securities[symbol].SlippageModel = new ConstantSlippageModel(0m);
                SetBrokerageModel(BrokerageName.OandaBrokerage);

                var consolidator = new QuoteBarConsolidator(TimeSpan.FromMinutes(20));
                var stoch        = new Stochastic(symbol, 10, 3, 3);
                var stochMA      = new ExponentialMovingAverage(symbol, 25).Of(stoch);
                var stochEmaLSMA = new LeastSquaresMovingAverage(symbol, 5).Of(stochMA);
                var ema          = new ExponentialMovingAverage(symbol, 40);
                var emaMA        = new LeastSquaresMovingAverage(symbol, 5).Of(ema);

                var rollingStochMA       = HistoryTracker.Track(stochMA);
                var rollingEmaSlope      = HistoryTracker.Track(emaMA.Slope);
                var rollingStochEmaSlope = HistoryTracker.Track(stochEmaLSMA.Slope);

                var shortTermMA = EMA(symbol, 30, Resolution.Minute, Field.Close);

                RegisterIndicator(symbol, stoch, consolidator);
                RegisterIndicator(symbol, ema, consolidator);
                SubscriptionManager.AddConsolidator(symbol, consolidator);

                _stoch[symbol] = stoch;
                _ema[symbol]   = ema;

                var consolidatorDaily = new QuoteBarConsolidator(TimeSpan.FromHours(1));
                var dailyMA           = new HullMovingAverage(symbol, 7);
                var dailyEmaLSMA      = new LeastSquaresMovingAverage(symbol, 3).Of(dailyMA);

                var rollingDailyEmaSlope = HistoryTracker.Track(dailyEmaLSMA.Slope);

                RegisterIndicator(symbol, dailyMA, consolidatorDaily);
                SubscriptionManager.AddConsolidator(symbol, consolidatorDaily);

                stochMA.Updated += (sender, args) =>
                {
                    if (Securities[symbol].Price > 0)
                    {
                        Plot("Indicator", "STO", rollingStochMA[0]);
                    }
                };

                stochEmaLSMA.Updated += (sender, args) =>
                {
                    if (Securities[symbol].Price > 0)
                    {
                        Plot("IndicatorTrend", "STO", stochEmaLSMA.Slope);
                    }
                };

                /*emaMA.Updated += (sender, args) =>
                 * {
                 *  if (Securities[symbol].Price > 0)
                 *  {
                 *      Plot("Trend", "LSMA", emaMA.Slope);
                 *  }
                 * };*/

                dailyEmaLSMA.Updated += (sender, args) =>
                {
                    if (Securities[symbol].Price > 0)
                    {
                        Plot("Trend", "LSMA", dailyEmaLSMA.Slope);
                        Plot("Trend", "EMA", dailyMA);
                    }
                };

                var std = ATR(symbol, 100, MovingAverageType.DoubleExponential, _dataResolution);

                var history = History <QuoteBar>(symbol, TimeSpan.FromDays(40), _dataResolution);

                foreach (var bar in history)
                {
                    std.Update(bar);
                    consolidator.Update(bar);
                    shortTermMA.Update(bar.EndTime, bar.Close);
                    consolidatorDaily.Update(bar);
                }

                var signal = new SVMBaselineSignalWIP(consolidator, stoch, stochMA, rollingStochMA, stochEmaLSMA, rollingStochEmaSlope, ema, emaMA,
                                                      rollingEmaSlope, shortTermMA, dailyEmaLSMA, rollingDailyEmaSlope, Portfolio[symbol], Securities[symbol], this);

                Securities[symbol].VolatilityModel = new AverageTrueRangeVolatilityModel(std);
                _tradingAssets.Add(symbol,
                                   new TradingAsset(Securities[symbol],
                                                    new OneShotTrigger(signal),
                                                    new ProfitTargetSignalExit(null, _targetProfitLoss),
                                                    _maximumTradeRisk,
                                                    _maximumTradeSize,
                                                    this
                                                    ));
            }

            //AddData<DailyFx>("DFX", Resolution.Second, TimeZones.Utc);

            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday),
                        TimeRules.At(7, 0, TimeZones.London), () =>
            {
                var tradeableDay = TradingCalendar.GetTradingDay().BusinessDay;
                if (tradeableDay)
                {
                    foreach (var s in Symbols)
                    {
                        _tradingAssets[s].IsTradable = true;
                    }
                }
            });

            Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday),
                        TimeRules.At(20, 0, TimeZones.London), () =>
            {
                foreach (var s in Symbols)
                {
                    _tradingAssets[s].IsTradable = false;
                }
            });

            Schedule.On(DateRules.Every(DayOfWeek.Friday),
                        TimeRules.BeforeMarketClose(Symbols.First(), 60), () =>
            {
                foreach (var s in Symbols)
                {
                    _tradingAssets[s].Liquidate();
                }
            });

            Chart plotter = new Chart("Plotter");

            plotter.AddSeries(new Series("Price", SeriesType.Line, 0));
            plotter.AddSeries(new Series("EMA", SeriesType.Line, 0));
            plotter.AddSeries(new Series("Buy", SeriesType.Scatter, "", Color.Green, ScatterMarkerSymbol.Triangle));
            plotter.AddSeries(new Series("Sell", SeriesType.Scatter, "", Color.Red, ScatterMarkerSymbol.TriangleDown));
            plotter.AddSeries(new Series("Stopped", SeriesType.Scatter, "", Color.Yellow, ScatterMarkerSymbol.Diamond));
            plotter.AddSeries(new Series("Prediction", SeriesType.Bar, 1));
            plotter.AddSeries(new Series("Probability", SeriesType.Bar, 2));
            AddChart(plotter);

            Chart indicator = new Chart("Indicator");

            indicator.AddSeries(new Series("STO", SeriesType.Line, 0));
            AddChart(indicator);

            Chart indicatorTrend = new Chart("IndicatorTrend");

            indicatorTrend.AddSeries(new Series("STO", SeriesType.Line, 0));
            AddChart(indicatorTrend);

            Chart trend = new Chart("Trend");

            trend.AddSeries(new Series("LSMA", SeriesType.Line, 0));
            trend.AddSeries(new Series("EMA", SeriesType.Line, 1));
            AddChart(trend);

            Chart prediction = new Chart("Prediction");

            prediction.AddSeries(new Series("Pred", SeriesType.Bar, 0));
            AddChart(prediction);

            Chart probability = new Chart("Probability");

            probability.AddSeries(new Series("Prob", SeriesType.Bar, 0));
            AddChart(probability);
        }