Help! Convert Metastock code to Amibroker AFL

#1
Hey everybody,

I have metastock Ulcer Index code below, but I can't convert to Amibroker AFL.
Can you help me. I appreciate it. Thanks you very much.

study(title = "Ulcer Index 3 [LazyBear]", shorttitle="UlcerIndex3_LB")
length1=input(10, title="Index 1 length")
length2=input(14, title="Index 2 length")
cutoffHigh=input(10, title="Index 1 cutoff")
cutoffLow=input(5, title="Index 2 cutoff")
src=close

calc_ui(src, length) =>
hcl=highest(src,length)
r=100.0*((src-hcl)/hcl)
sqrt(sum(pow(r,2), length)/length)

current = calc_ui(src[0], length1)
previous = calc_ui(src[1], length2)

hline(cutoffHigh, color=gray, title="Index 1 cutoff")
hline(cutoffLow, color=gray, title="Index 2 cutoff")
plot(current, color=green, linewidth=2, title="UlcerIndex 1")
plot(previous, color=orange, linewidth=2, title="UlcerIndex 2")
bgcolor(current > cutoffHigh and previous > cutoffLow ? red : na)
bgcolor(current < cutoffLow and previous < cutoffHigh ? green : na)
 

umeshmandal

Well-Known Member
#2
Hey everybody,

I have metastock Ulcer Index code below, but I can't convert to Amibroker AFL.
Can you help me. I appreciate it. Thanks you very much.

study(title = "Ulcer Index 3 [LazyBear]", shorttitle="UlcerIndex3_LB")
length1=input(10, title="Index 1 length")
length2=input(14, title="Index 2 length")
cutoffHigh=input(10, title="Index 1 cutoff")
cutoffLow=input(5, title="Index 2 cutoff")
src=close

calc_ui(src, length) =>
hcl=highest(src,length)
r=100.0*((src-hcl)/hcl)
sqrt(sum(pow(r,2), length)/length)

current = calc_ui(src[0], length1)
previous = calc_ui(src[1], length2)

hline(cutoffHigh, color=gray, title="Index 1 cutoff")
hline(cutoffLow, color=gray, title="Index 2 cutoff")
plot(current, color=green, linewidth=2, title="UlcerIndex 1")
plot(previous, color=orange, linewidth=2, title="UlcerIndex 2")
bgcolor(current > cutoffHigh and previous > cutoffLow ? red : na)
bgcolor(current < cutoffLow and previous < cutoffHigh ? green : na)
Do post if you get any response elsewhere as I too need to get a Metastock formula Converted to Ami!
 

extremist

Well-Known Member
#3
Hey everybody,

I have metastock Ulcer Index code below, but I can't convert to Amibroker AFL.
Can you help me. I appreciate it. Thanks you very much.

study(title = "Ulcer Index 3 [LazyBear]", shorttitle="UlcerIndex3_LB")
length1=input(10, title="Index 1 length")
length2=input(14, title="Index 2 length")
cutoffHigh=input(10, title="Index 1 cutoff")
cutoffLow=input(5, title="Index 2 cutoff")
src=close

calc_ui(src, length) =>
hcl=highest(src,length)
r=100.0*((src-hcl)/hcl)
sqrt(sum(pow(r,2), length)/length)

current = calc_ui(src[0], length1)
previous = calc_ui(src[1], length2)

hline(cutoffHigh, color=gray, title="Index 1 cutoff")
hline(cutoffLow, color=gray, title="Index 2 cutoff")
plot(current, color=green, linewidth=2, title="UlcerIndex 1")
plot(previous, color=orange, linewidth=2, title="UlcerIndex 2")
bgcolor(current > cutoffHigh and previous > cutoffLow ? red : na)
bgcolor(current < cutoffLow and previous < cutoffHigh ? green : na)
First of all i guess this is not metastock formula.
as i know in metastock "=" is written like ":="

LazyBear reminds me of Trading View.
If you can share the source then may be i can try to help you.
 
Last edited:

extremist

Well-Known Member
#4
Code:
_SECTION_BEGIN(" Ulcer Index ");
//https://www.tradingview.com/script/QuqgdJgF-Indicator-Ulcer-Index/
// Credits : LazyBear - TradingView.
length = Param( "Length", 10, 1, 5000, 1 );
cutoff = Param( "Cut off", 5, 0, 100, 0.1 );

hcl=hhv(close,length);
r=100.0*((close-hcl)/hcl);
ui=sqrt(sum(r^2, length)/length);
col=IIf(ui>cutoff,colorRed,colorAqua);
Plot( ui, "Ulcer Index ("+length+","+cutoff+") ", col);
Plotgrid(cutoff,colorBlack,9, 1);

_SECTION_END();
This the Ulcer index for amibroker convert of LazyBears Original code of UI.
this not the one you wanted.
but now if you take little effort further then you will get the code you want.


