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);
        }
        /// <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(2007, 1, 1);
            SetEndDate(2010, 1, 1);

            _spy  = AddEquity("SPY", Resolution.Daily, leverage: 1).Symbol;
            _appl = AddEquity("AAPL", Resolution.Daily, leverage: 1);

            Schedule.On(DateRules.EveryDay(), TimeRules.Noon, () =>
            {
                Plot("Info", "Portfolio.MarginRemaining", Portfolio.MarginRemaining);
                Plot("Info", "Portfolio.Cash", Portfolio.Cash);
            });
        }
        public override void Initialize()
        {
            // CHANGE ME
            SetStartDate(2013, 10, 07); // Set Start Date
            SetEndDate(2013, 10, 11);   // Set End Date
            SetCash(100000);            // Set Strategy Cash

            UniverseSettings.Resolution = Resolution.Daily;
            _dataPath = Path.Combine(_rootDataPath,
                                     _securityType.SecurityTypeToLower(),
                                     _market,
                                     "universes",
                                     _resolution.ResolutionToLower(),
                                     _universeName);
            Directory.CreateDirectory(_dataPath);

            // CHANGE ME
            int step = 0;

            AddUniverse(coarse =>
            {
                step++;
                switch (step)
                {
                case 1:
                case 2:
                    return(new[]
                    {
                        QuantConnect.Symbol.Create("QQQ", SecurityType.Equity, Market.USA),
                        QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA)
                    });

                case 3:
                    return(Enumerable.Empty <Symbol>());

                case 4:
                case 5:
                    return(new[]
                    {
                        QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA),
                        QuantConnect.Symbol.Create("FB", SecurityType.Equity, Market.USA)
                    });

                default:
                    throw new Exception("Unexpected step count");
                }
            });

            Schedule.On(DateRules.EveryDay(), TimeRules.At(23, 0), SaveConstituentsUniverseDataToDisk);
        }
Example #4
0
        public override void Initialize()
        {
            SetStartDate(2013, 10, 07);
            SetEndDate(2013, 10, 11);
            SetCash(100000);

            foreach (var underlying in _underlyings)
            {
                AddEquity(underlying, Resolution.Minute);
            }

            // Every 15 min scan.
            Schedule.On(DateRules.EveryDay("SPY"), TimeRules.Every(TimeSpan.FromMinutes(15)), Scan);
        }
Example #5
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;
            // });
        }
Example #6
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);
            });
        }
        public void DateRulesToFunc()
        {
            var dateRules = new DateRules(new SecurityManager(
                                              new TimeKeeper(new DateTime(2015, 1, 1), DateTimeZone.Utc)), DateTimeZone.Utc);
            var first    = new DateTime(2015, 1, 10);
            var second   = new DateTime(2015, 1, 30);
            var dateRule = dateRules.On(first, second);
            var func     = dateRule.ToFunc();

            Assert.AreEqual(first, func(new DateTime(2015, 1, 1)));
            Assert.AreEqual(first, func(new DateTime(2015, 1, 5)));
            Assert.AreEqual(second, func(first));
            Assert.AreEqual(Time.EndOfTime, func(second));
            Assert.AreEqual(Time.EndOfTime, func(second));
        }
Example #8
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);
        }
Example #9
0
        public override void Initialize()
        {
            UniverseSettings.Resolution = Resolution.Daily;

            SetStartDate(2018, 1, 1);   //Set Start Date
            SetEndDate(2018, 1, 3);     //Set End Date
            SetCash(50000);             //Set Strategy Cash
            var spy = AddEquity("SPY", Resolution.Daily);

            // this add universe method accepts two parameters:
            // - coarse selection function: accepts an IEnumerable<CoarseFundamental> and returns an IEnumerable<Symbol>
            // - fine selection function: accepts an IEnumerable<FineFundamental> and returns an IEnumerable<Symbol>
            AddUniverse(CoarseSelectionFunction, FineSelectionFunction);
            Schedule.On(DateRules.MonthStart(spy.Symbol), TimeRules.At(0, 0),
                        () => { _rebalance = true; });
        }
        public override void Initialize()
        {
            SetStartDate(2013, 10, 8);
            SetEndDate(2013, 10, 9);
            SetCash(1000000);

            foreach (var root in roots)
            {
                // set our expiry filter for this futures chain
                AddFuture(root, Resolution.Minute).SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
            }

            SetBenchmark(d => 1000000);

            Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromHours(1)), MakeHistoryCall);
        }
        /// <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);

            AddEquity("SPY");
            AddForex("EURUSD", Resolution.Hour);

            Schedule.On(DateRules.EveryDay(), TimeRules.Noon, () =>
            {
                Liquidate();
                foreach (var ticker in new[] { "SPY", "EURUSD" })
                {
                    PlaceTrade(ticker);
                }
            });
        }
        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());
        }
