public DIFStrategy(Indicator Price, int DecyclePeriod = 20, int InvFisherPeriod = 40, decimal Threshold = 0.9m, decimal Tolerance = 0.001m) { // Initialize the fields. _decyclePeriod = DecyclePeriod; _invFisherPeriod = InvFisherPeriod; _threshold = Threshold; _tolerance = Tolerance; // Initialize the indicators used by the Strategy. _price = Price; DecycleTrend = new Decycle(_decyclePeriod).Of(Price); InverseFisher = new InverseFisherTransform(_invFisherPeriod).Of(DecycleTrend); InvFisherRW = new RollingWindow<decimal>(2); LightSmoothPrice = new Decycle(10).Of(Price); Momersion = new MomersionIndicator(10, 30).Of(LightSmoothPrice, false); // Fill the Inverse Fisher rolling windows at every new InverseFisher observation. // Once the Inverse Fisher rolling windows is ready, at every InverseFisher update, the Check signal method will be called. InverseFisher.Updated += (object sender, IndicatorDataPoint updated) => { if (InverseFisher.IsReady) InvFisherRW.Add(updated); if (InvFisherRW.IsReady) CheckSignal(); }; Position = StockState.noInvested; EntryPrice = null; ActualSignal = OrderSignal.doNothing; }
public void IndexingBasedOnReverseInsertedOrder() { var window = new RollingWindow<int>(3); Assert.AreEqual(3, window.Size); window.Add(0); Assert.AreEqual(1, window.Count); Assert.AreEqual(0, window[0]); window.Add(1); Assert.AreEqual(2, window.Count); Assert.AreEqual(0, window[1]); Assert.AreEqual(1, window[0]); window.Add(2); Assert.AreEqual(3, window.Count); Assert.AreEqual(0, window[2]); Assert.AreEqual(1, window[1]); Assert.AreEqual(2, window[0]); window.Add(3); Assert.AreEqual(3, window.Count); Assert.AreEqual(1, window[2]); Assert.AreEqual(2, window[1]); Assert.AreEqual(3, window[0]); }
/// <summary> /// Initializes a new instance of the <see cref="RelativeStandardDeviationVolatilityModel"/> class /// </summary> /// <param name="periodSpan">The time span representing one 'period' length</param> /// <param name="periods">The nuber of 'period' lengths to wait until updating the value</param> public RelativeStandardDeviationVolatilityModel(TimeSpan periodSpan, int periods) { if (periods < 2) throw new ArgumentOutOfRangeException("periods", "'periods' must be greater than or equal to 2."); _periodSpan = periodSpan; _window = new RollingWindow<double>(periods); _lastUpdate = DateTime.MinValue + TimeSpan.FromMilliseconds(periodSpan.TotalMilliseconds*periods); }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { //mylog.Debug(transheader); mylog.Debug(ondataheader); //Initialize dates SetStartDate(2013, 10, 07); SetEndDate(2013, 10, 07); SetCash(25000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, _symbol, Resolution.Minute); maxHigh = new Maximum("MaxHigh", _period); minLow = new Minimum("MinLow", _period); value1 = new RollingWindow<IndicatorDataPoint>(_period); fish = new RollingWindow<IndicatorDataPoint>(_period); //wma = new LinearWeightedMovingAverage(5); // induces 2 bar lag //wwma = new RollingWindow<IndicatorDataPoint>(_period); //fishHigh = new Maximum("FishHigh", 400); //fishLow = new Minimum("FishLow", 400); fx = new FisherTransform(_symbol,_period); //fx = FT(_symbol, _period, Resolution.Minute); // Add a bars to initialize the RollingWindow value1.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m)); value1.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m)); fish.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); fish.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); //wwma.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m)); //wwma.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m)); }
public void NewWindowIsEmpty() { var window = new RollingWindow<int>(1); Assert.AreEqual(1, window.Size); Assert.AreEqual(0, window.Count); Assert.AreEqual(0, window.Samples); Assert.IsFalse(window.IsReady); }
/// <summary> /// Empty Consturctor /// </summary> //public InstantTrendStrategy() { } /// <summary> /// Constructor initializes the symbol and period of the RollingWindow /// </summary> /// <param name="symbol">string - ticker symbol</param> /// <param name="period">int - the period of the Trend History Rolling Window</param> /// <param name="algorithm"></param> public InstantTrendStrategyQC(string symbol, int period, QCAlgorithm algorithm) { _symbol = symbol; trendHistory = new RollingWindow<IndicatorDataPoint>(period); _algorithm = algorithm; orderFilled = true; maketrade = true; }
/// <summary> /// Constructor initializes the symbol and period of the RollingWindow /// </summary> /// <param name="symbol">string - ticker symbol</param> /// <param name="period">int - the period of the Trend History Rolling Window</param> /// <param name="tradesize">int - the number of shares to trade</param> /// <param name="algorithm"></param> public RateOfChangePercentStrategy(string symbol, int period, QCAlgorithm algorithm) { //sma20 = new SimpleMovingAverage(20); _symbol = symbol; Price = new RollingWindow<IndicatorDataPoint>(period); _algorithm = algorithm; orderFilled = true; }
public void EnumeratesAsExpected() { var window = new RollingWindow<int>(3) { 0, 1, 2 }; var inOrder = window.ToList(); Assert.AreEqual(2, inOrder[0]); Assert.AreEqual(1, inOrder[1]); Assert.AreEqual(0, inOrder[2]); }
/// <summary> /// Empty Consturctor /// </summary> //public InstantTrendStrategy() { } /// <summary> /// Constructor initializes the symbol and period of the RollingWindow /// </summary> /// <param name="symbol">string - ticker symbol</param> /// <param name="period">int - the period of the Trend History Rolling Window</param> /// <param name="algorithm"></param> public QCLiveSignal(string symbol, int period, QCAlgorithm algorithm) { _symbol = symbol; trendHistory = new RollingWindow<IndicatorDataPoint>(period); _algorithm = algorithm; orderFilled = true; maketrade = true; }
/// <summary> /// Creates the indicator /// </summary> /// <param name="name">string - the name of the indicator</param> /// <param name="period">int - half the number of periods in the dominant market cycle. </param> public RelativeVigorIndex(string name, int period) : base(name) { value1 = new RollingWindow<IndicatorDataPoint>(period); value2 = new RollingWindow<IndicatorDataPoint>(period); RviWindow = new RollingWindow<IndicatorDataPoint>(period); Bars = new RollingWindow<TradeBar>(period); }
/// <summary> /// Empty Consturctor /// </summary> //public InstantTrendStrategy() { } /// <summary> /// Constructor initializes the symbol and period of the RollingWindow /// </summary> /// <param name="symbol">string - ticker symbol</param> /// <param name="period">int - the period of the Trend History Rolling Window</param> /// <param name="algorithm"></param> public Sig1(Symbol symbol, int period, QCAlgorithm algorithm) { _symbol = symbol; trendHistory = new RollingWindow<IndicatorDataPoint>(3); _algorithm = algorithm; orderFilled = true; maketrade = true; Id = 1; }
public Sig2(Symbol symbol, int period, QCAlgorithm algorithm) { _symbol = symbol; trendHistory = new RollingWindow<decimal>(3); _algorithm = algorithm; orderFilled = true; maketrade = true; trendArray = new decimal[] { 0, 0, 0 }; Id = 2; }
/// <summary> /// Initializes a new instance of the <see cref="ITrendStrategy"/> class. /// </summary> /// <param name="period">The period of the Instantaneous trend.</param> public ITrendSignal(int period, decimal tolerance = 0.001m, decimal revetPct = 1.0015m, RevertPositionCheck checkRevertPosition = RevertPositionCheck.vsTrigger) { ITrend = new InstantaneousTrend(period); ITrendMomentum = new Momentum(2).Of(ITrend); MomentumWindow = new RollingWindow<decimal>(2); _tolerance = tolerance; _revertPCT = revetPct; _checkRevertPosition = checkRevertPosition; }
public double?Compute(RollingWindow <double> window) { double removed = 0; if (window.HasOverflowed) { removed = window.MostRecentlyRemoved; } sumOfSquares = sumOfSquares + window[0] * window[0] - removed * removed; return(sumOfSquares); }
public void EnumeratesAsExpected() { var window = new RollingWindow <int>(3) { 0, 1, 2 }; var inOrder = window.ToList(); Assert.AreEqual(2, inOrder[0]); Assert.AreEqual(1, inOrder[1]); Assert.AreEqual(0, inOrder[2]); }
/// <summary> /// Initializes a new instance of the average class /// </summary> /// <param name="name">The name of the indicator instance</param> /// <param name="n">The window period (must be even). Example value: 16</param> /// <param name="longPeriod">The average period. Example value: 198</param> public FractalAdaptiveMovingAverage(string name, int n, int longPeriod) : base(name) { if (n % 2 > 0) { throw new ArgumentException("N must be even."); } _n = n; _w = CalculateW(longPeriod); _high = new RollingWindow<double>(n); _low = new RollingWindow<double>(n); }
/// <summary> /// Initializes a new instance of the <see cref="RelativeStandardDeviationVolatilityModel"/> class /// </summary> /// <param name="periodSpan">The time span representing one 'period' length</param> /// <param name="periods">The nuber of 'period' lengths to wait until updating the value</param> public RelativeStandardDeviationVolatilityModel( TimeSpan periodSpan, int periods) { if (periods < 2) { throw new ArgumentOutOfRangeException("periods", "'periods' must be greater than or equal to 2."); } _periodSpan = periodSpan; _window = new RollingWindow <double>(periods); _lastUpdate = DateTime.MinValue + TimeSpan.FromMilliseconds(periodSpan.TotalMilliseconds * periods); }
private double[] GetReturns(QCAlgorithm algorithm, Symbol symbol) { var window = new RollingWindow <double>(period); var rateOfChange = new RateOfChange(1); rateOfChange.Updated += (s, item) => window.Add((double)item.Value); foreach (var bar in algorithm.History(symbol, period, Resolution.Daily)) { rateOfChange.Update(bar.EndTime, bar.Close); } return(window.ToArray()); }
public void WhenIndexingIntoWindow_Then_Items_AreInReverseChronologicalOrder() { const int size = 5; var items = Enumerable.Range(1, size).ToList(); var sut = new RollingWindow <int>(size); items.ForEach(sut.Add); for (int i = 0; i < size; i++) { Assert.AreEqual(size - i, sut[i]); } }
/// <summary> /// Initializes a new instance of the average class /// </summary> /// <param name="name">The name of the indicator instance</param> /// <param name="n">The window period (must be even). Example value: 16</param> /// <param name="longPeriod">The average period. Example value: 198</param> public FractalAdaptiveMovingAverage(string name, int n, int longPeriod) : base(name) { if (n % 2 > 0) { throw new ArgumentException($"{name}: N must be even, N = {n}", nameof(n)); } _n = n; _w = Math.Log(2d / (1 + longPeriod)); _high = new RollingWindow <double>(n); _low = new RollingWindow <double>(n); }
public void InsertTest() { RollingWindow<int> rollingWindow = new RollingWindow<int>(5); rollingWindow.Insert(0, 1); rollingWindow.Insert(1, 3); rollingWindow.Insert(0, 0); rollingWindow.Insert(2, 2); rollingWindow.Insert(4, 4); for (int i = 0; i < rollingWindow.Count; i++) Assert.AreEqual(i, rollingWindow[i]); }
private decimal LSMA(RollingWindow <decimal> dataW, int lsmaPeriod) { decimal delta = 0; for (int i = lsmaPeriod; i >= 1; i--) { delta += (i - (lsmaPeriod + 1) / 3.0m) * dataW[lsmaPeriod - i]; } var lsma = delta * 6 / (lsmaPeriod * (lsmaPeriod + 1)); return(lsma); }
public void OldDataFallsOffBackOfWindow() { var window = new RollingWindow<int>(1); window.Add(0); Assert.IsFalse(window.IsReady); // add one more and the window is ready window.Add(1); Assert.AreEqual(0, window.MostRecentlyRemoved); Assert.AreEqual(1, window.Count); Assert.IsTrue(window.IsReady); }
public void ClearTest() { RollingWindow <int> rollingWindow = new RollingWindow <int>(5); for (int i = 0; i < rollingWindow.WindowSize; i++) { rollingWindow.Add(i); } Assert.AreEqual(rollingWindow.WindowSize, rollingWindow.Count); rollingWindow.Clear(); Assert.AreEqual(0, rollingWindow.Count); }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { //Initialize dates SetStartDate(2015, 6, 15); SetEndDate(2015, 6, 15); SetCash(25000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, symbol, Resolution.Minute); #region "Init indicators" Price = new RollingWindow <IndicatorDataPoint>(samplesize); ema = new RollingWindow <IndicatorDataPoint>(samplesize); zema = new RollingWindow <IndicatorDataPoint>(samplesize); OptimalValue1 = new RollingWindow <IndicatorDataPoint>(samplesize); OmtimalValue2 = new RollingWindow <IndicatorDataPoint>(samplesize); OptimalTrackingFilter = new RollingWindow <IndicatorDataPoint>(samplesize); lambda = new RollingWindow <IndicatorDataPoint>(samplesize); alpha = new RollingWindow <IndicatorDataPoint>(samplesize); priceOptimalDiff = new RollingWindow <IndicatorDataPoint>(samplesize); priceOptimalSign = new RollingWindow <IndicatorDataPoint>(samplesize); priceOptimalCross = new RollingWindow <IndicatorDataPoint>(samplesize); fudge = new RollingWindow <IndicatorDataPoint>(samplesize); instantTrend = new RollingWindow <IndicatorDataPoint>(samplesize); instantTrendTrigger = new RollingWindow <IndicatorDataPoint>(samplesize); cyberCycle = new RollingWindow <IndicatorDataPoint>(samplesize); centerGravity = new RollingWindow <IndicatorDataPoint>(samplesize); cyberCycleSmooth = new RollingWindow <IndicatorDataPoint>(samplesize); rvi = new RelativeVigorIndex(8); rviHistory = new RollingWindow <IndicatorDataPoint>(samplesize); stochCenterGravityValue1 = new RollingWindow <IndicatorDataPoint>(8); stochCenterGravityValue2 = new RollingWindow <IndicatorDataPoint>(8); stochCyberCycleValue1 = new RollingWindow <IndicatorDataPoint>(8); stochCyberCycleValue2 = new RollingWindow <IndicatorDataPoint>(8); stochCyberCycleInverseFisher = new RollingWindow <IndicatorDataPoint>(8); stochCyberCycleFisher = new RollingWindow <IndicatorDataPoint>(8); stochRviHistoryValue1 = new RollingWindow <IndicatorDataPoint>(8); stochRviHistoryValue2 = new RollingWindow <IndicatorDataPoint>(8); ROC = new RateOfChange(4); maxCyberCycle = new Maximum(8); minCyberCycle = new Minimum(8); #endregion //mylog.Debug(transheader); mylog.Debug(ondataheader); string msg = "Security,Date,Day Profit,Day Fees, Day Net, Total Profit, Total Fees"; mylog.Debug(msg); mylog.Debug(tradeheader); }
public SymbolData(QCAlgorithm algorithm, Symbol symbol, int dailyLookback, int lookback, Resolution resolution) { Symbol = symbol; _dailyReturn = new RateOfChangePercent($"{symbol}.DailyROCP(1)", 1); _dailyConsolidator = algorithm.ResolveConsolidator(symbol, Resolution.Daily); _dailyReturnHistory = new RollingWindow <IndicatorDataPoint>(dailyLookback); _dailyReturn.Updated += (s, e) => _dailyReturnHistory.Add(e); algorithm.RegisterIndicator(symbol, _dailyReturn, _dailyConsolidator); Return = new RateOfChangePercent($"{symbol}.ROCP({lookback})", lookback); _consolidator = algorithm.ResolveConsolidator(symbol, resolution); algorithm.RegisterIndicator(symbol, Return, _consolidator); }
public void IndexOfTest() { RollingWindow <int> rollingWindow = new RollingWindow <int>(5); for (int i = 0; i < rollingWindow.WindowSize; i++) { rollingWindow.Add(i); } for (int i = 0; i < rollingWindow.WindowSize; i++) { Assert.AreEqual(i, rollingWindow.IndexOf(i)); } }
public void ContainsTest() { RollingWindow <int> rollingWindow = new RollingWindow <int>(5); for (int i = 0; i < rollingWindow.WindowSize; i++) { rollingWindow.Add(i); } for (int i = -5; i < 10; i++) { Assert.AreEqual((i >= 0) && (i < 5), rollingWindow.Contains(i)); } }
/// <summary> /// Creates a new instance of the <see cref="SignalBuffer"/> class. /// </summary> public SignalBuffer() { const int Sentinel = -1; m_blocks = new List <MeasurementBlock>(); m_blocks.Add(new MeasurementBlock(BlockSize)); m_removedBlockCounts = new RollingWindow <int>(StatWindow); m_blockLock = new object(); for (int i = 0; i < StatWindow; i++) { m_removedBlockCounts.Add(Sentinel); } }
public ShareClassMeanReversionAlphaModel( IEnumerable <Symbol> symbols, Resolution resolution = Resolution.Minute) { if (symbols.Count() != 2) { throw new ArgumentException("ShareClassMeanReversionAlphaModel: symbols parameter must contain 2 elements"); } _longSymbol = symbols.ToArray()[0]; _shortSymbol = symbols.ToArray()[1]; _insightPeriod = resolution.ToTimeSpan().Multiply(5); _sma = new SimpleMovingAverage(2); _positionWindow = new RollingWindow <decimal>(2); }
public override void Initialize() { SetStartDate(2006, 1, 1); SetEndDate(2020, 12, 1); SetCash(capital); AddSecurity(spy, Resolution.Daily); spyClosePrices = new RollingWindow <decimal>(StdPeriod); fastMA = EMA(spy, FastMAPeriod, Resolution.Daily); slowMA = EMA(spy, SlowMAPeriod, Resolution.Daily); SetWarmup(SlowMAPeriod); }
public void OldDataFallsOffBackOfWindow() { var window = new RollingWindow <int>(1); window.Add(0); Assert.IsFalse(window.IsReady); // add one more and the window is ready window.Add(1); Assert.AreEqual(0, window.MostRecentlyRemoved); Assert.AreEqual(1, window.Count); Assert.IsTrue(window.IsReady); }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { #region logging var algoname = this.GetType().Name; mylog.Debug(algoname); mylog.Debug(ondataheader); dailylog.Debug(algoname); dailylog.Debug(dailyheader); _transactions = new List <OrderTransaction>(); string filepath = AssemblyLocator.ExecutingDirectory() + "transactions.csv"; if (File.Exists(filepath)) { File.Delete(filepath); } #endregion //Initialize dates SetStartDate(_startDate); SetEndDate(_endDate); SetCash(_portfolioAmount); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, symbol, Resolution.Minute); // Indicators Price = new RollingWindow <IndicatorDataPoint>(14); // The price history // ITrend trend = new InstantaneousTrend(7); trendHistory = new RollingWindow <IndicatorDataPoint>(14); // The ITrendStrategy iTrendStrategy = new InstantTrendStrategy(symbol, 14, this); for (int i = 0; i < signals.Length; i++) { signals[i] = OrderSignal.doNothing; } _ticketsQueue = new ConcurrentQueue <OrderTicket>(); #region lists #endregion // for use with Tradier. Default is IB. //var security = Securities[symbol]; //security.TransactionModel = new ConstantFeeTransactionModel(1.0m); }
public void RemoveTest() { RollingWindow<int> rollingWindow = new RollingWindow<int>(5); for (int i = 0; i < rollingWindow.WindowSize; i++) rollingWindow.Add(i); rollingWindow.Remove(1); rollingWindow.Remove(3); Assert.AreEqual(3, rollingWindow.Count); Assert.AreEqual(0, rollingWindow[0]); Assert.AreEqual(2, rollingWindow[1]); Assert.AreEqual(4, rollingWindow[2]); }
/// <summary> /// Initializes a new instance of the <see cref="StandardDeviationOfReturnsVolatilityModel"/> class /// </summary> /// <param name="periods">The max number of samples in the rolling window to be considered for calculating the standard deviation of returns</param> /// <param name="resolution"> /// Resolution of the price data inserted into the rolling window series to calculate standard deviation. /// Will be used as the default value for update frequency if a value is not provided for <paramref name="updateFrequency"/>. /// This only has a material effect in live mode. For backtesting, this value does not cause any behavioral changes. /// </param> /// <param name="updateFrequency">Frequency at which we insert new values into the rolling window for the standard deviation calculation</param> /// <remarks> /// The volatility model will be updated with the most granular/highest resolution data that was added to your algorithm. /// That means that if I added <see cref="Resolution.Tick"/> data for my Futures strategy, that this model will be /// updated using <see cref="Resolution.Tick"/> data as the algorithm progresses in time. /// /// Keep this in mind when setting the period and update frequency. The Resolution parameter is only used for live mode, or for /// the default value of the <paramref name="updateFrequency"/> if no value is provided. /// </remarks> public StandardDeviationOfReturnsVolatilityModel( int periods, Resolution?resolution = null, TimeSpan?updateFrequency = null ) { if (periods < 2) { throw new ArgumentOutOfRangeException("periods", "'periods' must be greater than or equal to 2."); } _window = new RollingWindow <double>(periods); _resolution = resolution; _periodSpan = updateFrequency ?? resolution?.ToTimeSpan() ?? TimeSpan.FromDays(1); }
public void InsertTest() { RollingWindow <int> rollingWindow = new RollingWindow <int>(5); rollingWindow.Insert(0, 1); rollingWindow.Insert(1, 3); rollingWindow.Insert(0, 0); rollingWindow.Insert(2, 2); rollingWindow.Insert(4, 4); for (int i = 0; i < rollingWindow.Count; i++) { Assert.AreEqual(i, rollingWindow[i]); } }
public static bool CrossAbove(this RollingWindow <IndicatorDataPoint> window, decimal boundary, int lookback = 1, decimal tolerance = 0m) { var predicate = false; for (var i = 0; i < Math.Min(lookback, window.Count - 1); i++) { predicate = window[i] > boundary * (1 + tolerance) && window[i + 1] < boundary * (1 - tolerance); if (predicate) { break; } } return(predicate); }
public void ThrowsWhenIndexingOutOfRange() { var window = new RollingWindow <int>(1); Assert.IsFalse(window.IsReady); Assert.Throws <ArgumentOutOfRangeException>(() => { var x = window[0]; }); window.Add(0); Assert.AreEqual(1, window.Count); Assert.AreEqual(0, window[0]); Assert.IsTrue(window.IsReady); Assert.Throws <ArgumentOutOfRangeException>(() => { var x = window[1]; }); }
public void GetEnumeratorTest() { RollingWindow <int> rollingWindow = new RollingWindow <int>(5); int count = 0; for (int i = 0; i < rollingWindow.WindowSize + 1; i++) { rollingWindow.Add(i); } foreach (int i in rollingWindow) { Assert.AreEqual(++count, i); } }
public void WhenComputing_The_ResultIsTheArithmeticMeanOfAllDataInTheWindow() { const int period = 5; var sut = new MeanComputation(); var window = new RollingWindow <double>(period); for (int i = 0; i < 2 * period; i++) { window.Add(i); var result = sut.Compute(window); Assert.AreEqual(window.Average(), result); } }
public static bool CrossBelow(this RollingWindow <IndicatorDataPoint> window1, RollingWindow <IndicatorDataPoint> window2, int lookback = 1, decimal tolerance = 0m) { var predicate = false; for (var i = 0; i < Math.Min(lookback, Math.Min(window1.Count - 1, window2.Count - 1)); i++) { predicate = window1[i] < window2[i] * (1 - tolerance) && window1[i + 1] > window2[i + 1] * (1 + tolerance); if (predicate) { break; } } return(predicate); }
public void WhenComputing_Then_ResultIsTheSumOfAllDataInTheWindow() { const int period = 5; var sut = new SumOfSquaresComputation(); var window = new RollingWindow <double>(period); for (int i = 0; i < 2 * period; i++) { window.Add(i); var result = sut.Compute(window); Assert.AreEqual(window.Select(x => x * x).Sum(), result); } }
public override void OnSecuritiesChanged(SecurityChanges changes) { try { foreach (var addition in changes.AddedSecurities) { // momentum var slowIndicator = SMA(addition.Symbol, SlowSmaDays, Resolution.Daily); _slowSmas[addition.Symbol] = slowIndicator; //var slowIndicator = SMA(addition.Symbol, SlowSmaDays, Resolution.Daily); //var fastIndicator = SMA(addition.Symbol, FastSmaDays, Resolution.Daily); //var slope = fastIndicator.Minus(slowIndicator); // STO var stoIndicator = STO(addition.Symbol, StoDays, Resolution.Daily); var stoWindow = new RollingWindow <IndicatorDataPoint>(5); stoIndicator.Updated += (sender, dataPoint) => stoWindow.Add(dataPoint); _stos[addition.Symbol] = stoWindow; // MACD var macdIndicator = MACD(addition.Symbol, FastMacdDays, SlowMacdDays, SignalMacdDays, MovingAverageType.Exponential, Resolution.Daily); var macdWindow = new RollingWindow <IndicatorDataPoint>(5); macdIndicator.Histogram.Updated += (sender, dataPoint) => macdWindow.Add(dataPoint); _macdHistograms.Add(addition.Symbol, macdWindow); var history = History(addition.Symbol, SlowSmaDays, Resolution.Daily); foreach (var bar in history) { slowIndicator.Update(bar.EndTime, bar.Close); //fastIndicator.Update(bar.EndTime, bar.Close); stoIndicator.Update(bar); macdIndicator.Update(bar.EndTime, bar.Close); } } foreach (var removedSecurity in changes.RemovedSecurities) { _slowSmas.Remove(removedSecurity.Symbol); _stos.Remove(removedSecurity.Symbol); _macdHistograms.Remove(removedSecurity.Symbol); } } catch (Exception e) { Log($"Exception: OnSecuritiesChanged: {e.Message}"); } }
public static bool CrossBelow <T>(this RollingWindow <T> window, decimal boundary, int lookback = 1, decimal tolerance = 0m) where T : IBaseDataBar { var predicate = false; for (var i = 0; i < Math.Min(lookback, window.Count - 1); i++) { predicate = window[i].Open > boundary * (1 + tolerance) && window[i].Close < boundary * (1 - tolerance); if (predicate) { break; } } return(predicate); }
/// <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, 1); // Set Start Date SetEndDate(2013, 11, 1); // Set End Date SetCash(100000); // Set Strategy Cash // Find more symbols here: http://quantconnect.com/data AddEquity("SPY", Resolution.Daily); // Creates a Rolling Window indicator to keep the 2 TradeBar _window = new RollingWindow <TradeBar>(2); // For other security types, use QuoteBar // Creates an indicator and adds to a rolling window when it is updated SMA("SPY", 5).Updated += (sender, updated) => _smaWin.Add(updated); _smaWin = new RollingWindow <IndicatorDataPoint>(5); }
public void AddsData() { var window = new RollingWindow<int>(1); window.Add(1); Assert.AreEqual(1, window.Count); Assert.AreEqual(1, window.Samples); Assert.AreEqual(1, window.Size); Assert.IsFalse(window.IsReady); // add one more and the window is ready window.Add(2); Assert.AreEqual(1, window.Count); Assert.AreEqual(2, window.Samples); Assert.AreEqual(1, window.Size); Assert.IsTrue(window.IsReady); }
public void RetievesNonZeroIndexProperlyAfterReset() { var window = new RollingWindow <int>(3); window.Add(0); Assert.AreEqual(1, window.Count); Assert.AreEqual(0, window[0]); window.Add(1); Assert.AreEqual(2, window.Count); Assert.AreEqual(0, window[1]); Assert.AreEqual(1, window[0]); window.Add(2); Assert.AreEqual(3, window.Count); Assert.AreEqual(0, window[2]); Assert.AreEqual(1, window[1]); Assert.AreEqual(2, window[0]); window.Add(3); Assert.AreEqual(3, window.Count); Assert.AreEqual(1, window[2]); Assert.AreEqual(2, window[1]); Assert.AreEqual(3, window[0]); window.Reset(); window.Add(0); Assert.AreEqual(1, window.Count); Assert.AreEqual(0, window[0]); window.Add(1); Assert.AreEqual(2, window.Count); Assert.AreEqual(0, window[1]); Assert.AreEqual(1, window[0]); window.Add(2); Assert.AreEqual(3, window.Count); Assert.AreEqual(0, window[2]); Assert.AreEqual(1, window[1]); Assert.AreEqual(2, window[0]); window.Add(3); Assert.AreEqual(3, window.Count); Assert.AreEqual(1, window[2]); Assert.AreEqual(2, window[1]); Assert.AreEqual(3, window[0]); }
public void AddsData() { var window = new RollingWindow <int>(1); window.Add(1); Assert.AreEqual(1, window.Count); Assert.AreEqual(1, window.Samples); Assert.AreEqual(1, window.Size); Assert.IsFalse(window.IsReady); // add one more and the window is ready window.Add(2); Assert.AreEqual(1, window.Count); Assert.AreEqual(2, window.Samples); Assert.AreEqual(1, window.Size); Assert.IsTrue(window.IsReady); }
public void AddTest() { RollingWindow<int> rollingWindow = new RollingWindow<int>(5); for (int i = 0; i < rollingWindow.WindowSize; i++) { Assert.AreEqual(i, rollingWindow.Count); rollingWindow.Add(i); Assert.AreEqual(i, rollingWindow[i]); } Assert.AreEqual(rollingWindow.WindowSize, rollingWindow.Count); rollingWindow.Add(rollingWindow.WindowSize); Assert.AreEqual(rollingWindow.WindowSize, rollingWindow.Count); for (int i = 0; i < rollingWindow.WindowSize; i++) Assert.AreEqual(i + 1, rollingWindow[i]); }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { //Initialize dates SetStartDate(_startDate); SetEndDate(_endDate); SetCash(_portfolioAmount); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, symbol, Resolution.Daily); // Indicators Price = new RollingWindow<IndicatorDataPoint>(14); // The price history trendHistory = new RollingWindow<IndicatorDataPoint>(14); // ITrend trend = new InstantaneousTrend(7); _ticketsQueue = new List<OrderTicket>(); #region lists signalInfos.Add(new SignalInfo { Id = 8, IsActive = true, SignalJson = string.Empty, Value = OrderSignal.doNothing, InternalState = string.Empty, SignalType = typeof(Sig9) }); foreach (SignalInfo s in signalInfos) { s.IsActive = false; if (s.Id == LiveSignalIndex) { s.IsActive = true; } } #endregion // for use with Tradier. Default is IB. //var security = Securities[symbol]; //security.TransactionModel = new ConstantFeeTransactionModel(1.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> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { //mylog.Debug(transheader); mylog.Debug(ondataheader); //Initialize dates SetStartDate(2015, 5, 13); SetEndDate(2015, 5, 13); SetCash(25000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, symbol, Resolution.Minute); Price = new RollingWindow<IndicatorDataPoint>(14); hma7 = new HullMovingAverage("hma7", 7); hma14 = new HullMovingAverage("hma14",14); hma28 = new HullMovingAverage("hma28",28); instantTrend = new RollingWindow<IndicatorDataPoint>(7); }
/// <summary> /// The Deserializing constuctor /// </summary> /// <param name="info">the bag into which the serialized data was put</param> /// <param name="context">the stream to get the data from.</param> public Sig2(SerializationInfo info, StreamingContext context) { string s = (string)info.GetValue("Symbol", typeof(string)); _symbol = new Symbol(s); //_algorithm = (QCAlgorithm)info.GetValue("algorithm", typeof(QCAlgorithm)); Id = (int)info.GetValue("Id", typeof(int)); trendHistory = new RollingWindow<decimal>(3); nEntryPrice = (decimal)info.GetValue("nEntryPrice", typeof(decimal)); xOver = (int)info.GetValue("xOver", typeof(int)); nTrig = (decimal)info.GetValue("nTrig", typeof(decimal)); orderFilled = (Boolean)info.GetValue("orderFilled", typeof(Boolean)); maketrade = (Boolean)info.GetValue("maketrade", typeof(Boolean)); trendArray = (decimal[])info.GetValue("trendArray", typeof(decimal[])); foreach (decimal t in trendArray) { trendHistory.Add(t); } RevPct = 1.0015m; RngFac = .35m; }
/// <summary> /// Initializes a new instance of the <see cref="ITrendStrategy"/> class. /// </summary> /// <param name="period">The period of the Instantaneous trend.</param> public ITrendStrategyJJ(Indicator price, int period, decimal tolerance = 0.001m, decimal revetPct = 1.0015m, RevertPositionCheck checkRevertPosition = RevertPositionCheck.vsTrigger) { _price = price; ITrend = new InstantaneousTrend(period).Of(price); ITrendMomentum = new Momentum(2).Of(ITrend); MomentumWindow = new RollingWindow<decimal>(2); Position = StockState.noInvested; EntryPrice = null; ActualSignal = OrderSignal.doNothing; _tolerance = tolerance; _revertPCT = revetPct; _checkRevertPosition = checkRevertPosition; ITrendMomentum.Updated += (object sender, IndicatorDataPoint updated) => { if (ITrendMomentum.IsReady) MomentumWindow.Add(ITrendMomentum.Current.Value); if (MomentumWindow.IsReady) CheckSignal(); }; }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { //mylog.Debug(transheader); mylog.Debug(ondataheader); //Initialize dates SetStartDate(_startDate); SetEndDate(_endDate); SetCash(22000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, symbol, Resolution.Minute); Price = new RollingWindow<IndicatorDataPoint>(14); cycleSignal = new RollingWindow<IndicatorDataPoint>(14); cycle = new CyberCycle(7); Price = new RollingWindow<IndicatorDataPoint>(14); diff = new RollingWindow<IndicatorDataPoint>(20); standardDeviation = new StandardDeviation(30); fish = new InverseFisherTransform(10); fishHistory = new RollingWindow<IndicatorDataPoint>(7); fishDirectionHistory = new RollingWindow<IndicatorDataPoint>(7); }
/// <summary> /// Initializes a new instance of the <see cref="ITrendStrategy"/> class. /// </summary> /// <param name="period">The period of the Instantaneous trend.</param> public MultiSymbolStrategy(Indicator price, int period, decimal tolerance = 0.001m, decimal revetPct = 1.0015m, RevertPositionCheck checkRevertPosition = RevertPositionCheck.vsTrigger) { _price = price; sma = new SimpleMovingAverage(period).Of(price); SMAMomentum = new Momentum(2).Of(sma); MomentumWindow = new RollingWindow<decimal>(2); Position = StockState.noInvested; EntryPrice = null; ActualSignal = OrderSignal.doNothing; _tolerance = tolerance; _revertPCT = revetPct; _checkRevertPosition = checkRevertPosition; SMAMomentum.Updated += (object sender, IndicatorDataPoint updated) => { if (SMAMomentum.IsReady) MomentumWindow.Add(SMAMomentum.Current.Value); if (MomentumWindow.IsReady) CheckSignal(); }; }
/// <summary> /// Swiss Army Knife indicator by John Ehlers /// </summary> /// <param name="name"></param> /// <param name="period"></param> /// <param name="delta"></param> /// <param name="tool"></param> public SwissArmyKnife(string name, int period, double delta, SwissArmyKnifeTool tool) : base(name) { _period = period; _tool = tool; _delta = delta; _filt = new RollingWindow<double>(2) { 0.0, 0.0 }; _price = new RollingWindow<double>(3); double alpha; double beta; double gamma; if (_tool == SwissArmyKnifeTool.Gauss) { beta = 2.415 * (1 - Math.Cos(2 * Math.PI / _period)); alpha = -beta + Math.Sqrt(Math.Pow(beta, 2) + 2d * beta); _c0 = alpha * alpha; _a1 = 2d * (1 - alpha); _a2 = -(1 - alpha) * (1 - alpha); } if (_tool == SwissArmyKnifeTool.Butter) { beta = 2.415 * (1 - Math.Cos(2 * Math.PI / _period)); alpha = -beta + Math.Sqrt(Math.Pow(beta, 2) + 2d * beta); _c0 = alpha * alpha / 4d; _b1 = 2; _b2 = 1; _a1 = 2d * (1 - alpha); _a2 = -(1 - alpha) * (1 - alpha); } if (_tool == SwissArmyKnifeTool.HighPass) { alpha = (Math.Cos(2 * Math.PI / _period) + Math.Sin(2 * Math.PI / _period) - 1) / Math.Cos(2 * Math.PI / _period); _c0 = (1 + alpha) / 2; _b1 = -1; _a1 = 1 - alpha; } if (_tool == SwissArmyKnifeTool.TwoPoleHighPass) { beta = 2.415 * (1 - Math.Cos(2 * Math.PI / _period)); alpha = -beta + Math.Sqrt(Math.Pow(beta, 2) + 2d * beta); _c0 = (1 + alpha) * (1 + alpha) / 4; _b1 = -2; _b2 = 1; _a1 = 2d * (1 - alpha); _a2 = -(1 - alpha) * (1 - alpha); } if (_tool == SwissArmyKnifeTool.BandPass) { beta = Math.Cos(2 * Math.PI / _period); gamma = (1 / Math.Cos(4 * Math.PI * _delta / _period)); alpha = gamma - Math.Sqrt(Math.Pow(gamma, 2) - 1); _c0 = (1 - alpha) / 2d; _b0 = 1; _b2 = -1; _a1 = -beta * (1 - alpha); _a2 = alpha; } }
/// <summary> /// Resets to the initial state /// </summary> public override void Reset() { _period = 20; _delta = 0.1; _filt = new RollingWindow<double>(2) { 0.0, 0.0 }; _price = new RollingWindow<double>(3); base.Reset(); }
/// <summary> /// Initializes a new instance of the <see cref="MSAStrategy" /> class. /// </summary> /// <param name="smoothedSeries">The smoothed series.</param> /// <param name="previousDaysN">How many daily means will be used to estimate the thresholds.</param> /// <param name="runsPerDay">How many runs will be used to estimate the daily mean.</param> /// <param name="minRunThreshold">The minimum run threshold.</param> /// <param name="DailyIndicatorReset">if set to <c>true</c> [daily indicator reset].</param> public MSAStrategy(IndicatorBase<IndicatorDataPoint> smoothedSeries, int previousDaysN = 3, int runsPerDay = 5, decimal minRunThreshold = 0.0001m, bool DailyIndicatorReset = true) { _runsPerDay = runsPerDay; _actualRun = 1m; _turnAround = false; _minRunThreshold = minRunThreshold; _dailyIndicatorReset = DailyIndicatorReset; _smoothedSeries = smoothedSeries; _smoothedSeriesROC = new RateOfChange(1).Of(_smoothedSeries); _SSROCRW = new RollingWindow<IndicatorDataPoint>(2); _todayRuns = new List<decimal>(); _previousDaysDownwardRuns = new RollingWindow<decimal>(previousDaysN); _previousDaysUpwardRuns = new RollingWindow<decimal>(previousDaysN); ActualSignal = OrderSignal.doNothing; Position = StockState.noInvested; _smoothedSeriesROC.Updated += (object sender, IndicatorDataPoint updated) => { if (_smoothedSeriesROC.IsReady) _SSROCRW.Add(updated); if (_SSROCRW.IsReady) RunStrategy(); if (_SSROCRW.IsReady && IsReady) CheckSignal(); }; }
public void ResetsProperly() { var window = new RollingWindow<int>(3) { 0, 1, 2 }; window.Reset(); Assert.AreEqual(0, window.Samples); }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { // mylog.Debug(",CurrentBar,Time,Price,smooth,low,i1,cycle0,cycle1,cycle2,fish,medianDelta,DC,instaperiod, v2,DCPeriod,realpart,imagpart,dcphase"); mylog.Debug(ondataheader); //mylog.Debug(",Time,CurrentBar,Direction,TradeProfit,,Price,Profit,HoldingCost,FillQty,Fees,TransAmt"); //mylog.Debug(transheader); //Initialize SetStartDate(2015, 05, 12); SetEndDate(2015, 05, 12); SetCash(25000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, _symbol, Resolution.Minute); _indicators = new AlgoIndicators { //BB = BB(_symbol, 20, 1, MovingAverageType.Simple, Resolution.Daily), RSI = RSI(_symbol, 14, MovingAverageType.Simple, Resolution.Daily), //ATR = ATR(_symbol, 14, MovingAverageType.Simple, Resolution.Daily), //EMA = EMA(_symbol, 14, Resolution.Daily), //SMA = SMA(_symbol, 14, Resolution.Daily), MACD = MACD(_symbol, 12, 26, 9, MovingAverageType.Simple, Resolution.Minute) //AROON = AROON(_symbol, 20, Resolution.Daily), //MOM = MOM(_symbol, 20, Resolution.Daily), //MOMP = MOMP(_symbol, 20, Resolution.Daily), //STD = STD(_symbol, 20, Resolution.Daily), //MIN = MIN(_symbol, 14, Resolution.Daily), // by default if the symbol is a tradebar type then it will be the min of the low property //MAX = MAX(_symbol, 14, Resolution.Daily), // by default if the symbol is a tradebar type then it will be the max of the high property //open = new WindowIndicator<IndicatorDataPoint>(4) //Ft = FT(_symbol, samplesize, Resolution.Minute), //Rvi = RVI(_symbol, samplesize, Resolution.Minute) }; //open = new RollingWindow<IndicatorDataPoint>(samplesize); //close = new RollingWindow<IndicatorDataPoint>(samplesize); //high = new RollingWindow<IndicatorDataPoint>(samplesize); //low = new RollingWindow<IndicatorDataPoint>(samplesize); //i1 = new RollingWindow<IndicatorDataPoint>(samplesize); //instperiod = new RollingWindow<IndicatorDataPoint>(samplesize); //v2 = new RollingWindow<IndicatorDataPoint>(samplesize); //v1 = new RollingWindow<IndicatorDataPoint>(samplesize); //Rvi = new RollingWindow<IndicatorDataPoint>(samplesize); unrealized = new RollingWindow<IndicatorDataPoint>(samplesize); iFishes = new RollingWindow<IndicatorDataPoint>(samplesize); RsiHistory = new RollingWindow<IndicatorDataPoint>(samplesize); //Signal = new RollingWindow<IndicatorDataPoint>(samplesize); //maxRvi = new Maximum("RVI_Max", samplesize); //minRvi = new Minimum("RVi_Min", samplesize); //maxSignal = new Maximum("Sig_Max", samplesize); //minSignal = new Minimum("Sig_Min", samplesize); fish = new FisherTransform(samplesize); ifish = new InverseFisherTransform(samplesize); //Crossing = new RollingWindow<IndicatorDataPoint>(samplesize); //FisherHistory = new RollingWindow<IndicatorDataPoint>(samplesize); Rvi = new RelativeVigorIndex(_symbol, samplesize); for (int x = 0; x < samplesize; x++) { //open.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); //close.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); //high.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); //low.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); //i1.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); //instperiod.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); //v1.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); //v2.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); //Rvi.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); unrealized.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); iFishes.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); //Signal.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); //Crossing.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m)); } }