Back

Indicator Examples (BB, MACD, SMA, EMA, RSI, ATR)

By popular request I've developed an example project with the common indicators, including: Bollinger Bands, Simple Moving Average, Exponential Moving Average, Relative Strength Index, Average True Range and MACD. Down the bottom of the algorithm we plot them together with price. I've also set it up to use Daily consolidators - this way the plots look like characteristic ones you'll see on other stock charting websites.

The engine updates the indicators automatically and feeds the value through to the algorithms output for charting! Its a pretty cool system under the hood. I'd recommend looking at the Github project.
Update Backtest






The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.



Standard deviation?
0

Thanks @Tadas -- I've updated the QCU algorithm to include standard deviation, aroon and momentum as well.

You can see all the indicators here: https://github.com/QuantConnect/Lean/blob/master/Algorithm/QCAlgorithm.Indicators.cs
1

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Thanks, @Jared, though I saw somewhere what values go to different indicators :D

Also, searched, but didn't found how to use, let's say OnData(ImportedData id) along with usual OnData(TradeBars data)?
0

I'll try push new documentation this weekend @TT - for now you can look at the classes themselves to know the properties of each indicator. E.g. Aroon Up - https://github.com/QuantConnect/Lean/blob/master/Indicators/AroonOscillator.cs#L31

I've updated the algorithm again to include an example of a RSI indicator on custom data. It takes 3 lines instead of one because you need to tell us how to consolidate it together, and then manually register/subscribe the indicator class for data updates.
1

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Ah, ok, thank you, now starting to pick it up. QC platform is too much flexible :) Missing piece for me was:

var bitcoinIdentityConsolidator = new IdentityDataConsolidator();
0

I have some questions regarding this example. How do I modify the code the indicators are being calculated on 30 minute bars instead of daily or minute bar. I'm not sure how to setup and access the indicators to work on multiple securities.

ex.

