public void LSMAComputesCorrectly() { int LSMAPeriod = 20; LeastSquaresMovingAverage LSMA = new LeastSquaresMovingAverage(LSMAPeriod); DateTime time = DateTime.Now; #region Array input decimal[] expected = new decimal[40] { 125.99m , 125.91m , 125.75m , 125.62m , 125.54m , 125.45m , 125.47m , 125.4m , 125.43m , 125.45m , 125.42m , 125.36m , 125.23m , 125.32m , 125.26m , 125.31m , 125.41m , 125.5m , 125.51m , 125.41m , 125.328m , 125.381m , 125.4423m, 125.4591m, 125.4689m, 125.4713m, 125.4836m, 125.4834m, 125.4803m, 125.4703m, 125.4494m, 125.4206m, 125.3669m, 125.3521m, 125.3214m, 125.2986m, 125.2909m, 125.2723m, 125.2619m, 125.2224m, }; #endregion Array input decimal[] actual = new decimal[prices.Length]; for (int i = 0; i < prices.Length; i++) { LSMA.Update(new IndicatorDataPoint(time, prices[i])); decimal LSMAValue = Math.Round(LSMA.Current.Value, 4); actual[i] = LSMAValue; //Console.WriteLine(string.Format("Bar : {0} | {1}, Is ready? {2}", i, LSMA.ToString(), LSMA.IsReady)); time = time.AddMinutes(1); } Assert.AreEqual(expected, actual); }
public void LSMAComputesCorrectly() { int LSMAPeriod = 20; LeastSquaresMovingAverage LSMA = new LeastSquaresMovingAverage(LSMAPeriod); DateTime time = DateTime.Now; #region Array input decimal[] expected = new decimal[40] { 125.99m, 125.91m, 125.75m, 125.62m, 125.54m, 125.45m, 125.47m, 125.4m, 125.43m, 125.45m, 125.42m, 125.36m, 125.23m, 125.32m, 125.26m, 125.31m, 125.41m, 125.5m, 125.51m, 125.41m, 125.328m, 125.381m, 125.4423m, 125.4591m, 125.4689m, 125.4713m, 125.4836m, 125.4834m, 125.4803m, 125.4703m, 125.4494m, 125.4206m, 125.3669m, 125.3521m, 125.3214m, 125.2986m, 125.2909m, 125.2723m, 125.2619m, 125.2224m, }; #endregion Array input decimal[] actual = new decimal[prices.Length]; for (int i = 0; i < prices.Length; i++) { LSMA.Update(new IndicatorDataPoint(time, prices[i])); decimal LSMAValue = Math.Round(LSMA.Current.Value, 4); actual[i] = LSMAValue; //Console.WriteLine(string.Format("Bar : {0} | {1}, Is ready? {2}", i, LSMA.ToString(), LSMA.IsReady)); time = time.AddMinutes(1); } Assert.AreEqual(expected, actual); }
/// <summary> /// Initializes a new instance of the <see cref="RegressionChannel"/> class. /// </summary> /// <param name="name">The name of this indicator</param> /// <param name="period">The number of data points to hold in the window</param> /// <param name="k">The number of standard deviations specifying the distance between the linear regression and upper or lower channel lines</param> public RegressionChannel(string name, int period, decimal k) : base(name) { _standardDeviation = new StandardDeviation(period); LinearRegression = new LeastSquaresMovingAverage(name + "_LinearRegression", period); LowerChannel = LinearRegression.Minus(_standardDeviation.Times(k), name + "_LowerChannel"); UpperChannel = LinearRegression.Plus(_standardDeviation.Times(k), name + "_UpperChannel"); }
public BollingerBandSignal(BollingerBands bb, LeastSquaresMovingAverage lsmaUpperBand, LeastSquaresMovingAverage lsmaMiddleBand, LeastSquaresMovingAverage lsmaLowerBand, AverageDirectionalIndex adx, SecurityHolding securityHolding) { _bb = bb; _lsmaUpperBand = lsmaUpperBand; _lsmaMiddleBand = lsmaMiddleBand; _lsmaLowerBand = lsmaLowerBand; _adx = adx; _securityHolding = securityHolding; }
public LogReturnSignal(LogReturn logr_Fast, LogReturn logr_Slow, LeastSquaresMovingAverage logrFast, LeastSquaresMovingAverage logrSlow, TickConsolidator ticks, SecurityHolding securityHolding) { _logr_Fast = logr_Fast; _logr_Slow = logr_Slow; _logrFast = logrFast; _logrSlow = logrSlow; _ticks = ticks; _securityHolding = securityHolding; }
public void ResetsProperly() { int LSMAPeriod = 10; DateTime time = DateTime.Now; LeastSquaresMovingAverage LSMA = new LeastSquaresMovingAverage(LSMAPeriod); for (int i = 0; i < LSMAPeriod + 1; i++) { LSMA.Update(new IndicatorDataPoint(time, 1m)); time = time.AddMinutes(1); } Assert.IsTrue(LSMA.IsReady, "LSMA ready"); LSMA.Reset(); TestHelper.AssertIndicatorIsInDefaultState(LSMA); }
public void ResetsProperly() { int LSMAPeriod = 10; DateTime time = DateTime.Now; LeastSquaresMovingAverage LSMA = new LeastSquaresMovingAverage(LSMAPeriod); for (int i = 0; i < LSMAPeriod + 1; i++) { LSMA.Update(new IndicatorDataPoint(time, 1m)); time.AddMinutes(1); } Assert.IsTrue(LSMA.IsReady, "LSMA ready"); LSMA.Reset(); TestHelper.AssertIndicatorIsInDefaultState(LSMA); }
public void LSMAComputesCorrectly() { int LSMAPeriod = 20; LeastSquaresMovingAverage LSMA = new LeastSquaresMovingAverage(LSMAPeriod); DateTime time = DateTime.Now; decimal[] actual = new decimal[prices.Length]; for (int i = 0; i < prices.Length; i++) { LSMA.Update(new IndicatorDataPoint(time, prices[i])); decimal LSMAValue = Math.Round(LSMA.Current.Value, 4); actual[i] = LSMAValue; time = time.AddMinutes(1); } Assert.AreEqual(expected, actual); }
//RegisterIndicator(symbol, logr, null); //Initialize the data and resolution you require for your strategy: public override void Initialize() { //Start and End Date range for the backtest: SetStartDate(2009, 3, 1); SetEndDate(DateTime.Now); //Cash allocation SetCash(25000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, symbol, Resolution.Hour); logr_14 = LOGR(symbol, 14, Resolution.Hour); logr_30 = LOGR(symbol, 2, Resolution.Hour); logr14 = new LeastSquaresMovingAverage(14).Of(logr_14); logr30 = new LeastSquaresMovingAverage(30).Of(logr_30); }
public override void Initialize() { SetStartDate(2010, 01, 1); SetEndDate(2012, 12, 31); SetCash(100000); AddSecurity(SecurityType.Equity, symbol, Resolution.Daily); var close = Identity(symbol); LSMA = new LeastSquaresMovingAverage(20); RegisterIndicator(symbol, LSMA, Resolution.Daily, Field.Close); var chart = new Chart("Plot"); chart.AddSeries(new Series(close.Name)); chart.AddSeries(new Series(LSMA.Name)); PlotIndicator("Plot", close); PlotIndicator("Plot", true, LSMA); logResult.AppendLine("Time,Close,LSMA"); }
public SVMBaselineSignalWIP( QuoteBarConsolidator consolidator, Stochastic stoch, ExponentialMovingAverage stochMA, RollingWindow <IndicatorDataPoint> rollingStochMA, LeastSquaresMovingAverage stochEmaLSMA, RollingWindow <IndicatorDataPoint> rollingStochEmaSlope, ExponentialMovingAverage ema, LeastSquaresMovingAverage emaMA, RollingWindow <IndicatorDataPoint> rollingEmaSlope, ExponentialMovingAverage shortTermMA, LeastSquaresMovingAverage dailyEmaLSMA, RollingWindow <IndicatorDataPoint> rollingDailyEmaSlope, SecurityHolding securityHolding, Security security, SVMBaselineStrategyWIP qcAlgorithm) { _consolidator = consolidator; _stoch = stoch; _stochMA = stochMA; _rollingStochMA = rollingStochMA; _stochEmaLSMA = stochEmaLSMA; _rollingStochEmaSlope = rollingStochEmaSlope; _ema = ema; _emaMA = emaMA; _rollingEmaSlope = rollingEmaSlope; _shortTermMA = shortTermMA; _dailyEmaLSMA = dailyEmaLSMA; _rollingDailyEmaSlope = rollingDailyEmaSlope; _securityHolding = securityHolding; _security = security; _minimumPriceVariation = (1m / _security.SymbolProperties.MinimumPriceVariation) / 10m; _qcAlgorithm = qcAlgorithm; _stochMA.Updated += (sender, args) => { try { var currentQuote = (QuoteBar)_consolidator.Consolidated; var aboveEma = currentQuote.Close - _ema.Current.Value > 4m / _minimumPriceVariation; var belowEma = _ema.Current.Value - currentQuote.Close > 4m / _minimumPriceVariation; var aboveEmaExit = (currentQuote.Close - _ema.Current.Value > 10m / _minimumPriceVariation) || _rollingDailyEmaSlope[0] > 0.0005m; var belowEmaExit = (_ema.Current.Value - currentQuote.Close > 10m / _minimumPriceVariation) || _rollingDailyEmaSlope[0] < -0.0005m; var longCondition = _rollingStochMA[0] > _rollingStochMA[1] && _stochMA > 55 && aboveEma && //_rollingDailyEmaSlope[0] > _rollingDailyEmaSlope[1] && _dailyEmaLSMA.Slope > 0 && //_rollingStochEmaSlope[0] < 2 && //_rollingStochEmaSlope[0] > _rollingStochEmaSlope[1] && //_rollingStochMA[0] > 45 && _rollingEmaSlope[0] > 0.00001m; var shortCondition = _rollingStochMA[0] < _rollingStochMA[1] && _stochMA < 45 && belowEma && //_rollingDailyEmaSlope[0] < _rollingDailyEmaSlope[1] && _dailyEmaLSMA.Slope < 0 && //_rollingStochEmaSlope[0] > -2 && //_rollingStochEmaSlope[0] < _rollingStochEmaSlope[1] && //_rollingStochMA[0] < 55 && _rollingEmaSlope[0] < -0.00001m; var prediction = longCondition ? 1 : shortCondition ? -1 : 0; /*var prediction = _rollingStochMA[0] > _rollingStochMA[1] && aboveEma && _stochEmaLSMA.Slope > 0.5 && _rollingEmaSlope[0] > 0 * ? 1 * : _rollingStochMA[0] < _rollingStochMA[1] && belowEma && _stochEmaLSMA.Slope < -0.5 && _rollingEmaSlope[0] < 0 * ? -1 * : 0;*/ var probability = 1d; var logLikelihood = 1d; _qcAlgorithm.PlotSignal((QuoteBar)_consolidator.Consolidated, prediction, logLikelihood); var longExit = Signal == SignalType.Long && belowEmaExit && _rollingEmaSlope[0] < 0; var shortExit = Signal == SignalType.Short && aboveEmaExit && _rollingEmaSlope[0] > 0; /*var longExit = Signal == SignalType.Long && _stochEmaLSMA.Slope < -0.5; * var shortExit = Signal == SignalType.Short && _stochEmaLSMA.Slope > 0.5;*/ if (!_securityHolding.Invested && prediction == 1) { if (true)//if (!_shortOnly.Contains(_securityHolding.Symbol)) { Signal = Signal != SignalType.PendingLong ? SignalType.Long : SignalType.Long; } else { Signal = SignalType.NoSignal; } //Signal = Signal != SignalType.PendingLong ? SignalType.Long : SignalType.Long; //Signal = SignalType.NoSignal; if (_debug) { Console.WriteLine("Long Signal: {0} Probability: {1} Log Likelihood: {2}", Signal, probability, logLikelihood); Console.WriteLine("Long STO: {0} STO MA: {1}", _stoch.Current.Value, args.Value); Console.WriteLine("Long Time: {0} Price: {1}", _consolidator.Consolidated.Time, _consolidator.Consolidated.Value); } } else if (!_securityHolding.Invested && prediction == -1) { if (true) //if (_shortable.Contains(_securityHolding.Symbol)) { Signal = Signal != SignalType.PendingShort ? SignalType.Short : SignalType.Short; } else { Signal = SignalType.NoSignal; } //Signal = Signal != SignalType.PendingShort ? SignalType.Short : SignalType.Short; //Signal = SignalType.NoSignal; if (_debug) { Console.WriteLine("Short Signal: {0} Probability: {1} Log Likelihood: {2}", Signal, probability, logLikelihood); Console.WriteLine("Short STO: {0} STO MA: {1}", _stoch.Current.Value, args.Value); Console.WriteLine("Short Time: {0} Price: {1}", _consolidator.Consolidated.Time, _consolidator.Consolidated.Value); } } else if ((_securityHolding.Invested && longExit) || (_securityHolding.Invested && shortExit)) { if (_debug) { Console.WriteLine("Exit Signal: {0} Probability: {1} Log Likelihood: {2}", Signal, probability, logLikelihood); Console.WriteLine("Exit STO: {0} STO MA: {1}", _stoch.Current.Value, args.Value); Console.WriteLine("Exit Time: {0} Price: {1}", _consolidator.Consolidated.Time, _consolidator.Consolidated.Value); } Signal = SignalType.Exit; } else if (!_securityHolding.Invested && (Signal == SignalType.PendingLong || Signal == SignalType.PendingShort)) { Signal = SignalType.NoSignal; } else { //Signal = SignalType.NoSignal; } } catch (Exception ex) { Console.WriteLine(ex.Message); Signal = SignalType.NoSignal; } }; }
// 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); }