Exemplo n.º 1
0
        public override void Initialize()
        {
            AddEquity(SYM, Resolution.Minute);

            AddEquity("TLT", Resolution.Minute);
            AddEquity("IEF", Resolution.Minute);
            AddEquity("DBC", Resolution.Minute);
            //AddEquity("VEA", Resolution.Minute);
            AddEquity("GLD", Resolution.Minute);

            //var week5Consolidator = new TradeBarConsolidator(TimeSpan.FromDays(22));
            RegisterIndicator(SYM, ma, TimeSpan.FromDays(22));
            //week5Consolidator.DataConsolidated += (sender, consolidated) => OnWeek5(sender, (TradeBar) consolidated);

            // this call adds our 3 day to the manager to receive updates from the engine
            //SubscriptionManager.AddConsolidator(SYM, week5Consolidator);

            // There are other assets with similar methods. See "Selecting Options" etc for more details.
            // AddFuture, AddForex, AddCfd, AddOption
            Schedule.On(DateRules.EveryDay(SYM), TimeRules.AfterMarketOpen(SYM, 5), () =>
            {
                //Log("EveryDay.SPY 10 min after open: Fired at: " + Time);
                if (fullOn)
                {
                    if (Securities[SYM].Price < ma && prevRebalCondition)
                    {
                        var ratio = 1;
                        SetAllWeatherHoldings(ratio);
                        fullOn = false;
                    }
                    prevRebalCondition = Securities[SYM].Price > ma;
                }
            });
        }
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);
            SetEndDate(2013, 10, 11);

            var security = AddEquity("SPY", Resolution.Minute);

            _spy = security.Symbol;

            _closedMarketLeverage     = 2;
            _openMarketLeverage       = 5;
            security.BuyingPowerModel = new PatternDayTradingMarginModel(_closedMarketLeverage, _openMarketLeverage);

            Schedule.On(
                DateRules.EveryDay(_spy),
                // 15 minutes before market close, because PatternDayTradingMarginModel starts using closed
                // market leverage 10 minutes before market closes.
                TimeRules.BeforeMarketClose(_spy, 15),
                () => {
                // before market close we reduce our position to closed market leverage
                SetHoldings(_spy, _closedMarketLeverage);
            }
                );

            Schedule.On(
                DateRules.EveryDay(_spy),
                TimeRules.AfterMarketOpen(_spy, 1), // 1 min so that price is set
                () => {
                // at market open we increase our position to open market leverage
                SetHoldings(_spy, _openMarketLeverage);
            }
                );
        }
        /// <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


            SetSecurityInitializer(x => x.SetDataNormalizationMode(DataNormalizationMode.Raw));

            _symbol = AddEquity("IBM", Resolution.Minute).Symbol;
            AddEquity("AAPL", Resolution.Daily);

            // 2013-10-07 was Monday, that's why we ask 3 days history to get  data from previous Friday.
            var history = History(new[] { _symbol }, TimeSpan.FromDays(3), Resolution.Minute).ToList();

            Log($"{Time} - history.Count: {history.Count}");

            const int expectedSliceCount = 390;

            if (history.Count != expectedSliceCount)
            {
                throw new Exception($"History slices - expected: {expectedSliceCount}, actual: {history.Count}");
            }


            if (history.Any(s => s.Bars.Count != 1 && s.QuoteBars.Count != 1))
            {
                throw new Exception($"History not all slices have trades and quotes.");
            }

            Schedule.On(DateRules.EveryDay(_symbol), TimeRules.AfterMarketOpen(_symbol, 0), () => { _canTrade = true; });

            Schedule.On(DateRules.EveryDay(_symbol), TimeRules.BeforeMarketClose(_symbol, 16), () => { _canTrade = false; });
        }
        public override void Initialize()
        {
            SetStartDate(2020, 1, 5);
            SetEndDate(2020, 6, 30);

            // We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
            // which causes delisting events to never be processed, thus leading to options that might never
            // be exercised until the next data point arrives.
            AddEquity("AAPL", Resolution.Daily);

            _es19m20 = AddFutureContract(
                QuantConnect.Symbol.CreateFuture(
                    Futures.Indices.SP500EMini,
                    Market.CME,
                    new DateTime(2020, 6, 19)),
                Resolution.Minute).Symbol;

            // Select a future option expiring ITM, and adds it to the algorithm.
            _esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time)
                                                .Where(x => x.ID.StrikePrice >= 3400m && x.ID.OptionRight == OptionRight.Call)
                                                .OrderBy(x => x.ID.StrikePrice)
                                                .Take(1)
                                                .Single(), Resolution.Minute).Symbol;

            _expectedContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3400m, new DateTime(2020, 6, 19));
            if (_esOption != _expectedContract)
            {
                throw new Exception($"Contract {_expectedContract} was not found in the chain");
            }

            Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () =>
            {
                MarketOrder(_esOption, -1);
            });
        }
