Back

Understanding Alpha Algorithm Framework

I ran the BasicTemplateAlgoFramework sample, feeding in 4 currency pairs as data. The results are a bit confusing. Hopefully someone could help explain:

1. The algo on the whole makes a loss (based on equity), however, has $2,445 unrealized profit. However, The Overview says all 110 trades resulted in a loss (average win = 0. loss rate = 100%). How does this stack up with the overall equity and the equity curve which made a V shape ?

2. How do I see the direction score by assets ? i.e. which currency pair performs best / worst ?

3. Is there anyway to plot a normal curve for probability of wins so that we could find out the optimal values for a specific parameter ?

Update Backtest








As far as I understand the Win/Loss rate only reflects closed trades so if you only closed losses and leave the winners open it would show that 0/100.

You could track the returns of each asset, I'm unsure the code in python but in c# you could schedule an event monthly or at whatever frequency and log (Portfolio[symbol].Profit + Portfolio[symbol].UnrealizedProfit). This might do what you want it to.

I don't know about the last one, sorry!

0

Hey Rachel! Great to see you digging into the Framework. Your questions are also great and in our "to do list". We're planning on making a report card for each of the modules so you can get detailed analysis on the assets in a universe and alpha signals etc. 

For now the only way to do what you're asking though is manually; so please check out the Charting API and add anything you need there!

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 guys! Thanks for your guidance. Really can't wait to see my first alpha working.

I created my own Alpha class and would like to call it in my Main program. How do I do this ?

So when I do:

self.SetAlpha(MACDMomentumAlphaModel(12,26,9,MovingAverageType.Exponential, Resolution.Minute))

During runtime I get the following error:

During the algorithm initialization, the following exception has occurred: NameError : name 'MACDMomentumAlphaModel' is not defined
at Initialize in main.py:line 91
NameError : name 'MACDMomentumAlphaModel' is not defined

0

Hi, is it possible to provide more code? NameErrors is an error that occurs when Python attempts to load an object that doesn’t exist elsewhere in the callstack. The error could be how MACDMomentumAlphaModel is defined but without the source code, it is hard to determine where exactly the issue is. The links below point to a template for the algorithm framework and a properly defined alpha model. Comparing the differences (code/import statements) between the MACDMomentumAlphaModel and ConstantAlphaModel would be a good place to start. 

https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/BasicTemplateFrameworkAlgorithm.pyhttps://github.com/QuantConnect/Lean/blob/master/Algorithm.Framework/Alphas/ConstantAlphaModel.py
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.


The code MacdMomentumAlphaModel.py is in my original post in this Discussion. It was cloned from MacdAlphaModel.py, one of the examples provided. I just renamed it and called it within Main.py (the main.py included was not updated yet) replacing ConstantAlphaModel.

I noticed that MacdAlphaMdel, and all the Alphas reside in the Alpha package.

Do I have to specify the package name in the header of my files, like in Java ? If so, how do I do that ?

In anycase, I would like to maintain this Alpha class within my own workspace and thus it cannot belong to the samples packages.

0

In Python a class is imported via: from file import class

The backtest below has the code running. After importing the class into the main file, there was also the issue where MACDMomentumAlphaModel is the file name and MacdMomentumAlphaModel is the class name. The case of the class name matters when initializing a class as well. This should get you started:

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.


In which class and method do we initialize RollingWindow and update the window ? Am looking for OnData everywhere in the framework to no avail. I have tried doing it in SymbolData but the program cold not find the window.

0

Also, having problem with logging in MACDMomentumAlphaModel. It is not recognizing self.Debug(). 

Runtime Error: AttributeError : 'MacdMomentumAlphaModel' object has no attribute 'Debug'
at Update in MACDMomentumAlphaModel.py:line 106What could be the cause ?
0

Managed to resolve the Debug problem....that is, by doing algorithm.Debug instead.

But the Rollingwindow implementation remains a mystery in the framework. Hope to get some samples here.

0