Enjoy....
:)
regards
 
#5
Resp. Extremist bhai.. Thank you.
& Honsoosoo ji, I have found this on net.. ...may give some hint...
source: http://boards.fool.com/amibroker-code-superior-six-26224032.aspx
:)

If anyone uses Amibroker and would like the code for generating their own superior six candidates here it is. I assume you know how to use Amibroker and accordingly will make only a few comments. Note: I have not found it to ever replicate Zee's picks exactly and between my approach and his I'm pretty sure who is more accurate and it isn't me. :)

Quick notes (You may want to add them into the script)

1. You can change your base symbols for the UPI calculations. I have chosen SHV and SPY
2. You can use any of the variables below in addition to UPI as the "Position Score". However, I have found UPI to be consistently the best sort over many different backtests
3. MPT lookback length makes a big difference depending on what type of ETF category you use. I have my database broken up into sectors, countries, indexes and combinations of these. You can see some of my comments from summer testing as to what works best. As a general rule around 300 works well for about all categories.
4. You can create your own "superior whatever" by adjusting the Buy/Sell/ShortDays variables.
5. In my backtests I believe a "Superior 10" long works quite well followed immediately by a "Crappy 5" short. In most years it does not hurt returns much and in choppy or bad years it boosts them quite a bit. For example in 2007 doing the Superior 10/Crappy 5 beat the Superior 10 in just about every category thus far.

Cheers Kev




/*There are a few things with this routine that can trip you up depending on your data base.

1)One is the money market rate,

2)The assumed risk free interest rates where convention uses 5.4% (man I wish this were True),

3)The symbol of the S&P 500 Index via the SPY ETF, AND the window OR so called MPT period. The latter are in two
parameters to adjust. I've seen many versions of MPT calculations AND they all present somewhat different values for UI AND UPI.


You can strip the UI UPI code from this AND make your own exploration routine that doesn't depend on Buy/Sell OR the Equity curve.*/


// *************************** Function Section to calculate Risk Free Fixed Rate *********

function Irate(interest_rate)

{

// This gets the log of the daily rate

logbarfactor = log(1 + interest_rate / 100) / 252;

// Force the first bar to 0

logvect = IIf(BarIndex() == 0, 0, logbarfactor);

// Sum the log of the daily gain factors and

// convert back to get equity

return(exp(Cum(logvect)));

}

// -----------------------------------General Section--------------------------------

period = 22; // 22 trading days a month
MPT_Period = Param("MPT Period", 50, 0, 500, 10); //310 broad optimum, 50 for single country
//MPT_Period = Optimize("MPT Period", 130, 0, 500, 5);
IndexSym = ParamStr("S&P 500 Index ETF","SPY"); // NOTE: Figure out how to change this

// ------------------------------------MPT Section------------------------------------

Index = Foreign(IndexSym,"Close");
rfFund = Foreign("SHV","C"); //NOTE: Will need to get this loaded or use a different symbol (original:FDRXX)
riskfree = ((rffund/ Ref(rfFund,-MPT_Period)))^(252);

// Correlation coefficient of Equity to the Index
Corr = 100*Correlation(ROC(C,1),ROC(Index,1),MPT_Period);
SDF = StDev(ROC(Close, 1),MPT_Period);
SDI = StDev(ROC(Index, 1),MPT_Period);
RelStDev = SDF/SDI;

// Calculation of Beta -
Beta = Corr * RelStDev/100; // volatily relative to benchmark
NCAlpha = MA(ROC(Close,1),MPT_Period) - RelStDev*MA(ROC(Index,1),MPT_Period); // noncorrelated Alpha
Alpha = MA(ROC(Close,1),MPT_Period) - Beta*MA(ROC(Index,1),MPT_Period); // textbook definition

// SHARPE PERFORMANCE INDEX a risk adjusted measure of the performance of an Equity compared to the risk free benchmark standard rate of return = 5%
SHARPE = ( MA(ROC(C,1),MPT_Period) - MA(ROC(irate(5.1),1),MPT_Period) )/(SDF);

// ----------------------------------- UPI Code ---------------------------------------

// Retracements from the Highest High Current Draw Down Here using Monthly Period to call these numbers.
Cdd = (HHV(C,MPT_Period) - C)/HHV(C,MPT_Period);

// Max draw down
MaxDD = HHV(CDD,MPT_Period);

// Sum of all retracements squared -
R2 = (Sum(Cdd*Cdd,MPT_Period))/(MPT_Period-1);

// Ulcer Index -Cumulative downside volatility of an equity
UI = sqrt(R2);

// Annual compound percentage rate of return
TR = Close/Ref(Close,-MPT_Period); // Total Return for 1 year
ANN = (exp(log(TR))-1); // Annual compounded rate of return