Exemplo n.º 5
0
        public override void Initialize()
        {
            SetStartDate(2016, 01, 01);  //Set Start Date
            SetEndDate(2016, 10, 14);    //Set End Date
            SetCash(10000);              //Set Strategy Cash

            // Find more symbols here: http://quantconnect.com/data
            // Forex, CFD, Equities Resolutions: Tick, Second, Minute, Hour, Daily.
            // Futures Resolution: Tick, Second, Minute
            // Options Resolution: Minute Only.
            // Add each equity so we receive data
            AddEquity(_spy, Resolution.Daily);
            AddEquity(_qqq, Resolution.Daily);
            AddEquity(_tlt, Resolution.Daily);
            AddEquity(_agg, Resolution.Daily);

            //Build window
            _close_window = new RollingWindow <decimal>(84);
            IEnumerable <TradeBar> slices = History(_benchmark, 84);

            foreach (TradeBar bar in slices)
            {
                _close_window.Add(bar.Close);
            }

            // Schedule EveryDayOnMarketOpen function to be called
            // each day 10 minutes after market open
            Schedule.On(DateRules.EveryDay(_benchmark),
                        TimeRules.AfterMarketOpen(_benchmark, 10),
                        EveryDayOnMarketOpen);
        }
Exemplo n.º 6
0
        public override void Initialize()
        {
            SetStartDate(2020, 1, 5);
            SetEndDate(2020, 6, 30);

            _es19m20 = AddFutureContract(
                QuantConnect.Symbol.CreateFuture(
                    Futures.Indices.SP500EMini,
                    Market.CME,
                    new DateTime(2020, 6, 19)),
                Resolution.Minute).Symbol;

            // Select a future option expiring ITM, and adds it to the algorithm.
            _esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time)
                                                .Where(x => x.ID.StrikePrice <= 3200m && x.ID.OptionRight == OptionRight.Call)
                                                .OrderByDescending(x => x.ID.StrikePrice)
                                                .Take(1)
                                                .Single(), Resolution.Minute).Symbol;

            _expectedOptionContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m, new DateTime(2020, 6, 19));
            if (_esOption != _expectedOptionContract)
            {
                throw new Exception($"Contract {_expectedOptionContract} was not found in the chain");
            }

            Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () =>
            {
                MarketOrder(_esOption, 1);
            });
        }
        public override void Initialize()
        {
            SetStartDate(2021, 1, 4);
            SetEndDate(2021, 1, 31);

            _spx = AddIndex("SPX", Resolution.Minute).Symbol;

            // Select a index option expiring ITM, and adds it to the algorithm.
            _spxOption = AddIndexOptionContract(OptionChainProvider.GetOptionContractList(_spx, Time)
                                                .Where(x => x.ID.StrikePrice <= 3200m && x.ID.OptionRight == OptionRight.Put && x.ID.Date.Year == 2021 && x.ID.Date.Month == 1)
                                                .OrderByDescending(x => x.ID.StrikePrice)
                                                .Take(1)
                                                .Single(), Resolution.Minute).Symbol;

            _expectedContract = QuantConnect.Symbol.CreateOption(_spx, Market.USA, OptionStyle.European, OptionRight.Put, 3200m, new DateTime(2021, 1, 15));
            if (_spxOption != _expectedContract)
            {
                throw new Exception($"Contract {_expectedContract} was not found in the chain");
            }

            Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_spx, 1), () =>
            {
                MarketOrder(_spxOption, 1);
            });
        }