RollingWindow will get initialized in OnSecuritiesChanged, so a new rolling window will be added for each new security in the universe. Once the RollingWindow is initialized it should be saved into the SymbolData class. One thing to note is the Reset() method, because if you don't reset the indicator and rolling window, then they'll still have data from the last time the security was in the universe. The code below should get you started:

public override void OnSecuritiesChanged(QCAlgorithmFramework algorithm, SecurityChanges changes)
{
foreach (var added in changes.AddedSecurities)
{
SymbolData symbolData;
if (!_symbolDataBySymbol.TryGetValue(added.Symbol, out symbolData))
{
// create fast/slow EMAs and windows
var fastWindow = new RollingWindow<IndicatorDataPoint>(5);
var fast = algorithm.EMA(added.Symbol, _fastPeriod, _resolution);
fast.Updated += (sender, updated) => fastWindow.Add(updated);
var slowWindow = new RollingWindow<IndicatorDataPoint>(5);
var slow = algorithm.EMA(added.Symbol, _slowPeriod, _resolution);
slow.Updated += (sender, updated) => slowWindow.Add(updated);
_symbolDataBySymbol[added.Symbol] = new SymbolData
{
Security = added,
Fast = fast,
FastWindow = fastWindow,
Slow = slow,
SlowWindow = slowWindow
};
}
else
{
// a security that was already initialized was re-added, reset the indicators and windows
symbolData.Fast.Reset();
symbolData.FastWindow.Reset();
symbolData.Slow.Reset();
symbolData.SlowWindow.Reset();
}
}
}

private class SymbolData
{
public Security Security { get; set; }
public Symbol Symbol => Security.Symbol;
public ExponentialMovingAverage Fast { get; set; }
public ExponentialMovingAverage Slow { get; set; }
public RollingWindow<IndicatorDataPoint> FastWindow { get; set; }
public RollingWindow<IndicatorDataPoint> SlowWindow { get; set; }
public bool FastIsOverSlow { get; set; }
public bool SlowIsOverFast => !FastIsOverSlow;
}
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.


Any possibilities of  sharing the python version of the above ?

From my guess above, do we have to attach all indicators and rolling windows to algorithm context, instead of "self" ?

So in SymbolData, we have initialize an empty algorithm.variable for the RollingWindow. Then in OnSecuritiesChaged, we create the rolling window and update it ?

Also, what is the equivalent of "Reset()" method in python ?

0

Basically, I am trying to retrofit the same algo that I wrote using the Basic Template, where we only have Initialize and OnData to worry about, into the Alpha Framework. To recap, the algo requires:

1. A 15m consolidator

2. A 240m consolidator

3. A MACD each to be registered with both consolidators

4. A rolling window to contain the 240m MACD bars

5. The 15m MACD, 240m MACD, rollingwindow (for previous values of 204m MACD), must be callable each time new data is updated / each tick

Here is my updated source codes, taking into account your suggestions above, including my comments.

Apologies. Am totally confused over consolidators and rolling windows implementation in the Alpha Framework.

0


Hi Rachel, to upgrade your old algorithms into the Alpha Streams capable strategy you can use the EmitInsights endpoint. Please see an example of this here: 

https://github.com/QuantConnect/Lean/blob/master/Algorithm.Python/ConvertToFrameworkAlgorithm.py

I think this will answer what you need without you needing to convert anything. Let me know if it doesn't quite fit.

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 Jared,

Thanks for the sample. I have a few questions as follows:

1. It this the only thing we have to do to the old codes : 

EmitInsights{} ?

2. By taking in QCAlgorithmFrameworkBridge in the constructor does this effectively make the old code a Framework Main class ? 

3. Does this mean the universe selection, trade execution, portfolio allocation, risk management, etc... will remain in the same class along with Alpha (thru EmitInsights) ?

4. If I were to submit my "Alpha" for licensing, does this require submitting the whole file ?

0

1) For transmitting Alpha Streams yes; you just need to emit Insight objects.

2) Not a Framework algorithm - just capable of being licensed in Alpha Streams.

3) None of those things are set/needed in the old algorithm style. This bridge/upgrade just allows you to submit the strategy for licensing.

4) You submit the backtest for Alpha Streams; so yes its the entire code snapshot.

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