/// <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; });
        }
Beispiel #2
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;
                }
            });
        }
Beispiel #3
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);
            }
                );
        }
Beispiel #4
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);

            _spy = AddEquity("SPY").Symbol;

            var test     = 0;
            var dateRule = DateRules.EveryDay(_spy);

            var aEventCount = 0;
            var bEventCount = 0;
            var cEventCount = 0;

            // we add each twice and assert the order in which they are added is also respected for events at the same time
            for (var i = 0; i < 2; i++)
            {
                var id = i;
                Schedule.On(dateRule, TimeRules.At(9, 25), (name, time) =>
                {
                    // for id 0 event count should always be 0, for id 1 should be 1
                    if (aEventCount != id)
                    {
                        throw new Exception($"Scheduled event triggered out of order: {Time} expected id {id} but was {aEventCount}");
                    }
                    aEventCount++;
                    // goes from 0 to 1
                    aEventCount %= 2;
                    AssertScheduledEventTime();
                    Debug($"{Time} :: Test: {test}"); test++;
                });
                Schedule.On(dateRule, TimeRules.BeforeMarketClose(_spy, 5), (name, time) =>
                {
                    // for id 0 event count should always be 0, for id 1 should be 1
                    if (bEventCount != id)
                    {
                        throw new Exception($"Scheduled event triggered out of order: {Time} expected id {id} but was {bEventCount}");
                    }
                    bEventCount++;
                    // goes from 0 to 1
                    bEventCount %= 2;
                    AssertScheduledEventTime();
                    Debug($"{Time} :: Test: {test}"); test++;
                });
                Schedule.On(dateRule, TimeRules.At(16, 5), (name, time) =>
                {
                    // for id 0 event count should always be 0, for id 1 should be 1
                    if (cEventCount != id)
                    {
                        throw new Exception($"Scheduled event triggered out of order: {Time} expected id {id} but was {cEventCount}");
                    }
                    cEventCount++;
                    // goes from 0 to 1
                    cEventCount %= 2;
                    AssertScheduledEventTime();
                    Debug($"{Time} :: Test: {test}"); test = 0;
                });
            }
        }
Beispiel #5
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?
            });
        }
Beispiel #6
0
        public override void Initialize()
        {
            SetStartDate(2014, 6, 5);
            SetEndDate(2014, 6, 9);

            _twx = AddEquity("TWX", Resolution.Minute, extendedMarketHours: true).Symbol;
            Schedule.On(DateRules.EveryDay(_twx), TimeRules.Every(TimeSpan.FromHours(1)), PlotPrice);
        }
Beispiel #7
0
        public override void Initialize()
        {
            // backtest parameters
            // we have data for these dates locally
            var start = new DateTime(2020, 01, 01, 09, 30, 0);

            SetStartDate(start);
            SetEndDate(start.AddDays(30));
            SetCash(100000);

            // set security and option universe for tradebar
            _spy = AddEquity("SPY", Resolution.Minute);
            var option = AddOption("SPY", Resolution.Minute);

            // set filter on option universe
            _optionSymbol = option.Symbol;
            option.SetFilter(universe =>
                             from symbol in universe
                             .WeeklysOnly().Expiration(TimeSpan.Zero, TimeSpan.FromDays(10))
                             where symbol.ID.OptionRight != OptionRight.Put
                             select symbol);

            // use the underlying equity as the benchmark
            SetBenchmark("SPY");

            // Creates a Rolling Window indicator to hold 2 TradeBars
            _window = new RollingWindow <TradeBar>(2);

            // Creates a Rolling Window indicator to hold 1 option contract
            _optionWindow = new RollingWindow <OptionContract>(1);

            // create RSI indicator
            fast = new RelativeStrengthIndex("SPY", 14, MovingAverageType.Wilders);

            // Create a Rolling Window to keep two Indicator Data Points
            _rsiLag = new RollingWindow <IndicatorDataPoint>(2);

            // define our 5 minute trade bar consolidator. we can access the 5 minute bar
            // from the DataConsolidated events
            var minConsolidator = new TradeBarConsolidator(TimeSpan.FromMinutes(5));

            // attach our event handler. the event handler is a function that will be called each time we produce
            // a new consolidated piece of data.
            minConsolidator.DataConsolidated += OnFiveMinutes;

            // this call adds our daily consolidator to the manager to receive updates from the engine
            SubscriptionManager.AddConsolidator("SPY", minConsolidator);

            // we need to manually register these indicators for automatic updates
            RegisterIndicator("SPY", fast, minConsolidator);

            Schedule.On(DateRules.EveryDay(), TimeRules.BeforeMarketClose(_spy.Symbol, 4), () =>
            {
                CloseOpenPositions(_spy);
            });

            SetWarmUp(TimeSpan.FromDays(100));
        }
        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);
        }
        /// <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, 09);
            SetCash(100000);

            AddEquity("SPY", Resolution.Minute, extendedMarketHours: true, fillDataForward: false);

            Schedule.On("RunHistoryCall", DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromHours(1)), RunHistoryCall);
        }
        public override void Initialize()
        {
            SetStartDate(2018, 3, 26);
            SetEndDate(2018, 4, 10);
            foreach (var symbol in _symbols)
            {
                AddSecurity(symbol, Resolution.Minute);
            }

            Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromHours(1)), MakeHistoryCall);
        }
Beispiel #11
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);
     }
 }
 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);
 }
        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);
        }
Beispiel #14
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);
        }
        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);
            });
        }
Beispiel #17
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;
            // });
        }
Beispiel #18
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);
            });
        }