Exemplo n.º 8
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.º 9
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(2020, 1, 5);
            SetEndDate(2020, 6, 30);

            // We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872
            // which causes delisting events to never be processed, thus leading to options that might never
            // be exercised until the next data point arrives.
            AddEquity("AAPL", Resolution.Daily);

            var es20h20 = AddFutureContract(
                QuantConnect.Symbol.CreateFuture(
                    Futures.Indices.SP500EMini,
                    Market.CME,
                    new DateTime(2020, 3, 20)),
                Resolution.Minute).Symbol;

            var es20m20 = AddFutureContract(
                QuantConnect.Symbol.CreateFuture(
                    Futures.Indices.SP500EMini,
                    Market.CME,
                    new DateTime(2020, 6, 19)),
                Resolution.Minute).Symbol;

            // Select a future option expiring ITM, and adds it to the algorithm.
            var esOptions = OptionChainProvider.GetOptionContractList(es20m20, Time)
                            .Concat(OptionChainProvider.GetOptionContractList(es20h20, Time))
                            .Where(x => x.ID.StrikePrice == 3200m && x.ID.OptionRight == OptionRight.Call)
                            .Select(x => AddFutureOptionContract(x, Resolution.Minute).Symbol)
                            .ToList();

            var expectedContracts = new[]
            {
                QuantConnect.Symbol.CreateOption(es20h20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m,
                                                 new DateTime(2020, 3, 20)),
                QuantConnect.Symbol.CreateOption(es20m20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m,
                                                 new DateTime(2020, 6, 19))
            };

            foreach (var esOption in esOptions)
            {
                if (!expectedContracts.Contains(esOption))
                {
                    throw new Exception($"Contract {esOption} was not found in the chain");
                }
            }

            Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(es20m20, 1), () =>
            {
                MarketOrder(esOptions[0], 1);
                MarketOrder(esOptions[1], -1);
            });
            Schedule.On(DateRules.Tomorrow, TimeRules.Noon, () =>
            {
                Liquidate();
            });
        }
Exemplo n.º 11
0
        public override void Initialize()
        {
            SetStartDate(2021, 1, 4);
            SetEndDate(2021, 1, 31);

            var spx = AddIndex("SPX", Resolution.Minute).Symbol;

            // Select a index option expiring ITM, and adds it to the algorithm.
            var spxOptions = OptionChainProvider.GetOptionContractList(spx, Time)
                             .Where(x => (x.ID.StrikePrice == 3700m || x.ID.StrikePrice == 3800m) && x.ID.OptionRight == OptionRight.Call && x.ID.Date.Year == 2021 && x.ID.Date.Month == 1)
                             .Select(x => AddIndexOptionContract(x, Resolution.Minute).Symbol)
                             .OrderBy(x => x.ID.StrikePrice)
                             .ToList();

            var expectedContract3700 = QuantConnect.Symbol.CreateOption(
                spx,
                Market.USA,
                OptionStyle.European,
                OptionRight.Call,
                3700m,
                new DateTime(2021, 1, 15));

            var expectedContract3800 = QuantConnect.Symbol.CreateOption(
                spx,
                Market.USA,
                OptionStyle.European,
                OptionRight.Call,
                3800m,
                new DateTime(2021, 1, 15));

            if (spxOptions.Count != 2)
            {
                throw new Exception($"Expected 2 index options symbols from chain provider, found {spxOptions.Count}");
            }

            if (spxOptions[0] != expectedContract3700)
            {
                throw new Exception($"Contract {expectedContract3700} was not found in the chain, found instead: {spxOptions[0]}");
            }
            if (spxOptions[1] != expectedContract3800)
            {
                throw new Exception($"Contract {expectedContract3800} was not found in the chain, found instead: {spxOptions[1]}");
            }

            Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(spx, 1), () =>
            {
                MarketOrder(spxOptions[0], 1);
                MarketOrder(spxOptions[1], -1);
            });
            Schedule.On(DateRules.Tomorrow, TimeRules.Noon, () =>
            {
                Liquidate();
            });
        }
