# Calculating Monthly Weighted Return using Daily data

I have this code:

``````function CalculateWeightedReturn(sym)
{
WeightedReturn = Null;
Data = Null;

TimeFrameSet(inMonthly);

Data = Foreign(sym,"C");

WeightedReturn = 100 * ((1 * Nz(Data / Ref(Data,  -1) - 1) +
1 * Nz(Data / Ref(Data,  -3) - 1) +
2 * Nz(Data / Ref(Data,  -6) - 1) +
0 * Nz(Data / Ref(Data, -12) - 1)) / 4)
;

TimeFrameRestore();
WeightedReturn = TimeFrameExpand(WeightedReturn, inMonthly, expandLast);

return WeightedReturn;
}

Symbols="IWM,IWP,IWS";

if (Status("stocknum") == 0)
{
StaticVarRemove("sv*");

// Calculate the Weighted Return values
for (i=0; (sym = StrExtract(Symbols,i)) != ""; i++) {
C0 = Foreign(sym,"C");  // for debugging
WeightedReturn = CalculateWeightedReturn(sym);  // pass in the symbol, do NOT pass in Close due to the timeframe switch

// Store Local variable
VarSet("WeightedReturn"+sym,WeightedReturn);

// Store Static Variable
StaticVarSet("svWeightedReturn"+sym,WeightedReturn);

printf("sym=%s\tWeightedReturn=%f\n",sym,WeightedReturn[BarCount-1]);
}
}

``````

Walking this through the debugger, if my active chart is monthly periodicity I get the correct results. When I switch to daily periodicity the results are incorrect.

Here is a screenshot from the debugger:

The problem is on the line Data = Foreign(sym,"C") in the function.

I've read the doc on the TimeFrame* functions as well as the tutorial but can't see what I'm doing wrong.

@LinusVanPelt I haven't had a good look into your code yet but I suspect the solution can be found in the Knowledge Base article that discusses a few methods of mixing foreign data with MultiTimeFrame functionality.

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.