public void OnData(TradeBars data)
{

foreach(var symbol in Securities.Keys)
{
if (data["symbol"].High > _bb.UpperBand["symbol"] ) { //do something };
}

}
0

Hey @Johnny! I like to use a pattern I refer to as SymbolData. Here's a link to a thread showing an example of it.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Hi Michael,

Thank you for your wonderful suggestion. I modified the basic template to handle multiple securities. However, I'm still not sure what to do regarding the resolution.

Is it possible for QuantConnect to use multiple resolutions with each indicators? Ex. use 5 minute bars for RSI, 10 minutes bars for EMA, and 30 minute bars for SMA?
1

Sounds like you need to use the consolidator system! Consolidators can take high resolution data (tick,second,minute, ect...) and aggregate it into lower resolution data (5min, 45 min, anything...).

Have a peak at this thread which shows how to make a consolidator and indicators that depend on the consolidator. For multiple time frames, you'll need multiple consolidators.

An important note, one consolidator can only be used with one symbol! So if you're doing multiple symbols you'll need one consolidator per symbol per time frame (5min, 10min, ect...).
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Would something like this work if I wanted to create Bollinger Bands from 15 minutes bars? Also, is there a way for me to pass in the bar's open, high, low, and close into the SymbolData class? Thanks again for your help.

public SymbolData(string symbol, QCAlgorithm algorithm)
{

Symbol = symbol;
_bb = new BollingerBands(50, 3, MovingAverageType.Simple);
algorithm.RegisterIndicator(Symbol, _bb, TimeSpan.FromMinutes(15));
}
1

The bollingerbands look to be created correctly. Try plotting it to verify. As for passing in the OHLC data, there are various ways to do this. Do you want a method to be called with the data?

You could define a SymbolData.OnData(TradeBar bar) which could be called from your algorithm's OnData method.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Jared, did you mean you plotted the indicators as well as price or on top of price, because when i run it i get separate charts. Have you guys figured out a solution to plotting ex. 2 different EMAs on top of price?
0

The following code will plot two EMAs on top of the SPY closing price on the registered resolution:var price = Identity("SPY");
var fast = EMA("SPY", 7);
var slow = EMA("SPY", 14);
PlotIndicator("SPY", price, fast, slow);


Take a peek at the attached code below which creates a new plot called 'SPY' for the price and EMAs.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Is there a way to put this on the "Stockplot" that shows when the algorithm makes moves in the market?
0

oh nice, great thank you Michael! Good question Stephen that would also be very helpful
0

I think it would be easier (and more general) to place the execution plots on the custom indicator chart. For example, if you're working with a MACD and RSI on separate charts, it may be helpful to plot a scatter plot on each of those charts with buy/sell points. Have a look at the QCU How Do I Create Custom Charts? available in the university tab. This details how to define some custom charts, including buy/sell points.

If you want price data overlayed on your custom chart, you can use:PlotIndicator("MyCustomChartName", Identity("SPY", Resolution.Daily));
This will add the closing daily spy price as a series to the 'MyCustomChartName' chart.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


You're completely right. I got that up and running. Thank you! One more question now that I have that:

I'm using this plot to help debug my algorithm. Is there any way to adjust the vertical scale? I know you can adjust the horizontal easily, but sometimes it's still tough to see.

Thank you again!
0

Sadly we can't currently adjust the vertical scale
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Ah, that's ok. Thank you again for the help!!!
0

Is there a way to have these calculate on the close of the set resolution?

fast = EMA(Symbol, 25, Resolution.Minute);

something like this (obviously doesn't work but sort of shows what I mean):

fast = EMA(Symbol, 25, Resolution.Minute.Close);
0

By default any single dimension indicator (SMA, EMA, ect..) uses the closing of the bar. If you'd like to use something else, you can specify a function that selects what value to use:fast = EMA(Symbol, 25, Resolution.Minute, baseData => ((TradeBar)baseData).High);
There are some helpers to make this easier, so the above could be written as:fast = EMA(Symbol, 25, Resolution.Minute, Field.High);
Here's a link to the Field class.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


I'm getting this following error when I tried to use the consolidator in the backtest. What is the proper way to register the indicator?

"Backtest Error: Error initializing algorithm: Type mismatch found between consolidator and indicator for symbol: DIA.Consolidator outputs type TradeBar but indicator expects input type IndicatorDataPoint"

public SymbolData(string symbol, QCAlgorithm algorithm)
{
Symbol = symbol;
_bb = new BollingerBands(100, 3, MovingAverageType.Simple);
_atr = new AverageTrueRange(100, MovingAverageType.Simple);
algorithm.RegisterIndicator(Symbol, _bb, TimeSpan.FromMinutes(15));
algorithm.RegisterIndicator(Symbol, _atr, TimeSpan.FromMinutes(30));
}
0

Hey Johnny, you'll need to include some of your Initialize code. From the error message the symbol with issue is 'DIA'. Is this custom data? The error message is saying you're trying to register an indicator that accepts a single value (such as close, or high) but passing a full TradeBar. You can try appending 'Field.Close' to the RegisterIndicator call for '_bb'. If you still have issues please share the full algorithm and we can be of further assistance!
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Hey Michael,

Thanks for taking a look at my code. DIA is an ETF that tracks the Dow 30. It is a standard symbol in the quantconnect database. If I try to append the Field.Close then I must use the quantconnection resolution class instead of time span. There is currently a method that converts resolution to timespan. Do you think it would be possible to implement a feature that convert timespan to resolution allowing us to create our own custom resolutions.

Ex. TimeSpan.FromMinutes(15).ToResolution();

Also, the feature using strings for symbol is now deprecated. Where do I find a symbol's sid? That information is not displayed in the data manager.

using System;
using QuantConnect.Data.Market;
using QuantConnect.Securities;
using QuantConnect.Indicators;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Algorithm.CSharp.MyTradingStrategies;

namespace QuantConnect.Algorithm
{
public class BollingerBandsAlgorithm : QCAlgorithm
{
class SymbolData
{
public readonly string Symbol;
public readonly BollingerBands _bb;
public readonly AverageTrueRange _atr;
public bool isReady { get { return _bb.IsReady && _atr.IsReady; } }

public SymbolData(string symbol, QCAlgorithm algorithm)
{
Symbol = symbol;
_bb = new BollingerBands(100, 3, MovingAverageType.Simple);
_atr = new AverageTrueRange(100, MovingAverageType.Simple);
algorithm.RegisterIndicator(Symbol, _bb, TimeSpan.FromMinutes(15));
algorithm.RegisterIndicator(Symbol, _atr, TimeSpan.FromMinutes(15));
}
}
private List symbols = new List()
{ "DIA", "DXJ", "EEM", "EFA", "EWZ",
"FXI", "GDX","IWM", "IYR", "QQQ",
"SPY", "XLB", "XLE","XLF", "XLI",
"XLK", "XLP", "XLU", "XLV", "XLY" };

private Dictionary Symbols = new Dictionary();

//Initialize the data and resolution you require for your strategy:
public override void Initialize()
{
//Initialize
SetStartDate(2007, 1, 1);
SetEndDate(DateTime.Now.AddDays(-1));
SetCash(100000);

foreach (var symbol in symbols)
{
AddSecurity(SecurityType.Equity, symbol, Resolution.Minute);
Symbols.Add(symbol, new SymbolData(symbol, this));
}
}

public void OnData(TradeBars data)
{
foreach (var symbolData in Symbols.Values)
{
if (!symbolData.isReady || data.ContainsKey(symbolData.Symbol))
return;

if (!Portfolio.HoldStock)
{
var _buyPrice = symbolData._bb.LowerBand;
var _buySignal = data[symbolData.Symbol].Close > _buyPrice;
if (_buySignal) { SetHoldings(symbolData.Symbol, 1); }
}
else
{
var _sellPrice = symbolData._bb.UpperBand;
var _sellSignal = data[symbolData.Symbol].Close > _sellPrice;
if (_sellSignal) { Liquidate(symbolData.Symbol); }
}
}
}
}
}
0

Hey Johnny, I've added the requested overload. It will be available in the next deploy. Just a head up, it won't work with the ATR since the field selector required for ATR requires a TradeBar.

The ToResolution method is a great idea, but may require a little thought on our end since it is a widely used enumeration.

An alternate solution is to have your SymbolData class accept a TradeBarConsolidator which you could create from your Initialize method:var consolidator = new TradeBarConsolidator(TimeSpan.FromMinutes(15));
Then there are overloads available that accept the Field parameter.
0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Update Backtest





0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Loading...

This discussion is closed