Exemplo n.º 12
0
 public override void Initialize()
 {
     SetStartDate(2011, 1, 1);
     SetEndDate(2018, 1, 1);
     SetCash(100000);
     AddEquity("SPY");
     foreach (int period in Enumerable.Range(0, 300))
     {
         Schedule.On(DateRules.EveryDay("SPY"), TimeRules.AfterMarketOpen("SPY", period), Rebalance);
         Schedule.On(DateRules.EveryDay("SPY"), TimeRules.BeforeMarketClose("SPY", period), Rebalance);
     }
 }
Exemplo n.º 13
0
        public override void Initialize()
        {
            SetStartDate(2020, 1, 5);
            SetEndDate(2020, 6, 30);

            var es20h20 = AddFutureContract(
                QuantConnect.Symbol.CreateFuture(
                    Futures.Indices.SP500EMini,
                    Market.CME,
                    new DateTime(2020, 3, 20)),
                Resolution.Minute).Symbol;

            var es20m20 = AddFutureContract(
                QuantConnect.Symbol.CreateFuture(
                    Futures.Indices.SP500EMini,
                    Market.CME,
                    new DateTime(2020, 6, 19)),
                Resolution.Minute).Symbol;

            // Select a future option expiring ITM, and adds it to the algorithm.
            var esOptions = OptionChainProvider.GetOptionContractList(es20m20, Time)
                            .Concat(OptionChainProvider.GetOptionContractList(es20h20, Time))
                            .Where(x => x.ID.StrikePrice == 3200m && x.ID.OptionRight == OptionRight.Call)
                            .Select(x => AddFutureOptionContract(x, Resolution.Minute).Symbol)
                            .ToList();

            var expectedContracts = new[]
            {
                QuantConnect.Symbol.CreateOption(es20h20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m,
                                                 new DateTime(2020, 3, 20)),
                QuantConnect.Symbol.CreateOption(es20m20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m,
                                                 new DateTime(2020, 6, 19))
            };

            foreach (var esOption in esOptions)
            {
                if (!expectedContracts.Contains(esOption))
                {
                    throw new Exception($"Contract {esOption} was not found in the chain");
                }
            }

            Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(es20m20, 1), () =>
            {
                MarketOrder(esOptions[0], 1);
                MarketOrder(esOptions[1], -1);
            });
            Schedule.On(DateRules.Tomorrow, TimeRules.Noon, () =>
            {
                Liquidate();
            });
        }
Exemplo n.º 14
0
 public override void Initialize()
 {
     SetStartDate(2011, 1, 1);
     SetEndDate(2018, 1, 1);
     SetCash(100000);
     AddSecurity(SecurityType.Equity, "SPY", Resolution.Minute);
     foreach (int period in Enumerable.Range(0, 100))
     {
         Schedule.On(DateRules.EveryDay("SPY"), TimeRules.AfterMarketOpen("SPY", period), Rebalance);
         Schedule.On(DateRules.EveryDay("SPY"), TimeRules.BeforeMarketClose("SPY", period), Rebalance);
     }
     Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromSeconds(5)), Rebalance);
 }
