public override void Initialize() { SetStartDate(2007, 6, 1); SetEndDate(DateTime.Now.Date.AddDays(-1)); SetCash(10000); AddSecurity(SecurityType.Equity, spy, Resolution.Minute); foreach (var security in securities) { AddSecurity(SecurityType.Equity, security, Resolution.Minute); Securities[security].SetLeverage(8m); } Schedule.On(DateRules.Every(DayOfWeek.Tuesday), TimeRules.At(11, 0), () => { foreach (var security in hedges.Where(s => Securities[s].Price > 0m)) { SetHoldings(security, _leverage * 1.06m / (hedges.Where(s => Securities[s].Price > 0m).Count())); } foreach (var security in riskyAssets.Where(s => Securities[s].Price > 0m)) { SetHoldings(security, _leverage * 0.27m / (riskyAssets.Where(s => Securities[s].Price > 0m).Count())); } }); }
public override void Initialize() { SetStartDate(2001, 1, 1); SetEndDate(DateTime.Now); SetCash(10000); mean = SMA(symbol, n, Resolution.Daily); sigma = STD(symbol, n, Resolution.Daily); var history = History(symbol, TimeSpan.FromDays(150), Resolution.Daily); foreach (var tb in history) { mean.Update(tb.EndTime, tb.Close); sigma.Update(tb.EndTime, tb.Close); } Schedule.On(DateRules.EveryDay(), TimeRules.At(11, 0), () => { var z = (Securities[symbol].Price - mean) / sigma; var target = 2.0 / (1 + Math.Exp((double)(-1.2m * z))); if (z >= -4 && z <= 4) { SetHoldings(symbol, target); SetHoldings("TLT", 2 - target); } else { SetHoldings(symbol, 0); SetHoldings("TLT", 1); } }); }
/// <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? }); }
/// <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; }); } }
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() { UniverseSettings.Resolution = globalResolution; SetStartDate(1998, 1, 1); //Set Start Date SetEndDate(2018, 9, 1); //Set End Date SetCash(1000000); //Set Strategy Cash var spy = AddEquity("SPY", Resolution.Daily); Schedule.On(DateRules.MonthStart("SPY"), TimeRules.At(0, 0), Rebalance); Rebalance(); }
public override void Initialize() { SetStartDate(2013, 10, 7); SetEndDate(2013, 10, 14); AddEquity("SPY", Resolution.Daily); // Set TrainingMethod to be executed immediately Train(TrainingMethod); // Set TrainingMethod to be executed at 8:00 am every Sunday Train(DateRules.Every(DayOfWeek.Sunday), TimeRules.At(8, 0), TrainingMethod); }
protected override void ScheduleBuySell() { // Schedule a purchase of this contract at Noon Schedule.On(DateRules.Today, TimeRules.Noon, () => { Ticket = MarketOrder(DcOption, 1); }); // Schedule liquidation at 6PM Schedule.On(DateRules.Today, TimeRules.At(18, 0, 0), () => { Liquidate(); }); }
protected virtual void ScheduleBuySell() { // Schedule a purchase of this contract tomorrow at 1AM Schedule.On(DateRules.Tomorrow, TimeRules.At(1, 0, 0), () => { Ticket = MarketOrder(DcOption, 1); }); // Schedule liquidation tomorrow at 6PM Schedule.On(DateRules.Tomorrow, TimeRules.At(18, 0, 0), () => { Liquidate(); }); }
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); }
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() { 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; }); }
/// <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); } } }); }
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); }); }
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); } } } } ); }
public override void Initialize() { SetStartDate(2006, 5, 1); //Set Start Date SetEndDate(2015, 5, 1); //Set End Date //Set up total capital SetCash(TOTALCASH); //Set Strategy Cash SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin); //select stocks to be traded. stockSelection(); DateTimeZone TimeZone = DateTimeZoneProviders.Tzdb["America/New_York"]; Schedule.On(DateRules.EveryDay(), TimeRules.At(9, 40, TimeZone), () => { foreach (var val in _sd.Values) { if (!val.Security.Exchange.DateIsOpen(Time)) { return; } else { Transactions.CancelOpenOrders(val.Symbol); //close all open orders at the daily beginning if (!val.IsReady) { return; } } } Dictionary <Symbol, IEnumerable <TradeBar> > bdic = new Dictionary <Symbol, IEnumerable <TradeBar> >(); int count = -1; foreach (var val in _sd.Values) { IEnumerable <TradeBar> bars = History <TradeBar>(val.Symbol, TimeSpan.FromDays(HS), Resolution.Daily); //Debug(Time + " " + val.Symbol + " " + bars.Count()); if (bars.Count() != count && count != -1) { return; } count = bars.Count(); bdic.Add(val.Symbol, bars); } //if less than 2 days, STD will be 0. if (count < 2) { return; } decimal[] comb_price_past_window = new decimal[count]; for (int i = 0; i < count; i++) { comb_price_past_window[i] = 0; } for (int i = 0; i < count; i++) { int j = 0; Nullable <DateTime> time = null; foreach (KeyValuePair <Symbol, IEnumerable <TradeBar> > kv in bdic) { if (j > 0) { if (!time.Equals(kv.Value.ElementAt(i).Time)) { return; } } j++; time = kv.Value.ElementAt(i).Time; comb_price_past_window[i] = comb_price_past_window[i] + _sd[kv.Key].Weight * kv.Value.ElementAt(i).Close; } } decimal meanPrice = comb_price_past_window.Average(); double sum = comb_price_past_window.Sum(d => Math.Pow((double)(d - meanPrice), 2)); decimal stdPrice = (decimal)Math.Sqrt(sum / comb_price_past_window.Count()); decimal comb_price = 0; foreach (var val in _sd.Values) { comb_price = comb_price + val.Weight * val.Security.Close; } //Debug("Debug: " + Time + ": std: " + stdPrice); decimal h = (comb_price - meanPrice) / stdPrice; //update positions foreach (var val in _sd.Values) { decimal current_position = val.Security.Holdings.Quantity; //Debug("Debug: Time: " + Time + " Symbol: " + val.Symbol + //" current_position:" + current_position); decimal new_position = USHARE * -1 * h * val.Weight; //Debug("Debug: Time: " + Time + " Symbol: " + val.Symbol + //" new_position:" + current_position); MarketOrder(val.Symbol, new_position - current_position); } }); }
// TODO: check volatilitymodel https://github.com/QuantConnect/Lean/blob/master/Common/Securities/RelativeStandardDeviationVolatilityModel.cs public override void Initialize() { SetStartDate(2016, 1, 1); SetEndDate(2016, 4, 1); SetCash(3000); SetBrokerageMessageHandler(new CustomBrokerageMessageHandler(this)); var allInputs = new List <double[]>(); var allOutputs = new List <int>(); var allWeights = new List <double>(); foreach (var symbol in Symbols) { AddForex(symbol, _dataResolution, Market.Oanda, false, 1m); Securities[symbol].TransactionModel = new OandaTransactionModel(); //Securities[symbol].SlippageModel = new ConstantSlippageModel(0m); SetBrokerageModel(BrokerageName.OandaBrokerage); /************ TRAINING ************/ var trainingResolution = Resolution.Minute; /*var slowT = HMA(symbol, 28, trainingResolution, Field.Close); * var slowSlopeT = new InstantTrend(symbol, 5).Of(slowT); * var returnT = LOGR(symbol, 3, trainingResolution, Field.Close); * var returnSlopeT = LSMA(symbol, 5, trainingResolution).Of(returnT);*/ var consolidatorT = new QuoteBarConsolidator(TimeSpan.FromMinutes(15)); var stochT = new Stochastic(symbol, 14, 3, 3); var stochTMA = new HullMovingAverage(symbol, 3).Of(stochT); var emaT = new ExponentialMovingAverage(symbol, 40); RegisterIndicator(symbol, stochT, consolidatorT); RegisterIndicator(symbol, emaT, consolidatorT); SubscriptionManager.AddConsolidator(symbol, consolidatorT); var historyT = History <QuoteBar>(symbol, TimeSpan.FromDays(500), trainingResolution); var quoteBars = new List <QuoteBar>(); var stochs = new List <double>(); var rollingStochs = new RollingWindow <double>(1000); var stochsMA = new List <double>(); var emas = new List <double>(); var stochCount = new List <double>(); var stochAverage = new List <double>(); //consolidatorT.DataConsolidated += (sender, args) => quoteBars.Add(args); stochTMA.Updated += (sender, args) => { if (!stochTMA.IsReady || !emaT.IsReady) { return; } quoteBars.Add((QuoteBar)consolidatorT.Consolidated); stochs.Add((double)stochT.Current.Value); rollingStochs.Add((double)args.Value); stochsMA.Add((double)args.Value); emas.Add((double)emaT.Current.Value); var filtered = rollingStochs.TakeWhile((s) => args.Value > 50 ? s > 50 : args.Value < 50 ? s < 50 : false); stochCount.Add(filtered.Count()); try { stochAverage.Add(filtered.Average()); } catch (Exception ex) { stochAverage.Add(0); } }; foreach (var bar in historyT) { consolidatorT.Update(bar); } Console.WriteLine("{0} {1} {2} {3} {4}", quoteBars.Count, stochs.Count, stochCount.Count, stochAverage.Count, emas.Count); var inputs = new List <double[]>(); var outputs = new List <int>(); var weights = new List <double>(); for (var i = 1; i < quoteBars.Count; i++) { var longTarget = quoteBars[i].Close + (30m / 10000m); var longStop = quoteBars[i].Close - (10m / 10000m); var shortTarget = quoteBars[i].Close - (30m / 10000m); var shortStop = quoteBars[i].Close + (10m / 10000m); var longSetup = stochs[i] >= 35 && stochsMA[i] > stochsMA[i - 1] && (double)quoteBars[i].Close > emas[i]; var shortSetup = stochs[i] <= 65 && stochs[i] > 0 && stochsMA[i] < stochsMA[i - 1] && (double)quoteBars[i].Close < emas[i]; if (!longSetup && !shortSetup) { continue; } for (var j = i + 1; j < quoteBars.Count; j++) { var current = quoteBars[j]; if (current.High >= longTarget && current.Low > longStop && longSetup) { inputs.Add(new double[] { stochAverage[i], stochCount[i], (double)quoteBars[i].Close / emas[i] }); outputs.Add(1); var profit = current.High - quoteBars[i].Close; /*for (var k = j + 1; k < quoteBars.Count; k++) * { * * }*/ weights.Add((double)(1m - (50m / 10000m) / profit)); //i = j; break; } else if (current.Low <= shortTarget && current.High < shortStop && shortSetup) { inputs.Add(new double[] { stochAverage[i], stochCount[i], (double)quoteBars[i].Close / emas[i] }); outputs.Add(0); var profit = quoteBars[i].Close - current.Low; /*for (var k = j + 1; k < quoteBars.Count; k++) * { * * }*/ weights.Add((double)(1m - (50m / 10000m) / profit)); //i = j; break; } else if ((current.Low <= longStop && longSetup) || (current.High >= shortStop && shortSetup)) { //inputs.Add(new double[] { stochAverage[i] / stochs[i], stochCount[i], stochAverage[i] }); //outputs.Add(2); //i = j; break; } /*else if (j - i > 4 * 8) * { * inputs.Add(new double[] { stochs[i], stochCount[i], stochAverage[i] }); * outputs.Add(0); * //i = j; * break; * }*/ } } allInputs.AddRange(inputs); allOutputs.AddRange(outputs); allWeights.AddRange(weights); for (var i = 0; i < inputs.Count; i++) { //Console.WriteLine("Input: " + inputs[i][0] + " " + inputs[i][1] + " " + inputs[i][2] + " Output: " + outputs[i]); } var none = outputs.Where((o) => o == 2).Count(); var sell = outputs.Where((o) => o == 0).Count(); var buy = outputs.Where((o) => o == 1).Count(); Console.WriteLine("Total: {0} None: {1} Short: {2} Long: {3}", outputs.Count, none, sell, buy); /************ HMA ************/ /*var slow = HMA(symbol, 28, trainingResolution, Field.Close); * var slowSlope = new InstantTrend(symbol, 5).Of(slow); * var logReturns = LOGR(symbol, 3, trainingResolution, Field.Close); * var returnSlope = LSMA(symbol, 5, trainingResolution).Of(logReturns);*/ var consolidator = new QuoteBarConsolidator(TimeSpan.FromMinutes(15)); var stoch = new Stochastic(symbol, 14, 3, 3); var stochMA = new HullMovingAverage(symbol, 2).Of(stoch); var ema = new ExponentialMovingAverage(symbol, 40); var rolling = new RollingWindow <double>(1000); RegisterIndicator(symbol, stoch, consolidator); RegisterIndicator(symbol, ema, consolidator); SubscriptionManager.AddConsolidator(symbol, consolidator); _stoch[symbol] = stoch; _ema[symbol] = ema; stochMA.Updated += (sender, args) => { rolling.Add((double)args.Value); if (Securities[symbol].Price > 0) { //Plot("Plotter", "Price", Securities["EURUSD"].Price); Plot("Indicator", "STO", rolling[0]); } }; var std = ATR(symbol, 100, MovingAverageType.DoubleExponential, _dataResolution); var history = History <QuoteBar>(symbol, TimeSpan.FromDays(20), trainingResolution); foreach (var bar in history) { //slow.Update(bar.EndTime, bar.Close); //logReturns.Update(bar.EndTime, bar.Close); std.Update(bar); consolidator.Update(bar); } var signal = new SVMSignal(consolidator, stoch, stochMA, rolling, ema, Portfolio[symbol], this); signal.TrainSVM(inputs, outputs, weights); //signal.TrainNN(inputs, outputs, weights); Securities[symbol].VolatilityModel = new AverageTrueRangeVolatilityModel(std); _tradingAssets.Add(symbol, new TradingAsset(Securities[symbol], new OneShotTrigger(signal), new ProfitTargetSignalExit(null, _targetProfitLoss), _maximumTradeRisk, _maximumTradeSize, this )); } foreach (var symbol in Symbols) { //_tradingAssets[symbol].Retrain(allInputs, allOutputs, allWeights); } //AddData<DailyFx>("DFX", Resolution.Second, TimeZones.Utc); Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday), TimeRules.At(7, 0, TimeZones.London), () => { var tradeableDay = TradingCalendar.GetTradingDay().BusinessDay; if (tradeableDay) { foreach (var s in Symbols) { _tradingAssets[s].IsTradable = true; } } }); Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday), TimeRules.At(18, 0, TimeZones.London), () => { foreach (var s in Symbols) { _tradingAssets[s].IsTradable = false; } }); Schedule.On(DateRules.Every(DayOfWeek.Friday), TimeRules.BeforeMarketClose(Symbols.First(), 60), () => { foreach (var s in Symbols) { _tradingAssets[s].Liquidate(); } }); Chart plotter = new Chart("Plotter"); plotter.AddSeries(new Series("Price", SeriesType.Line, 0)); plotter.AddSeries(new Series("EMA", SeriesType.Line, 0)); plotter.AddSeries(new Series("Buy", SeriesType.Scatter, "", Color.Green, ScatterMarkerSymbol.Triangle)); plotter.AddSeries(new Series("Sell", SeriesType.Scatter, "", Color.Red, ScatterMarkerSymbol.TriangleDown)); plotter.AddSeries(new Series("Stopped", SeriesType.Scatter, "", Color.Yellow, ScatterMarkerSymbol.Diamond)); plotter.AddSeries(new Series("Prediction", SeriesType.Bar, 1)); plotter.AddSeries(new Series("Probability", SeriesType.Bar, 2)); AddChart(plotter); Chart indicator = new Chart("Indicator"); indicator.AddSeries(new Series("STO", SeriesType.Line, 0)); AddChart(indicator); Chart prediction = new Chart("Prediction"); prediction.AddSeries(new Series("Pred", SeriesType.Bar, 0)); AddChart(prediction); Chart probability = new Chart("Probability"); probability.AddSeries(new Series("Prob", SeriesType.Bar, 0)); AddChart(probability); }
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); }); }
// TODO: check volatilitymodel https://github.com/QuantConnect/Lean/blob/master/Common/Securities/RelativeStandardDeviationVolatilityModel.cs public override void Initialize() { SetStartDate(2016, 1, 1); SetEndDate(2017, 1, 1); SetCash(3000); SetBrokerageMessageHandler(new CustomBrokerageMessageHandler(this)); foreach (var symbol in Symbols) { AddForex(symbol, _dataResolution, Market.Oanda, false, 1m); Securities[symbol].TransactionModel = new OandaTransactionModel(); //Securities[symbol].SlippageModel = new ConstantSlippageModel(0m); SetBrokerageModel(BrokerageName.OandaBrokerage); var consolidator = new QuoteBarConsolidator(TimeSpan.FromMinutes(20)); var stoch = new Stochastic(symbol, 10, 3, 3); var stochMA = new ExponentialMovingAverage(symbol, 25).Of(stoch); var stochEmaLSMA = new LeastSquaresMovingAverage(symbol, 5).Of(stochMA); var ema = new ExponentialMovingAverage(symbol, 40); var emaMA = new LeastSquaresMovingAverage(symbol, 5).Of(ema); var rollingStochMA = HistoryTracker.Track(stochMA); var rollingEmaSlope = HistoryTracker.Track(emaMA.Slope); var rollingStochEmaSlope = HistoryTracker.Track(stochEmaLSMA.Slope); var shortTermMA = EMA(symbol, 30, Resolution.Minute, Field.Close); RegisterIndicator(symbol, stoch, consolidator); RegisterIndicator(symbol, ema, consolidator); SubscriptionManager.AddConsolidator(symbol, consolidator); _stoch[symbol] = stoch; _ema[symbol] = ema; var consolidatorDaily = new QuoteBarConsolidator(TimeSpan.FromHours(1)); var dailyMA = new HullMovingAverage(symbol, 7); var dailyEmaLSMA = new LeastSquaresMovingAverage(symbol, 3).Of(dailyMA); var rollingDailyEmaSlope = HistoryTracker.Track(dailyEmaLSMA.Slope); RegisterIndicator(symbol, dailyMA, consolidatorDaily); SubscriptionManager.AddConsolidator(symbol, consolidatorDaily); stochMA.Updated += (sender, args) => { if (Securities[symbol].Price > 0) { Plot("Indicator", "STO", rollingStochMA[0]); } }; stochEmaLSMA.Updated += (sender, args) => { if (Securities[symbol].Price > 0) { Plot("IndicatorTrend", "STO", stochEmaLSMA.Slope); } }; /*emaMA.Updated += (sender, args) => * { * if (Securities[symbol].Price > 0) * { * Plot("Trend", "LSMA", emaMA.Slope); * } * };*/ dailyEmaLSMA.Updated += (sender, args) => { if (Securities[symbol].Price > 0) { Plot("Trend", "LSMA", dailyEmaLSMA.Slope); Plot("Trend", "EMA", dailyMA); } }; var std = ATR(symbol, 100, MovingAverageType.DoubleExponential, _dataResolution); var history = History <QuoteBar>(symbol, TimeSpan.FromDays(40), _dataResolution); foreach (var bar in history) { std.Update(bar); consolidator.Update(bar); shortTermMA.Update(bar.EndTime, bar.Close); consolidatorDaily.Update(bar); } var signal = new SVMBaselineSignalWIP(consolidator, stoch, stochMA, rollingStochMA, stochEmaLSMA, rollingStochEmaSlope, ema, emaMA, rollingEmaSlope, shortTermMA, dailyEmaLSMA, rollingDailyEmaSlope, Portfolio[symbol], Securities[symbol], this); Securities[symbol].VolatilityModel = new AverageTrueRangeVolatilityModel(std); _tradingAssets.Add(symbol, new TradingAsset(Securities[symbol], new OneShotTrigger(signal), new ProfitTargetSignalExit(null, _targetProfitLoss), _maximumTradeRisk, _maximumTradeSize, this )); } //AddData<DailyFx>("DFX", Resolution.Second, TimeZones.Utc); Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday), TimeRules.At(7, 0, TimeZones.London), () => { var tradeableDay = TradingCalendar.GetTradingDay().BusinessDay; if (tradeableDay) { foreach (var s in Symbols) { _tradingAssets[s].IsTradable = true; } } }); Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday), TimeRules.At(20, 0, TimeZones.London), () => { foreach (var s in Symbols) { _tradingAssets[s].IsTradable = false; } }); Schedule.On(DateRules.Every(DayOfWeek.Friday), TimeRules.BeforeMarketClose(Symbols.First(), 60), () => { foreach (var s in Symbols) { _tradingAssets[s].Liquidate(); } }); Chart plotter = new Chart("Plotter"); plotter.AddSeries(new Series("Price", SeriesType.Line, 0)); plotter.AddSeries(new Series("EMA", SeriesType.Line, 0)); plotter.AddSeries(new Series("Buy", SeriesType.Scatter, "", Color.Green, ScatterMarkerSymbol.Triangle)); plotter.AddSeries(new Series("Sell", SeriesType.Scatter, "", Color.Red, ScatterMarkerSymbol.TriangleDown)); plotter.AddSeries(new Series("Stopped", SeriesType.Scatter, "", Color.Yellow, ScatterMarkerSymbol.Diamond)); plotter.AddSeries(new Series("Prediction", SeriesType.Bar, 1)); plotter.AddSeries(new Series("Probability", SeriesType.Bar, 2)); AddChart(plotter); Chart indicator = new Chart("Indicator"); indicator.AddSeries(new Series("STO", SeriesType.Line, 0)); AddChart(indicator); Chart indicatorTrend = new Chart("IndicatorTrend"); indicatorTrend.AddSeries(new Series("STO", SeriesType.Line, 0)); AddChart(indicatorTrend); Chart trend = new Chart("Trend"); trend.AddSeries(new Series("LSMA", SeriesType.Line, 0)); trend.AddSeries(new Series("EMA", SeriesType.Line, 1)); AddChart(trend); Chart prediction = new Chart("Prediction"); prediction.AddSeries(new Series("Pred", SeriesType.Bar, 0)); AddChart(prediction); Chart probability = new Chart("Probability"); probability.AddSeries(new Series("Prob", SeriesType.Bar, 0)); AddChart(probability); }
public override void Initialize() { SetStartDate(2016, 1, 1); SetEndDate(2017, 1, 1); SetCash(3000); SetBrokerageMessageHandler(new CustomBrokerageMessageHandler(this)); foreach (var symbol in Symbols) { AddForex(symbol, _dataResolution, Market.Oanda, false, 1m); Securities[symbol].TransactionModel = new OandaTransactionModel(); //Securities[symbol].SlippageModel = new ConstantSlippageModel(0m); SetBrokerageModel(BrokerageName.OandaBrokerage); /******** LONG TERM TREND ********/ var dailyConsolidator = new QuoteBarConsolidator(TimeSpan.FromDays(1)); var alma = new ExponentialMovingAverage(symbol, 10); RegisterIndicator(symbol, alma, dailyConsolidator); SubscriptionManager.AddConsolidator(symbol, dailyConsolidator); /******** SHORT TERM TRADING ********/ var consolidator = new QuoteBarConsolidator(TimeSpan.FromMinutes(15)); var schaffTrendCycle = new SchaffTrendCycle(symbol); var atr = new AverageTrueRange(symbol, 10); var adx = new AverageDirectionalIndex(symbol, 10); RegisterIndicator(symbol, schaffTrendCycle, consolidator); RegisterIndicator(symbol, atr, consolidator); RegisterIndicator(symbol, adx, consolidator); /****** ALMA Fibonacci ******/ var alma5 = new ArnaudLegouxMovingAverage(symbol, 5); var alma8 = new ArnaudLegouxMovingAverage(symbol, 8); var alma13 = new ArnaudLegouxMovingAverage(symbol, 13); var alma21 = new ArnaudLegouxMovingAverage(symbol, 21); var alma34 = new ArnaudLegouxMovingAverage(symbol, 34); var alma55 = new ArnaudLegouxMovingAverage(symbol, 55); var alma89 = new ArnaudLegouxMovingAverage(symbol, 89); var alma144 = new ArnaudLegouxMovingAverage(symbol, 144); RegisterIndicator(symbol, alma5, consolidator); RegisterIndicator(symbol, alma8, consolidator); RegisterIndicator(symbol, alma13, consolidator); RegisterIndicator(symbol, alma21, consolidator); RegisterIndicator(symbol, alma34, consolidator); RegisterIndicator(symbol, alma55, consolidator); RegisterIndicator(symbol, alma89, consolidator); RegisterIndicator(symbol, alma144, consolidator); SubscriptionManager.AddConsolidator(symbol, consolidator); var signal = new SVMBaselineSignal( dailyConsolidator, alma, consolidator, alma5, alma8, alma13, alma21, alma34, alma55, alma89, alma144, schaffTrendCycle, atr, adx, Portfolio[symbol], Securities[symbol], this ); var std = ATR(symbol, 100, MovingAverageType.DoubleExponential, _dataResolution); /******** HISTORY ********/ var history = History <QuoteBar>(symbol, TimeSpan.FromDays(100), _dataResolution); foreach (var bar in history) { std.Update(bar); consolidator.Update(bar); dailyConsolidator.Update(bar); } if (_store) { var header = new string[] { "Time", "ALMA_5", "ALMA_8", "ALMA_13", "ALMA_21", "ALMA_34", "ALMA_55", "ALMA_89", "ALMA_144" }; Storage.CreateFile($"C:\\Users\\M\\Desktop\\{symbol}_ALMA.csv", header); consolidator.DataConsolidated += (sender, args) => { var line = new object[] { Storage.ToUTCTimestamp(args.Time), alma5.Current.Value, alma8.Current.Value, alma13.Current.Value, alma21.Current.Value, alma34.Current.Value, alma55.Current.Value, alma89.Current.Value, alma144.Current.Value }; Storage.AppendToFile($"C:\\Users\\M\\Desktop\\{symbol}_ALMA.csv", line); }; } Securities[symbol].VolatilityModel = new AverageTrueRangeVolatilityModel(std); _tradingAssets.Add(symbol, new TradingAsset(Securities[symbol], new OneShotTrigger(signal), new ProfitTargetSignalExit(null, _targetProfitLoss), _maximumTradeRisk, _maximumTradeSize, this )); //_tradingAssets[symbol].IsTradable = true; var h = new object[] { "Time", "Signal", "Price" }; Storage.CreateFile($"C:\\Users\\M\\Desktop\\{symbol}_ALMA_Signal.csv", h); } Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday), TimeRules.At(7, 0, TimeZones.London), () => { var tradeableDay = TradingCalendar.GetTradingDay().BusinessDay; if (tradeableDay) { foreach (var s in Symbols) { _tradingAssets[s].IsTradable = true; } } }); Schedule.On(DateRules.Every(DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday), TimeRules.At(20, 0, TimeZones.London), () => { foreach (var s in Symbols) { //_tradingAssets[s].IsTradable = false; } }); Schedule.On(DateRules.Every(DayOfWeek.Friday), TimeRules.BeforeMarketClose(Symbols.First(), 240), () => { foreach (var s in Symbols) { //_tradingAssets[s].IsTradable = false; } }); Schedule.On(DateRules.Every(DayOfWeek.Friday), TimeRules.BeforeMarketClose(Symbols.First(), 180), () => { foreach (var s in Symbols) { //_tradingAssets[s].Liquidate(); //_tradingAssets[s].IsTradable = false; } }); /******** CHARTING ********/ /*Chart price = new Chart("Daily Price"); * price.AddSeries(new Series("Price", SeriesType.Candle, 0)); * price.AddSeries(new Series("MA", SeriesType.Line, 0)); * price.AddSeries(new Series("Slope", SeriesType.Line, 1)); * price.AddSeries(new Series("STC", SeriesType.Line, 2)); * AddChart(price); * * Chart ma = new Chart("MA"); * ma.AddSeries(new Series("HMA", SeriesType.Line, 0)); * ma.AddSeries(new Series("FAMA", SeriesType.Line, 1)); * AddChart(ma); * * Chart lsma = new Chart("LSMA"); * lsma.AddSeries(new Series("Slope", SeriesType.Line, 0)); * AddChart(lsma);*/ Chart plotter = new Chart("Plotter"); plotter.AddSeries(new Series("Close", SeriesType.Line, 0)); plotter.AddSeries(new Series("EMA", SeriesType.Line, 1)); plotter.AddSeries(new Series("Buy", SeriesType.Scatter, "", Color.Green, ScatterMarkerSymbol.Triangle)); plotter.AddSeries(new Series("Sell", SeriesType.Scatter, "", Color.Red, ScatterMarkerSymbol.TriangleDown)); //plotter.AddSeries(new Series("Stopped", SeriesType.Scatter, "", Color.Yellow, ScatterMarkerSymbol.Diamond)); plotter.AddSeries(new Series("Diff", SeriesType.Bar, 2)); plotter.AddSeries(new Series("Slope", SeriesType.Line, 3)); plotter.AddSeries(new Series("STC", SeriesType.Line, 4)); plotter.AddSeries(new Series("STOCH", SeriesType.Line, 5)); plotter.AddSeries(new Series("Prediction", SeriesType.Bar, 6)); plotter.AddSeries(new Series("Signal", SeriesType.Bar, 7)); AddChart(plotter); }