Example #13
0
        public DateTime Date(DateRules rules)
        {
            // apply rule restrictions
            if (rules == DateRules.Within1Year)
            {
                GenFu.MinDateTime = DateTime.Now.AddYears(-1);
                GenFu.MaxDateTime = DateTime.Now.AddYears(1);
            }

            if (rules == DateRules.Within10Years)
            {
                GenFu.MinDateTime = DateTime.Now.AddYears(-10);
                GenFu.MaxDateTime = DateTime.Now.AddYears(10);
            }

            if (rules == DateRules.Within25years)
            {
                GenFu.MinDateTime = DateTime.Now.AddYears(-25);
                GenFu.MaxDateTime = DateTime.Now.AddYears(25);
            }

            if (rules == DateRules.Within50Years)
            {
                GenFu.MinDateTime = DateTime.Now.AddYears(-50);
                GenFu.MaxDateTime = DateTime.Now.AddYears(50);
            }

            if (rules == DateRules.Within100Years)
            {
                GenFu.MinDateTime = DateTime.Now.AddYears(-100);
                GenFu.MaxDateTime = DateTime.Now.AddYears(100);
            }

            if (rules == DateRules.FutureDates)
            {
                GenFu.MinDateTime = DateTime.Now;
            }

            if (rules == DateRules.PastDate)
            {
                GenFu.MaxDateTime = DateTime.Now;
            }

            return(DateTimeFill(GenFu.MinDateTime, GenFu.MaxDateTime));
        }
Example #14
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);
                }
                    );
            }
        }
Example #15
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);
        }
        /// <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(2018, 04, 04);
            SetEndDate(2018, 04, 06);

            SetExecution(new ImmediateExecutionModel());
            Settings.MinimumOrderMarginPortfolioPercentage = 0.01m;
            SetPortfolioConstruction(new EqualWeightingAlphaStreamsPortfolioConstructionModel());

            SetUniverseSelection(new ScheduledUniverseSelectionModel(
                                     DateRules.EveryDay(),
                                     TimeRules.Midnight,
                                     SelectAlphas,
                                     new UniverseSettings(UniverseSettings)
            {
                SubscriptionDataTypes = new List <Tuple <Type, TickType> >
                {
                    new(typeof(AlphaStreamsPortfolioState), TickType.Trade)
                },
Example #17
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(2010, 1, 1);
            SetEndDate(2019, 1, 1);

            var tickers = new List <string> {
                "AAPL", "AMZN", "MSFT", "IBM", "FB", "QQQ",
                "IWM", "BAC", "BNO", "AIG", "UW", "WM"
            };

            _securities    = new List <Security>();
            _customSymbols = new List <Symbol>();

            foreach (var ticker in tickers)
            {
                var equity = AddEquity(ticker, Resolution.Hour);
                _securities.Add(equity);

                _customSymbols.Add(
                    AddData <SmartInsiderIntention>(equity.Symbol, Resolution.Daily).Symbol);
                _customSymbols.Add(
                    AddData <SmartInsiderTransaction>(equity.Symbol, Resolution.Daily).Symbol);
            }

            Schedule.On(DateRules.EveryDay(), TimeRules.At(16, 0), () =>
            {
                foreach (var slice in History(_customSymbols, TimeSpan.FromDays(5)))
                {
                    _historySymbolCount += slice.Count;
                }

                foreach (var security in _securities)
                {
                    SmartInsiderIntention intention     = security.Data.Get <SmartInsiderIntention>();
                    SmartInsiderTransaction transaction = security.Data.Get <SmartInsiderTransaction>();

                    if (!security.HoldStock && intention != null && transaction != null)
                    {
                        SetHoldings(security.Symbol, 1d / _securities.Count);
                    }
                }
            });
        }
Example #18
0
        public override void Initialize()
        {
            SetStartDate(2010, 1, 1);
            SetEndDate(DateTime.Now.Date);
            SetCash(25000);

            _baseWeight = 1m / _securities.Count;
            _downsideProtectionModels = new Dictionary <Symbol, DownsideProtectionModel>();

            AddSecurity(SecurityType.Equity, "SPY", Resolution.Daily);
            AddSecurity(SecurityType.Equity, _rfAsset, Resolution.Daily);

            foreach (var security in _securities)
            {
                AddSecurity(SecurityType.Equity, security, Resolution.Daily);
                var dpm = new DownsideProtectionModel(security.Value);
                RegisterIndicator(security, dpm, Resolution.Daily);
                _downsideProtectionModels[security] = dpm;
            }

            var history = History(TimeSpan.FromDays(252), Resolution.Daily);

            foreach (var tb in history)
            {
                foreach (var security in _securities)
                {
                    _downsideProtectionModels[security].Update(tb[security]);
                }
            }

            Schedule.On(DateRules.MonthStart(), TimeRules.At(12, 0), () =>
            {
                var rfAssetTarget = 0m;
                foreach (var dpm in _downsideProtectionModels)
                {
                    SetHoldings(dpm.Key, dpm.Value.Exposure * _baseWeight);
                    rfAssetTarget += dpm.Value.NonAssetExposure;
                }

                SetHoldings(_rfAsset, rfAssetTarget * _baseWeight);
            });
        }
Example #19
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());
        }