Exemplo n.º 15
0
        public override void Initialize()
        {
            //SetStartDate(2010, 3, 1);
            //SetEndDate(2020, 2, 15);

            // SetStartDate(2019, 1, 1);

            //SetCash(REF_CASH);

            //SetWarmup(TimeSpan.FromDays(45));

            var ref_etf = "UPRO";

            // stocks.Add("TMF");
            // stocks.Add(ref_etf);
            foreach (var s in stocks)
            {
                AddEquity(s, Resolution.Minute);
            }

            AddEquity("VXX", Resolution.Minute);
            bb = Algo.BB("VXX", 20, 2m, MovingAverageType.Exponential, Resolution.Daily);
            //bbc = BB("UPRO", 100, 2m, MovingAverageType.Exponential, Resolution.Daily, x => (decimal)GetCorrel());
            if (!LiveMode)
            {
                AddEquity("VXX.1", Resolution.Minute);
            }
            if (!LiveMode)
            {
                bb1 = Algo.BB("VXX.1", 20, 2m, MovingAverageType.Exponential, Resolution.Daily);
            }

            int c = stocks.Count;

            weights = new double[c];



            //Schedule.On(DateRules.Every(DayOfWeek.Tuesday), TimeRules.AfterMarketOpen(ref_etf, 60), () =>
            Schedule.On(DateRules.EveryDay(ref_etf), TimeRules.AfterMarketOpen(ref_etf, 60), () =>
            {
                allocationTime = true;
                Log("allocationTime = true");
            });

            // Schedule.On(DateRules.EveryDay(ref_etf), TimeRules.AfterMarketOpen(ref_etf, 60), () =>
            // {
            //     if (!canAllocate) reallocateCheck = true;
            // });
        }
        public override void Initialize()
        {
            SetStartDate(2022, 02, 01);
            SetEndDate(2022, 02, 08);
            var esFuture = AddFuture("ES").Symbol;

            Schedule.On(DateRules.EveryDay(esFuture),
                        TimeRules.AfterMarketOpen(esFuture),
                        EveryDayAfterMarketOpen);

            Schedule.On(DateRules.EveryDay(esFuture),
                        TimeRules.BeforeMarketClose(esFuture),
                        EveryDayBeforeMarketClose);
        }
Exemplo n.º 17
0
        public override void Initialize()
        {
            SetStartDate(2020, 1, 1);
            SetEndDate(2020, 3, 31);
            SetCash(10000);

            _spy = AddEquity("SPY", Resolution.Hour).Symbol;
            var bnd = AddEquity("BND", Resolution.Hour).Symbol;

            Schedule.On(DateRules.EveryDay(_spy), TimeRules.AfterMarketOpen(_spy, 1, false), () =>
            {
                SetHoldings(_spy, 0.5m);
                SetHoldings(bnd, 0.5m);
            });
        }
Exemplo n.º 18
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);
        }
Exemplo n.º 19
0
        public override void Initialize()
        {
            SetStartDate(2010, 1, 1);
            SetEndDate(2018, 1, 1);
            SetCash(3000);

            foreach (var symbol in Symbols)
            {
                AddForex(symbol, _dataResolution, Market.Oanda, false, _leverage);
                AddData <QuandlRate>(_rateSymbols[symbol], _dataResolution, TimeZones.Utc, false);
            }

            Schedule.On(DateRules.MonthStart("USDEUR"),
                        TimeRules.AfterMarketOpen("USDEUR"), () =>
            {
                var orderByRateDecreasing = Symbols.Select((s) =>
                {
                    var kv = new KeyValuePair <string, string>(s, _rateSymbols[s]);
                    return(Tuple.Create(kv, Securities[kv.Value].Price));
                }).OrderByDescending((kvr) => kvr.Item2);

                foreach (var kvr in orderByRateDecreasing.Take(_positionCount))
                {
                    SetHoldings(kvr.Item1.Key, _leverage * 1m / (_positionCount * 2));
                }

                foreach (var kvr in orderByRateDecreasing.Skip(Math.Max(0, orderByRateDecreasing.Count() - _positionCount)))
                {
                    SetHoldings(kvr.Item1.Key, _leverage * -1m / (_positionCount * 2));
                }

                foreach (var kvr in orderByRateDecreasing.Skip(_positionCount).Take(orderByRateDecreasing.Count() - (2 * _positionCount)))
                {
                    Liquidate(kvr.Item1.Key);
                }

                foreach (var kvr in orderByRateDecreasing)
                {
                    //Console.WriteLine("Symbol: {0} Rate: {1}", kvr.Item1.Key, kvr.Item2);
                }
            });

            //AddData<DailyFx>("DFX", Resolution.Minute, TimeZones.Utc);
        }
