Back

Indicator on combined data

Hi Team,

What is the best way to create indicator on combined data?
For example, in pair trading, you want to long/short Microsoft and Apple. And I want to create MACD on the price difference of the two.
Thank you.

Jianwei
Update Backtest








You can do this quite easily:

public class PairsTradingAlgorithm : QCAlgorithm
{
decimal _diff;
MovingAverageConvergenceDivergence _macd;

//Initialize the data and resolution you require for your strategy:
public override void Initialize()
{
//Start and End Date range for the backtest:
SetStartDate(2013, 1, 1);
SetEndDate(2014, 1, 1);

//Cash allocation
SetCash(25000);

//Add as many securities as you like. All the data will be passed into the event handler:
AddSecurity(SecurityType.Equity, "AAPL", Resolution.Minute);
AddSecurity(SecurityType.Equity, "MSFT", Resolution.Minute);

//Initialise MACD
_macd = new MovingAverageConvergenceDivergence(12, 26, 9, MovingAverageType.Simple);
}

//Data Event Handler: All data arrives here in slices.
public override void OnData(Slice slice)
{
if (!slice.ContainsKey("MSFT") || !slice.ContainsKey("AAPL")) return;

//Calculate difference MSFT and AAPL
_diff = slice["MSFT"].Close - slice["AAPL"].Close;

//Update MACD
_macd.Update(slice.Time, _diff);

//Calculate MACD difference
decimal signalDeltaPercent = (_macd - _macd.Signal)/_macd.Fast;
var tolerance = 0.0025m;

//If MACD gives signal and we're not in a position right now
if (!Portfolio.HoldStock && signalDeltaPercent > tolerance)
{
//Calculate quantities of individual positions
int quantityA = (int)Math.Floor(0.5M*Portfolio.Cash/slice["MSFT"].Close);
int quantityB = (int)Math.Floor(0.5M*Portfolio.Cash/slice["AAPL"].Close);

//Go long on first, go short on second
Order("MSFT", quantityA);
Order("AAPL", -quantityB);
} else if (signalDeltaPercent < -tolerance) {
//If MACD gives opposite signal
Liquidate("MSFT");
Liquidate("AAPL");
}

//Plot MACD lines
Plot("MACD", "Difference", _diff);
Plot("MACD", _macd.Fast, _macd.Slow);
}
}


You can clone this project below. Mind you: I am not sure whether my trading logic makes any sense. You can change the trading rules to your liking. I'm just showing you an example of how to write such a pair-trading strategy.
0


That is one way to do it, but there's actually an even easier way :)

We've built a system which I call 'composable indicators'. This basically allows you to build new indicators from other indicators. We can define indicators that pump price data using Identity:var msft = Identity("MSFT");
var aapl = Identity("AAPL");
We can then take these and form more complex indicators from them, such as a difference:var diff = msft.Minus(aapl);We can then define a MACD on the difference using:var macdDiff = new MovingAverageConvergenceDivergence(12, 26, 9).Of(diff);
All of the above indicators will be auto-updating and should be defined in the algorithm's initialize method. Have a peek at the indicator extension methods here.
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.


@MichaelH Cool! Didn't know that. Learning something new every day here at QC :)
0

@MichaelH I just noticed a little bug in the highcharts representation of your backtest.

See picture below:



A tiny bug, but might be worth removing in the backtest visualisation js.
0

Very helpful. Thank you guys!
0

Hi MichaelH ,

I'm trying a CAD/CL1 pair for this algorithm.
Since Cl1 is future contract, so I try to refer to the "QCU How Do I Import Futures Data" example and create a "QuandlFuture" class.
However, met some error in the data update of Identity:

Runtime Error: Received type of Quandl but expected QuandlFuture
Parameter name: data (Open Stacktrace)

Am I doing correctly or is there a way to get around with this?
Thank you!

Jianwei
0

Attaching code as below.
1


Hey @Jianwei, it looks like a deficiency in the QuandlFuture type, in that it actually creates Quandl instances instead of QuandlFuture instances! In the long run we'll update the how do I import quandl futures data, in the short term, we'll need to manually create the correct consolidator that is capable of handling Quandl instances instead of QuandlFuture instances.

Attached is the working code.
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.


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