Example #20
0
        public override void Initialize()
        {
            SetStartDate(2017, 01, 01);
            SetEndDate(2017, 02, 01);

            SetUniverseSelection(new ScheduledUniverseSelectionModel(
                                     DateRules.EveryDay(),
                                     TimeRules.At(9, 31),
                                     SelectSymbolsAt
                                     ));

            Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromHours(6)), () =>
            {
                _scheduleEventEveryCallCount++;
                if (Time.Hour != 0 &&
                    Time.Hour != 6 &&
                    Time.Hour != 12 &&
                    Time.Hour != 18)
                {
                    throw new Exception($"Unexpected every 6 hours scheduled event time: {Time}");
                }
            });

            Schedule.On(DateRules.EveryDay(), TimeRules.Noon, () =>
            {
                _scheduleEventNoonCallCount++;
                if (Time.Hour != 12)
                {
                    throw new Exception($"Unexpected Noon scheduled event time: {Time}");
                }
            });

            Schedule.On(DateRules.EveryDay(), TimeRules.Midnight, () =>
            {
                _scheduleEventMidnightCallCount++;
                if (Time.Hour != 0)
                {
                    throw new Exception($"Unexpected Midnight scheduled event time: {Time}");
                }
            });
        }
Example #21
0
        public static DateTime Date(DateRules rules)
        {
            // apply rule restrictions
            if (rules == DateRules.Within1Year)
            {
                GenFu.MinDateTime = DateTime.Now.AddYears(-1);
                GenFu.MaxDateTime = DateTime.Now.AddYears(1);
            }

            if (rules == DateRules.Within10Years)
            {
                GenFu.MinDateTime = DateTime.Now.AddYears(-10);
                GenFu.MaxDateTime = DateTime.Now.AddYears(10);
            }

            if (rules == DateRules.Within25years)
            {
                GenFu.MinDateTime = DateTime.Now.AddYears(-25);
                GenFu.MaxDateTime = DateTime.Now.AddYears(25);
            }

            if (rules == DateRules.Within50Years)
            {
                GenFu.MinDateTime = DateTime.Now.AddYears(-50);
                GenFu.MaxDateTime = DateTime.Now.AddYears(50);
            }

            if (rules == DateRules.Within100Years)
            {
                GenFu.MinDateTime = DateTime.Now.AddYears(-100);
                GenFu.MaxDateTime = DateTime.Now.AddYears(100);
            }

            if (rules == DateRules.FutureDates)
                GenFu.MinDateTime = DateTime.Now;

            if (rules == DateRules.PastDate)
                GenFu.MaxDateTime = DateTime.Now;

            return DateTimeFill(GenFu.MinDateTime, GenFu.MaxDateTime);
        }