Exemplo n.º 20
0
        public void Rebalance(Universe universe, List <Symbol> newPortfolio)
        {
            List <Symbol> portfolio = GetPortfolioSymbols();
            List <Symbol> sellList  = this.minus(portfolio, newPortfolio);
            List <Symbol> buyList   = this.minus(newPortfolio, portfolio);

            int diff = sellList.Count() - buyList.Count();

            while (diff > 0)
            {
                sellList.RemoveAt(0);
                diff--;
            }

            foreach (var symbol in sellList)
            {
                Security security = universe.Members[symbol];
                DateTime nextOpen = security.Exchange.Hours.GetNextMarketOpen(new DateTime(Time.Year, Time.Month, Time.Day), false);

                Schedule.On(
                    DateRules.On(nextOpen.Year, nextOpen.Month, nextOpen.Day),
                    TimeRules.AfterMarketOpen(symbol, 60),
                    () => {
                    //Debug("sold " + symbol);
                    Liquidate(symbol);
                }
                    );
            }

            foreach (var symbol in buyList)
            {
                Security security = universe.Members[symbol];
                DateTime nextOpen = security.Exchange.Hours.GetNextMarketOpen(new DateTime(Time.Year, Time.Month, Time.Day), false);

                Schedule.On(
                    DateRules.On(nextOpen.Year, nextOpen.Month, nextOpen.Day),
                    TimeRules.AfterMarketOpen(symbol, 90),
                    () => {
                    //Debug("bought " + symbol);
                    SetHoldings(symbol, 0.95m / newPortfolio.Count);
                }
                    );
            }
        }
Exemplo n.º 21
0
        public override void Initialize()
        {
            SetStartDate(2020, 11, 2);  //Set Start Date
            SetCash(100000);            //Set Strategy Cash
            SetWarmup(TimeSpan.FromDays(365));
            var resolution = Resolution.Daily;

            foreach (var etf in etfs)
            {
                AddEquity(etf, resolution);
                mas[etf] = new SimpleMovingAverage(12);
            }

            foreach (var etf in mm)
            {
                AddEquity(etf, resolution);
            }

            Schedule.On(DateRules.MonthStart(5), TimeRules.AfterMarketOpen(mm.ElementAt(0), 15),
                        () => rebalance = true);
        }
Exemplo n.º 22
0
        private readonly Dictionary <Symbol, SymbolData> _sd = new Dictionary <Symbol, SymbolData>(); //portfolio corresponding dic

        /// <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()
        {
            //set trade period
            SetStartDate(2010, 01, 01);  //Set Start Date
            SetEndDate(2018, 05, 01);    //Set End Date

            //设置总资金
            SetCash(TOTALCASH);             //Set Strategy Cash

            //select stocks to be traded.
            stockSelection();

            foreach (var val in _sd.Values)
            {
                Schedule.On(DateRules.EveryDay(val.Symbol), TimeRules.AfterMarketOpen(val.Symbol, -1), () =>
                {
                    Debug("EveryDay." + val.Symbol.ToString() + " initialize at: " + Time);
                    Transactions.CancelOpenOrders(val.Symbol);                  //close all open orders at the daily beginning
                });
            }

            SetWarmup(TimeSpan.FromDays(NUMDAYWU));
        }
