A suggestion for a new Advanced Position Sizer, based on the CNN Fear & Greed indicator:
If 5 day average Fear & Greed is >= 75, increase the position size by N%
If 5 day average Fear & Greed is >= 50, increase the position size by N%
If 5 day average Fear & Greed is < 50, reduce the position size by N%
If 5 day average Fear & Greed is <= 25, reduce the position size by N%
If 5 day average Fear & Greed is >= 75, increase the position size by N%
If 5 day average Fear & Greed is >= 50, increase the position size by N%
If 5 day average Fear & Greed is < 50, reduce the position size by N%
If 5 day average Fear & Greed is <= 25, reduce the position size by N%
Rename
The way it's requested your idea is too specific. Why this sentiment indicator and not some other? It should be more generic IMO, otherwise it looks like a concierge type of job.
Here's a modified suggestion for a new generic Advanced Position Sizer:
If the <selectable indicator> N-day average is >= N, increase the position size by N%.
If the <selectable indicator> N-day average is <= N, reduce the position size by N%.
If the <selectable indicator> N-day average is >= N, increase the position size by N%.
If the <selectable indicator> N-day average is <= N, reduce the position size by N%.
Here's an attempt to calculate the transaction quantity (depending on the Fera & Greed Index) and to pack it into a Position Sizer API extension. However, I am not sure whether this procedure is correct (as the help is a bit thin)?
Any hints are appreciated!
Any hints are appreciated!
CODE:
using System; using WealthLab.Core; using WealthLab.Indicators; using WealthLab.PowerPack; namespace WealthLab.Backtest { public class CnnFearGreedPositionSize : BasicPositionSizer { private IndicatorBase cnnFearGreed; public override void GenerateParameters() { base.GenerateParameters(); } public override string Name => "Cnn Fear & Greed Position Sizer"; public override string Description => ""; public override void Initialize() { base.Initialize(); } private double CalculateQuantitySize(int idx, Transaction tran) { if (cnnFearGreed[idx] >= 75) return Math.Floor(tran.Quantity * 1.25); else if (cnnFearGreed[idx] >= 55) return Math.Floor(tran.Quantity * 1.1); else if (cnnFearGreed[idx] >= 45) return Math.Floor(tran.Quantity * 1); else if (cnnFearGreed[idx] >= 25) return Math.Floor(tran.Quantity * 0.75); else if (cnnFearGreed[idx] >= 0) return Math.Floor(tran.Quantity * 0.5); else return tran.Quantity; } public override double SizePosition(Transaction t, BarHistory bars, int idx, double basisPrice, double equity, double cash) { cnnFearGreed = new SmoothedInd(bars, new CNNFearGreed(bars), new EMA(new CNNFearGreed(bars), 5)); t.Quantity = CalculateQuantitySize(idx, t); return base.SizePosition(t, bars, idx, basisPrice, equity, cash); } } }
Looks good. I'd optimize it so as not to recreate the indicator each time a Position is being sized:
CODE:
public override double SizePosition(Transaction t, BarHistory bars, int idx, double basisPrice, double equity, double cash) { if(cnnFearGreed == null) cnnFearGreed = new SmoothedInd(bars, new CNNFearGreed(bars), new EMA(new CNNFearGreed(bars), 5)); ...
The following issues I have when setting the quantity:
Why is t.Quantity always 0? If I set t.Quantity fixed to 200, I still don't get the desired result and the quantity isn't calculated by the desired Advanced Position Sizer?
There should be a way to recalculate and override the quantity so that it is taken over from the extension?
Any help is appreciated.
![](/api/discussion/download/image/7728-2024-05-11-14-27-53-png)
Why is t.Quantity always 0? If I set t.Quantity fixed to 200, I still don't get the desired result and the quantity isn't calculated by the desired Advanced Position Sizer?
There should be a way to recalculate and override the quantity so that it is taken over from the extension?
Any help is appreciated.
CODE:
public override double SizePosition(Transaction t, BarHistory bars, int idx, double basisPrice, double equity, double cash) { if (cnnFearGreed == null) { cnnFearGreed = new SmoothedInd(bars, new CNNFearGreed(bars), new EMA(new CNNFearGreed(bars), 5)); } t.Quantity = 200; //CalculateQuantitySize(idx, t); return base.SizePosition(t, bars, idx, basisPrice, equity, cash); } // Trade Rules in Strategy public override void Execute(BarHistory bars, int idx) { Position foundPosition0 = FindOpenPosition(0); if (foundPosition0 == null) { if (ConsecDown.Series(bars.Close, 1)[idx] >= 2.00) { PlaceTrade(bars, TransactionType.Buy, OrderType.Market, 0, 0, ""); } } else { if (idx - foundPosition0.EntryBar + 1 >= 2) { ClosePosition(foundPosition0, OrderType.Market, 0,""); } } }
You should return 200 if you want the quantity to be 200.
That's what I try by setting t.Quantity = 200 but under Backtest - Positions I have different quantity values?
Even then your code does NOT return 200 but base.SizePosition(...)
Please RETURN 200 from the method instead of assigning 200 to the Quantity properly.
The return in base.SizePosition(t, bars, idx, basisPrice, equity, cash) accepts the 200, but they are not taken over into the backtest.
How can I use an integer in the return base.SizePosition(), when a transaction type is required?
Delete lines 68 and 69.
And in it’s place code:
And in it’s place code:
CODE:
return 200;
Thanks. That worked!
![](/api/discussion/download/image/7731-2024-05-11-16-01-52-png)
I firmly assumed that I had to trigger base.SizePosition() in any case :-(
Would definitely be much easier if the API help would have an example where you can actually see, how to calculate and submit a "real-world conditional" position size. The snippet (and the help there) is more than confusing, at least for me...
I firmly assumed that I had to trigger base.SizePosition() in any case :-(
Would definitely be much easier if the API help would have an example where you can actually see, how to calculate and submit a "real-world conditional" position size. The snippet (and the help there) is more than confusing, at least for me...
We don't have the capacity to provide a complete example for each method. The best we can do is answer clarifications as quickly as possible here on the forum.
It could be a language issue but I feel the method is adequately documented.
It could be a language issue but I feel the method is adequately documented.
You might be right, because although I went through this article several times, I wouldn't have got the idea of doing it this way.
In hindsight, I learnt that I can't simply increase/decrease the quantity (as a percentage), but always have to consider how much cash is available.
Nevertheless, the whole thing cost me a few hours of reverse engineering, which could have been avoided with simply 1-2 more realistic examples.
But I see the positive side as well, because the longer I work on the product, the more I grow into it, which makes me more independent and self-determined.
In hindsight, I learnt that I can't simply increase/decrease the quantity (as a percentage), but always have to consider how much cash is available.
Nevertheless, the whole thing cost me a few hours of reverse engineering, which could have been avoided with simply 1-2 more realistic examples.
But I see the positive side as well, because the longer I work on the product, the more I grow into it, which makes me more independent and self-determined.
I'm a bit late to the party, but please let me join in and add a few comments and suggestions.
First, I think the idea to use an (arbitrary) indicator to modulate position sizes is a very good and valuable (counted in $$) one.
Second, I think to make such an idea useful, there are some more practical considerations necessary.
Some Background
At the end of the day you want the same profit if a security makes an average favorable move no matter what the price level of the security looks like, no matter what the volatility of that security looks like. This means that a position size (in dollar) should be a fixed percentage of available equity. (This takes the price level out of the equation) and more position size should be inverse proportional to current volatility (smaller positions in volatile stocks, larger positions in quiet stocks).
For practical considerations (and to limit risk) there should be an upper limit for your positions (say 20%). Likewise there should be a lower bound for your position size. (it makes no sense to invest in one share of a $5 stock).
Now, with all these considerations and calculations in place you should use your favorite indicator to increase or decrease the position size (as calculated above) within the limits mentioned above.
---
This explanation may sound a bit overwhelming when it comes to implement such a thing but fortunately the heavy lifting is already done, there is a versatile method available for use in an advanced postion sizer. The position size for a certain volatility is based on the RiskStopLevel mechanism and looks like this:
The positon size for a certain percent amount of equity is calculated like so:
Same code with minPct for the minimum positon size. And requestedPct for the requested position size (in percent of equity).
After these four calls you have everything to apply your indicator.
First, I think the idea to use an (arbitrary) indicator to modulate position sizes is a very good and valuable (counted in $$) one.
Second, I think to make such an idea useful, there are some more practical considerations necessary.
Some Background
At the end of the day you want the same profit if a security makes an average favorable move no matter what the price level of the security looks like, no matter what the volatility of that security looks like. This means that a position size (in dollar) should be a fixed percentage of available equity. (This takes the price level out of the equation) and more position size should be inverse proportional to current volatility (smaller positions in volatile stocks, larger positions in quiet stocks).
For practical considerations (and to limit risk) there should be an upper limit for your positions (say 20%). Likewise there should be a lower bound for your position size. (it makes no sense to invest in one share of a $5 stock).
Now, with all these considerations and calculations in place you should use your favorite indicator to increase or decrease the position size (as calculated above) within the limits mentioned above.
---
This explanation may sound a bit overwhelming when it comes to implement such a thing but fortunately the heavy lifting is already done, there is a versatile method available for use in an advanced postion sizer. The position size for a certain volatility is based on the RiskStopLevel mechanism and looks like this:
CODE:
double riskSize = CalculatePositionSize(PositionSizeType.MaxRiskPct, riskPct, bars, basisPrice, equity, idx);
The positon size for a certain percent amount of equity is calculated like so:
CODE:
// maximum posSize double maxPosSize = CalculatePositionSize(PositionSizeType.PctOfEquity, maxPct, bars, basisPrice, equity, idx);
Same code with minPct for the minimum positon size. And requestedPct for the requested position size (in percent of equity).
After these four calls you have everything to apply your indicator.
It is not too hard to put that code in your personal advance position sizer.
A new general useable indicator modulated advanced position sizer would follow this #FeatureRequest:
Parameters of Advanced Position Sizer:
* position size in percent of equity - this is the nominal position size
* position size based on volatility - position size calculated with the RiskStopLevel mechanism
* Maximal position size in percent of equity
* Minimal Postion Size in percent of equity
* Indicator Expression - this indicator is used to modulate the position size
* upper indicator value - indicator values greater or equal this value lead the the full calculated position size.
* lower indicator value - indicator values less or equal this value lead the the minimum position size.
Calculation Rules
1. calculate pos. size based on volatility/risk
2. calculate pos. size based on pct of equity
3. take lower of 1) and 2)
4. calculate indicator
5. scale and limit indicator values with "upper indi value" and "lower Indi value" to the range [0,1].
6. multiply factor from 5) with 3)
7. Apply lower limit and upper limit.
Example
Rules 1), 2), 3) and 7) constitute the well known "Max Risk Limited to Percent of Equity" position sizer.
Let's say the rules give us a position size of 100 shares.
If we now choose an indicator like RSI(14), that oscillates between 0 an 100, and we say an RSI of 80 should lead to "fill position size" and an RSI of 20 should lead to "minimum position size" then various indicator values of RSI result in these position sizes (we assume a lower limit of 5 shares):
RSI Pos.Size
100 100
80 100
50 50
20 5 (lower limit)
0 5 (lower limit)
A new general useable indicator modulated advanced position sizer would follow this #FeatureRequest:
Parameters of Advanced Position Sizer:
* position size in percent of equity - this is the nominal position size
* position size based on volatility - position size calculated with the RiskStopLevel mechanism
* Maximal position size in percent of equity
* Minimal Postion Size in percent of equity
* Indicator Expression - this indicator is used to modulate the position size
* upper indicator value - indicator values greater or equal this value lead the the full calculated position size.
* lower indicator value - indicator values less or equal this value lead the the minimum position size.
Calculation Rules
1. calculate pos. size based on volatility/risk
2. calculate pos. size based on pct of equity
3. take lower of 1) and 2)
4. calculate indicator
5. scale and limit indicator values with "upper indi value" and "lower Indi value" to the range [0,1].
6. multiply factor from 5) with 3)
7. Apply lower limit and upper limit.
Example
Rules 1), 2), 3) and 7) constitute the well known "Max Risk Limited to Percent of Equity" position sizer.
Let's say the rules give us a position size of 100 shares.
If we now choose an indicator like RSI(14), that oscillates between 0 an 100, and we say an RSI of 80 should lead to "fill position size" and an RSI of 20 should lead to "minimum position size" then various indicator values of RSI result in these position sizes (we assume a lower limit of 5 shares):
RSI Pos.Size
100 100
80 100
50 50
20 5 (lower limit)
0 5 (lower limit)
The other interesting question in this discussion: Is the CNN Fear and Greed Indicator useful for modulation of position size?
Or to put it more directly: Is there any relation between indicator values and trade outcome?
To answer this question I used the finantic.IndicatorSelection extension.
I produced a large number of trades with a modified version of "Knife Juggler" and analysed the relationship between these trades (profit of each trade) and the CNN Fear and Greed Indicator: The results are best seen in the "Cumulated Average Target" Graph of the Indicator Selection extension:
![](/api/discussion/download/image/7733-CnnFearAndGreedVsKnifeJuggle-PNG)
On the X-Axis we have the CNN Fear and Greed indicator values from 0 to 100 (shown on a scaled axis 0.0 to 1.0)
On the Y-Axis are cumulated and averaged trade profits. This means: For an indicator value of 10 we take all trades where the indicator is 10 or less (left side of graph), calculate the average trade outcome of all these trades and show the result as a single point with X-Value 10.
If repeated for all indicator values this results in a line.
(The same calculation is done for Indicator value X or more, resuting in results at the right side of the graph.)
The graph shows such lines for various date ranges:
![](/api/discussion/download/image/7734-Intervals-PNG)
The use of several date ranges shows clearly if the results are robust i.e. repeat throughout history or if the resuts are just statistical fluctuations.
Results of Analysis
From the Chart it is possible to learn these facts:
* Effects are much larger for Fear (CNN Fear and Greed Indicator in the range 0.0 - 20.0, "Extreme Fear") than for Greed (Range 80.0 - 100.0 "Extreme Greed")
* There are no useful effects for other indicator values (Range 20.0 to 80.0)
* There are consistent positive effects for Knife Juggler trades if the CNN indicator shows extreme fear, but not in the Test2 interval (years 2019/2020), where the effects are reversed(!)
Summary: The result say that it might be useful to use the CNN Fear and Greed indicator to modulate position sizes. If CNN is 20 or below, the position sizes should be much bigger than for other indicator readings.
The resuts do not hold for the years 2019 and 2020. So if using this you should pray that there will be no other Corona virus.
Or to put it more directly: Is there any relation between indicator values and trade outcome?
To answer this question I used the finantic.IndicatorSelection extension.
I produced a large number of trades with a modified version of "Knife Juggler" and analysed the relationship between these trades (profit of each trade) and the CNN Fear and Greed Indicator: The results are best seen in the "Cumulated Average Target" Graph of the Indicator Selection extension:
On the X-Axis we have the CNN Fear and Greed indicator values from 0 to 100 (shown on a scaled axis 0.0 to 1.0)
On the Y-Axis are cumulated and averaged trade profits. This means: For an indicator value of 10 we take all trades where the indicator is 10 or less (left side of graph), calculate the average trade outcome of all these trades and show the result as a single point with X-Value 10.
If repeated for all indicator values this results in a line.
(The same calculation is done for Indicator value X or more, resuting in results at the right side of the graph.)
The graph shows such lines for various date ranges:
The use of several date ranges shows clearly if the results are robust i.e. repeat throughout history or if the resuts are just statistical fluctuations.
Results of Analysis
From the Chart it is possible to learn these facts:
* Effects are much larger for Fear (CNN Fear and Greed Indicator in the range 0.0 - 20.0, "Extreme Fear") than for Greed (Range 80.0 - 100.0 "Extreme Greed")
* There are no useful effects for other indicator values (Range 20.0 to 80.0)
* There are consistent positive effects for Knife Juggler trades if the CNN indicator shows extreme fear, but not in the Test2 interval (years 2019/2020), where the effects are reversed(!)
Summary: The result say that it might be useful to use the CNN Fear and Greed indicator to modulate position sizes. If CNN is 20 or below, the position sizes should be much bigger than for other indicator readings.
The resuts do not hold for the years 2019 and 2020. So if using this you should pray that there will be no other Corona virus.
QUOTE:
The positon size for a certain percent amount of equity is calculated like so:
CODE:
// maximum posSize
double maxPosSize = CalculatePositionSize(PositionSizeType.PctOfEquity,
maxPct, bars, basisPrice, equity, idx);
Same code with minPct for the minimum positon size. And requestedPct for the requested position size (in percent of equity).
Thanks for the hint. This helper function is indeed useful in calculating the propper position size.
QUOTE:
Summary: The result say that it might be useful to use the CNN Fear and Greed indicator to modulate position sizes. If CNN is 20 or below, the position sizes should be much bigger than for other indicator readings.
Well, I can imagine that a dip buyer system on stocks doesn't has the desired effect. Originally and for a few reasons, my idea was to use the slightly smoothed CNN F&G exclusively on leveraged ETFs.
Now that I have painstakingly familiarised myself with the Position Sizer API, I will go a large step further by taking the options market risks and the mean square tracking error (logarithmic trend) into account to build kind of an Margin-Risk Position Sizer.
Your Response
Post
Edit Post
Login is required