Example #22
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);
        }
        public override void Initialize()
        {
            SetStartDate(2020, 9, 1);
            SetEndDate(2020, 9, 2);
            SetCash(100000);

            numberOfSymbols     = 2000;
            numberOfSymbolsFine = 1000;
            SetUniverseSelection(new FineFundamentalUniverseSelectionModel(CoarseSelectionFunction, FineSelectionFunction));

            SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());

            SetExecution(new ImmediateExecutionModel());

            queue       = new Queue <Symbol>();
            dequeueSize = 100;

            AddEquity("SPY", Resolution.Minute);
            Schedule.On(DateRules.EveryDay("SPY"), TimeRules.At(0, 0), FillQueue);
            Schedule.On(DateRules.EveryDay("SPY"), TimeRules.Every(TimeSpan.FromMinutes(60)), TakeFromQueue);
        }
Example #24
0
        private static DateRules GetDateRules()
        {
            var timeKeeper            = new TimeKeeper(DateTime.Today, new List <DateTimeZone>());
            var manager               = new SecurityManager(timeKeeper);
            var securityExchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.USA, null, SecurityType.Equity);
            var config = new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Daily, TimeZones.NewYork, TimeZones.NewYork, true, false, false);

            manager.Add(
                Symbols.SPY,
                new Security(
                    securityExchangeHours,
                    config,
                    new Cash(Currencies.USD, 0, 1m),
                    SymbolProperties.GetDefault(Currencies.USD),
                    ErrorCurrencyConverter.Instance
                    )
                );
            var rules = new DateRules(manager);

            return(rules);
        }
Example #25
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());
        }
        public override void Initialize()
        {
            UniverseSettings.Resolution = Resolution.Daily;

            SetStartDate(2014, 03, 24);
            SetEndDate(2014, 04, 06);
            SetCash(50000);

            AddUniverse(CoarseSelectionFunction);

            // schedule an event at 10 AM every day
            Schedule.On(
                DateRules.EveryDay(),
                TimeRules.At(10, 0),
                () =>
            {
                foreach (var symbol in _coarsePrices.Keys)
                {
                    if (Securities.ContainsKey(symbol))
                    {
                        // If the coarse price is emitted at midnight for the same date, we would have look-ahead bias
                        // i.e. _coarsePrices[symbol] would be the closing price of the current day,
                        // which we obviously cannot know at 10 AM :)
                        // As the coarse data is now emitted for the previous day, there is no look-ahead bias:
                        // _coarsePrices[symbol] and Securities[symbol].Price will have the same value (equal to the previous closing price)
                        // for the backtesting period, so we expect this algorithm to make zero trades.
                        if (_coarsePrices[symbol] > Securities[symbol].Price)
                        {
                            SetHoldings(symbol, 1m / NumberOfSymbols);
                        }
                        else
                        {
                            Liquidate(symbol);
                        }
                    }
                }
            }
                );
        }
Example #27
0
        /// <summary>
        /// Initialize your algorithm and add desired assets.
        /// </summary>
        public override void Initialize()
        {
            //SetStartDate(2013, 11, 1);
            //SetEndDate(2018, 9, 30);

            SetStartDate(2015, 5, 1);
            SetEndDate(2015, 7, 30);
            SetCash(1000000000);

            foreach (string symbol in S_AND_P_500_SYMOLS)
            {
                var option = AddOption(symbol, Resolution.Daily, null, false);
                option.PriceModel = OptionPriceModels.BlackScholes();

                // set our strike/expiry filter for this option chain
                //option.SetFilter((universe) => universe.WeeklysOnly().Expiration(TimeSpan.FromDays(0), TimeSpan.FromDays(7)));
                //option.SetFilter(TimeSpan.FromDays(0), TimeSpan.FromDays(7));

                if (!this.registerForEOD)
                {
                    this.registerForEOD = true;

                    // Schedule an event to fire every trading day for a security
                    // The time rule here tells it to fire 10 minutes before market close
                    Schedule.On(DateRules.EveryDay(option.Symbol), TimeRules.BeforeMarketClose(option.Symbol, 15), () =>
                    {
                        Log("EveryDay 15 min before markets close: Fired at: " + Time);
                        this.LiquidateExpiredOptions();
                    });
                }
            }

            // set the warm-up period for the pricing model
            SetWarmup(TimeSpan.FromDays(15));

            // set the benchmark to be the initial cash
            SetBenchmark((d) => 1000000000);
        }