Exemplo n.º 23
0
        public override void Initialize()
        {
            SetStartDate(2015, 1, 1);
            SetEndDate(DateTime.Now);
            SetCash(10000);

            foreach (var equity in _equities)
            {
                AddSecurity(SecurityType.Equity, equity, Resolution.Minute);
            }

            _s          = new int[_stocks.Length];
            _x0         = new int[_stocks.Length];
            _x1         = Enumerable.Repeat(1d / _stocks.Length, _stocks.Length).ToArray();
            _symbolData = new Dictionary <Symbol, SymbolData>();

            _bb     = new BollingerBands(_spy, 22, 1.05m, MovingAverageType.Simple);
            _spyWvf = new RollingWindow <decimal>(22);

            foreach (var stock in _stocks)
            {
                var closes      = new RollingWindow <decimal>(17 * 390);
                var dailyCloses = new RollingWindow <TradeBar>(29);

                var dailyConsolidator = new TradeBarConsolidator(TimeSpan.FromDays(1));
                dailyConsolidator.DataConsolidated += (sender, consolidated) => _symbolData[consolidated.Symbol].UpdateDaily(consolidated);
                SubscriptionManager.AddConsolidator(stock, dailyConsolidator);

                _symbolData.Add(stock, new SymbolData(closes, dailyCloses));
            }

            var spyDailyCloses = new RollingWindow <TradeBar>(28);

            var spyDailyConsolidator = new TradeBarConsolidator(TimeSpan.FromDays(1));

            spyDailyConsolidator.DataConsolidated += (sender, consolidated) => _symbolData[consolidated.Symbol].UpdateDaily(consolidated);
            SubscriptionManager.AddConsolidator(_spy, spyDailyConsolidator);
            _symbolData.Add(_spy, new SymbolData(null, spyDailyCloses));


            var vxxDailyConsolidator = new TradeBarConsolidator(TimeSpan.FromDays(1));

            vxxDailyConsolidator.DataConsolidated += (sender, consolidated) => _symbolData[consolidated.Symbol].UpdateDaily(consolidated);
            SubscriptionManager.AddConsolidator(_vxx, vxxDailyConsolidator);

            _symbolData.Add(_spy, new SymbolData(null, spyDailyCloses));

            Schedule.On(DateRules.EveryDay(), TimeRules.AfterMarketOpen("SPY", 15d), () =>
            {
                if (_symbolData[_spy].IsReady)
                {
                    return;
                }

                var vxxCloses = _symbolData[_vxx].DailyHistory.Select(tb => tb.Close);
                var vxxLows   = _symbolData[_vxx].DailyHistory.Select(tb => tb.Low);

                // William's VIX Fix indicator a.k.a. the Synthetic VIX
                var previousMax = vxxCloses.Take(28).Max();
                var previousWvf = 100 * (previousMax - vxxLows.Skip(27).First()) / previousMax;

                var max = vxxCloses.Skip(1).Max();
                var wvf = 100 * (max - vxxLows.Last()) / max;

                if (previousWvf < WvfLimit && wvf >= WvfLimit)
                {
                    SetHoldings(_vxx, 0);
                    SetHoldings(_xiv, 0.07);
                }
                else if (previousWvf > WvfLimit && wvf <= WvfLimit)
                {
                    SetHoldings(_vxx, 0.07);
                    SetHoldings(_xiv, 0);
                }
            });

            Schedule.On(DateRules.EveryDay(), TimeRules.AfterMarketOpen("SPY", 15d), () =>
            {
                if (_symbolData[_spy].IsReady)
                {
                    return;
                }

                var spyCloses = _symbolData[_spy].NDaysDailyHistory(22).Select(tb => tb.Close);
                var spyLows   = _symbolData[_spy].NDaysDailyHistory(22).Select(tb => tb.Low);
                var max       = spyCloses.Max();
                var wvf       = 100 * (max - spyLows.Last()) / max;
                _bb.Update(DateTime.Now, wvf);
                _spyWvf.Add(wvf);

                var rangeHigh = _spyWvf.Max() * 0.9m;

                var latestClose = _symbolData[_spy].NDaysDailyHistory(1).First().Close;
                var spy_higher_then_Xdays_back = latestClose > _symbolData[_spy].NDaysDailyHistory(3).First().Close;
                var spy_lower_then_longterm    = latestClose > _symbolData[_spy].NDaysDailyHistory(40).First().Close;
                var spy_lower_then_midterm     = latestClose > _symbolData[_spy].NDaysDailyHistory(14).First().Close;

                // Alerts Criteria
                var alert2 = !(_spyWvf[0] >= _bb.UpperBand && _spyWvf[0] >= rangeHigh) &&
                             (_spyWvf[1] >= _bb.UpperBand && _spyWvf[2] >= rangeHigh);

                if ((alert2 || spy_higher_then_Xdays_back) && (spy_lower_then_longterm || spy_lower_then_midterm))
                {
                    SetHoldings(_spy, 0.3);
                    SetHoldings(_shortSpy, 0);
                }
                else
                {
                    SetHoldings(_spy, 0);
                    SetHoldings(_shortSpy, 0.3);
                }
            });

            Schedule.On(DateRules.EveryDay(), TimeRules.AfterMarketOpen("SPY", 15d), () =>
            {
                if (_symbolData[_spy].IsReady)
                {
                    return;
                }

                var returns = new List <double[]>(); // 28?

                foreach (var stock in _stocks)
                {
                    _symbolData[stock].UpdateWeights();
                    returns.Add(_symbolData[stock].PercentReturn.Select(pr => (double)(pr / _symbolData[stock].Norm)).ToArray());
                }

                var retNorm    = _symbolData.Select(s => s.Value.Norm);
                var retNormMax = retNorm.Max();
                var epsFactor  = retNormMax > 0 ? 0.9m : 1.0m;
                var eps        = (double)(epsFactor * retNormMax);

                var constraints = new List <LinearConstraint>();

                constraints.Add(new LinearConstraint(Enumerable.Repeat(1.0, _stocks.Length).ToArray())
                {
                    ShouldBe = ConstraintType.EqualTo,
                    Value    = 1
                });

                constraints.Add(new LinearConstraint(retNorm.Select(x => (double)x).ToArray())
                {
                    ShouldBe = ConstraintType.GreaterThanOrEqualTo,
                    Value    = eps + eps * 0.01
                }); // Add and subtract small bounce to achieve inequality?

                constraints.Add(new LinearConstraint(retNorm.Select(x => (double)x).ToArray())
                {
                    ShouldBe = ConstraintType.LesserThanOrEqualTo,
                    Value    = eps - eps * 0.01
                }); // Add and subtract small bounce to achieve inequality?

                constraints.Add(new LinearConstraint(_stocks.Length)
                {
                    VariablesAtIndices = Enumerable.Range(0, _stocks.Length).ToArray(),
                    ShouldBe           = ConstraintType.GreaterThanOrEqualTo,
                    Value = 0
                });

                constraints.Add(new LinearConstraint(_stocks.Length)
                {
                    VariablesAtIndices = Enumerable.Range(0, _stocks.Length).ToArray(),
                    ShouldBe           = ConstraintType.LesserThanOrEqualTo,
                    Value = 1
                });

                var initialGuess = new double[_stocks.Length];
                var f            = new QuadraticObjectiveFunction(() => Variance(initialGuess, returns.ToMatrix()));

                var solver = new GoldfarbIdnani(f, constraints);
                solver.Minimize();

                var weights     = _x1;
                var totalWeight = weights.Sum();

                if (solver.Status == GoldfarbIdnaniStatus.Success)
                {
                    weights = solver.Solution;
                }

                for (var i = 0; i < _stocks.Length; i++)
                {
                    SetHoldings(_stocks[i], weights[i] / totalWeight);
                }
            });
        }
Exemplo n.º 24
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
                                                    ));
            }
        }