// Ulcer performance index - risk adjusted performance of an investment.
UPI = (ANN - irate(5.1)/100)/UI; // I have 2.2% here, early analysts used 5.4%

// ----------------------------- Performance Calculation ----------------------------

EndV = ValueWhen(DateNum()==DateNum(), C); // Today's Close
BegV = ValueWhen(DateNum()==1070103, C); // Starts year with Jan 3, 2005 Closing Value (original:1050103)

//Returns the array with numbers that represent quotation dates coded as follows:
//10000 * (Year - 1900) + 100 * Month + Day, so 2001-12-31 becomes 1011231 AND 1995-12-31 becomes 951231
YTD = 100*(EndV-BegV)/BegV;

// --------------------------- Calculate RSI / Stochastics - Exploration --------------------------------------

slow=LLV(C,21);
shigh=HHV(C,21);
faststoc=EMA(100*(C-slow)/(shigh-slow),13)/2 + RSI(14)/2;
momentum=faststoc-Ref(faststoc,-6); // as used in Cheese3 and FT
momentumchg=((faststoc-Ref(faststoc,-6))/Ref(faststoc,-6))*100; //as used in Cheese3 and FT

// ---------------------------- Test Section -----------------------------------------------------
xbar = MA(ROC(C,1),MPT_Period);
SumR2 = Sum((ROC(C,1)-xbar)^2,MPT_Period);
Sigma = (SumR2/(MPT_Period-1))^.5;
Filter = 1;
AddTextColumn(FullName(),"Name",1.2);
AddColumn(Corr,"Cor Coeff");
AddColumn(Alpha,"Alpha");
AddColumn(NCAlpha,"NCAlpha");
AddColumn(Beta,"Beta");
AddColumn(SDF,"Std Dev");
AddColumn(RelStDev,"RelSD");
AddColumn(Sharpe,"Sharpe");
AddColumn(100*Ann,"ANN");
AddColumn(100*MaxDD,"MDD %");
AddColumn(100*UI,"UI");
AddColumn(UPI,"UPI");
AddColumn(faststoc,"Stoch/RSI",1.2);
AddColumn(momentum,"Mom",1.2);
AddColumn(momentumchg,"Mom-Chg%",1.2);
AddColumn(ROC(C,Period)," 1 mnth");
AddColumn(YTD," YTD");
AddColumn(ROC(C,MPT_Period)," 1 yr ");

PositionScore = UPI;

PosSize = Param("Position Size", 1, 1, 25, 1 );
//PosSize = Optimize("Postion Size", 2, 1, 10, 1 );
//MArginFactor = Param("Margin Factor", 1, 1, 100 );
//MarginFactor = Optimize("Margin Factor", 1, 1, 10, 1 );
SetOption("MaxOpenPositions", Possize );
PositionSize = -100/PosSize;

//All 6/3/6/360/37.7% hold 1, 29.5% hold 3
//EEM Settings 7/4/5/-/41.1%
//Country 6/3/4/450/25.7% Analysis of days only yields 6/2 long only as optimal and in sample set of 50 days (as of 7/4/2007)
//Intl Sector 6/3/4/350/33.5% Analysis of days only yields 6/2 long only as optimal and in sample set of 50 days (as of 7/4/2007)
//US Sector 6/4/4/310/29.3%
//Asset Classes 6/3/5/310/22.9%
//Intl Index 6/3/6/350/44.7%
//iShares 6/3/5/420/34.97%
//Ultra Long Shares 6/2/50/10.1% Analysis of days only yields 6/2 long only as optimal and in sample set of 50 days (as of 7/4/2007)



//BuyDays = Param("# of BuyDays", 6, 1, 10, 1 );
//SellDays = Param("# of SellDays", 2, -1, 15, 1 );
//ShortDays = Param("# of ShortDays", 3, 0, 10, 1 );
//Mo = Param("Month", 1, 1, 12, 1);*/

BuyDays = Optimize("# of BuyDays", 6, 1, 11, 1 );
SellDays = Optimize("# of SellDays", 3, 0, 11, 1 );
ShortDays = Optimize("# of ShortDays", 4, 3, 8, 1 );
//Mo = Optimize("Month", 1, 1, 12, 1);*/


m = Month()!=Ref(Month(),-1);
Buy = Ref( m, BuyDays );// AND Month() != 6 AND Month() !=7 AND Month() !=8;//
Sell = Ref( m, -SellDays ); //AND Month() == Mo+1;
Short = Ref(m, - SellDays);// AND Month() == 6;
Cover = Ref(m, - (SellDays+ShortDays)); //AND Month() == Mo+1;
 

Similar threads

Broker Special Offers

Intraday Higher Leverage

Save up to 90% in brokerage and get higher leverage for intraday trades.

Name:Phone:
Email:City:
State:
Are you a day trader?