Beispiel #19
0
        public void TimeTriggeredDoesNotReturnPastTimes()
        {
            // Schedule our universe for 12PM each day
            var universe = new ScheduledUniverse(
                _dateRules.EveryDay(), _timeRules.At(12, 0),
                (time =>
            {
                return(new List <Symbol>());
            })
                );

            // For this test; start time will be 1/5/2000 wednesday at 3PM
            // which is after 12PM, this case will ensure we don't have a 1/5 12pm event
            var start = new DateTime(2000, 1, 5, 15, 0, 0);
            var end   = new DateTime(2000, 1, 10);

            // Get our trigger times, these will be in UTC
            var triggerTimesUtc = universe.GetTriggerTimes(start.ConvertToUtc(_timezone), end.ConvertToUtc(_timezone), MarketHoursDatabase.AlwaysOpen);

            // Setup expectDate variables to assert behavior
            // We expect the first day to be 1/6 12PM
            var expectedDate = new DateTime(2000, 1, 6, 12, 0, 0);

            foreach (var time in triggerTimesUtc)
            {
                // Convert our UTC time back to our timezone
                var localTime = time.ConvertFromUtc(_timezone);

                // Assert we aren't receiving dates prior to our start
                Assert.IsTrue(localTime > start);

                // Verify the date
                Assert.AreEqual(expectedDate, localTime);
                expectedDate = expectedDate.AddDays(1);
            }
        }
        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);
                }
            });
        }
        /// <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)
                },
Beispiel #23
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);
                    }
                }
            });
        }
Beispiel #24
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}");
                }
            });
        }
        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);
        }
        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);
                        }
                    }
                }
            }
                );
        }
Beispiel #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);
        }
Beispiel #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));
        }
        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);
                }
            });
        }
Beispiel #30
0
        public override void Initialize()
        {
            //set trade period
            SetStartDate(2014, 6, 1);  //Set Start Date
            SetEndDate(2018, 6, 1);    //Set End Date

            //set total capital
            SetCash(TOTALCASH);             //Set Strategy Cash

            SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash);

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

            DateTimeZone TimeZone = DateTimeZoneProviders.Tzdb["America/New_York"];

            Schedule.On(DateRules.EveryDay(), TimeRules.At(9, 40, TimeZone), () =>
            {
                List <SymbolData> ranks = new List <SymbolData>();
                decimal tmp             = 0;

                foreach (var val in _sd.Values)
                {
                    if (!val.Security.Exchange.DateIsOpen(Time))
                    {
                        continue;
                    }
                    else
                    {
                        Transactions.CancelOpenOrders(val.Symbol);      //close all open orders at the daily beginning
                        if (!val.IsReady)
                        {
                            continue;
                        }
                    }

                    var tradeBarHistory = History <TradeBar>(val.Symbol, TimeSpan.FromDays(HS), Resolution.Daily);

                    //Calculate LSma
                    foreach (TradeBar tradeBar in tradeBarHistory)
                    {
                        tmp = tmp + tradeBar.Close;
                        //Debug("His_bar time: " + tradeBar.Time);
                    }
                    if (tradeBarHistory.Count() > 0)
                    {
                        val.LSma = tmp / tradeBarHistory.Count();
                    }
                    else
                    {
                        continue;
                    }

                    //Calculate SSma
                    int i = 0;
                    int count;
                    tmp = 0;
                    if (tradeBarHistory.Count() - WD2 > 0)
                    {
                        i     = tradeBarHistory.Count() - WD2;
                        count = WD2;
                    }
                    else
                    {
                        count = tradeBarHistory.Count();
                    }
                    for (int j = i; j < tradeBarHistory.Count(); j++)
                    {
                        tmp = tmp + tradeBarHistory.ElementAt(j).Close;
                    }
                    val.SSma = tmp / count;

                    //System.Console.WriteLine("Count: " + tradeBarHistory.Count());

                    if (tradeBarHistory.Count() - WD1 > 0)
                    {
                        tmp = tradeBarHistory.ElementAt(tradeBarHistory.Count() - 1).Close
                              - tradeBarHistory.ElementAt(tradeBarHistory.Count() - 1 - WD1).Close;
                        if (tradeBarHistory.ElementAt(tradeBarHistory.Count() - 1 - WD1).Close > 0)
                        {
                            tmp = tmp /
                                  tradeBarHistory.ElementAt(tradeBarHistory.Count() - 1 - WD1).Close;
                        }
                        else
                        {
                            tmp = tmp / ZERO;
                        }
                    }
                    else
                    {
                        tmp = tradeBarHistory.ElementAt(tradeBarHistory.Count() - 1).Close
                              - tradeBarHistory.ElementAt(0).Close;
                        if (tradeBarHistory.ElementAt(0).Close > 0)
                        {
                            tmp = tmp / tradeBarHistory.ElementAt(0).Close;
                        }
                        else
                        {
                            tmp = tmp / ZERO;
                        }
                    }
                    val.Return = tmp;
                    ranks.Add(val);
                }

                ranks.Sort(delegate(SymbolData x, SymbolData y) { return(y.CompareTo(x)); });

                for (int i = 0; i < ranks.Count; i++)
                {
                    if (i < TOP_K && ranks.ElementAt(i).SSma - ranks.ElementAt(i).LSma > 0)
                    {
                        ranks.ElementAt(i).wt = LEVERAGE / TOP_K;
                    }
                    else
                    {
                        ranks.ElementAt(i).wt = 0;
                    }
                }

                reweight(ranks);
            });
        }