Example #28
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));
        }
        /// <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());
        }
        /// <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 a single day of the week
            Schedule.On(DateRules.Every(DayOfWeek.Wednesday), TimeRules.At(12, 0), () =>
            {
                Log("Wed at 12pm: 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?
            });
        }
Example #31
0
        private static DateRules GetDateRules()
        {
            var timeKeeper = new TimeKeeper(DateTime.Today, new List <DateTimeZone>());
            var manager    = new SecurityManager(timeKeeper);

            // Add SPY for Equity testing
            var securityExchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.USA, null, SecurityType.Equity);
            var config = new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Daily, TimeZones.NewYork, TimeZones.NewYork, true, false, false);

            manager.Add(
                Symbols.SPY,
                new Security(
                    securityExchangeHours,
                    config,
                    new Cash(Currencies.USD, 0, 1m),
                    SymbolProperties.GetDefault(Currencies.USD),
                    ErrorCurrencyConverter.Instance,
                    RegisteredSecurityDataTypesProvider.Null,
                    new SecurityCache()
                    )
                );

            // Add BTC for Crypto testing
            securityExchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.Bitfinex, Symbols.BTCUSD, SecurityType.Crypto);
            config = new SubscriptionDataConfig(typeof(TradeBar), Symbols.BTCUSD, Resolution.Daily, TimeZones.NewYork, TimeZones.NewYork, true, false, false);
            manager.Add(
                Symbols.BTCUSD,
                new Security(
                    securityExchangeHours,
                    config,
                    new Cash(Currencies.USD, 0, 1m),
                    SymbolProperties.GetDefault(Currencies.USD),
                    ErrorCurrencyConverter.Instance,
                    RegisteredSecurityDataTypesProvider.Null,
                    new SecurityCache()
                    )
                );

            // Add EURUSD for Forex testing
            securityExchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.FXCM, Symbols.EURUSD, SecurityType.Forex);
            config = new SubscriptionDataConfig(typeof(TradeBar), Symbols.EURUSD, Resolution.Daily, TimeZones.NewYork, TimeZones.NewYork, true, false, false);
            manager.Add(
                Symbols.EURUSD,
                new Security(
                    securityExchangeHours,
                    config,
                    new Cash(Currencies.USD, 0, 1m),
                    SymbolProperties.GetDefault(Currencies.USD),
                    ErrorCurrencyConverter.Instance,
                    RegisteredSecurityDataTypesProvider.Null,
                    new SecurityCache()
                    )
                );

            // Add Fut_SPY_Feb19_2016 for testing
            securityExchangeHours = MarketHoursDatabase.FromDataFolder().GetExchangeHours(Market.CME, Symbols.Fut_SPY_Feb19_2016, SecurityType.Future);
            config = new SubscriptionDataConfig(typeof(TradeBar), Symbols.Fut_SPY_Feb19_2016, Resolution.Daily, TimeZones.NewYork, TimeZones.NewYork, true, false, false);
            manager.Add(
                Symbols.Fut_SPY_Feb19_2016,
                new Security(
                    securityExchangeHours,
                    config,
                    new Cash(Currencies.USD, 0, 1m),
                    SymbolProperties.GetDefault(Currencies.USD),
                    ErrorCurrencyConverter.Instance,
                    RegisteredSecurityDataTypesProvider.Null,
                    new SecurityCache()
                    )
                );

            var rules = new DateRules(manager, TimeZones.NewYork);

            return(rules);
        }