Issue with multiple loops

1 vue (au cours des 30 derniers jours)
egert
egert le 5 Mar 2012
Hi,
Having an issue with the code below. Basically I want the loop to loop through each of the "en" (or entry) values. When outputting, the entry values are correct, but it is not used in calculations - what am I missing here?
en=2:0.5:6; % entry threshold (standard deviations)
ex=1; % exit threshold (standard deviations)
for entry=en
for i=1:(4630-lookback-1) % In sample
%for i=4631:(size(CO1)-lookback-1) % Out of sample
if zCO1(i)<-entry
while zCO1(i)<ex
pos(i)=1;
i=i+1;
end
elseif zCO1(i)>entry
while zCO1(i)>-ex
pos(i)=-1;
i=i+1;
end
end
end
for i=1:(4630-lookback-1) % In sample
%for i=4631:(size(CO1)-lookback-1) % Out of sample
if pos(i) == 1
ret(i)=retCO1(i+1);
elseif pos(i) == -1
ret(i)=-retCO1(i+1);
else
ret(i)=0;
end
end
fprintf('\nEntry'); disp(entry);
fprintf('Cumulative return');disp(sum(ret));
fprintf('Sharperatio');disp((sqrt(252)*mean(ret))/std(ret));
fprintf('Calmar');disp(sum(ret)/(std(ret)*252));
fprintf('**********************');
end
and the output is like:
Entry 2
Cumulative return 0.4896
Sharperatio 0.1242
Calmar 0.1428
**********************
Entry 2.5000
Cumulative return 0.4896
Sharperatio 0.1242
Calmar 0.1428
**********************
Entry 3
Cumulative return 0.4896
Sharperatio 0.1242
Calmar 0.1428
**********************
Tnx, Egert

Réponses (2)

Oleg Komarov
Oleg Komarov le 5 Mar 2012
You're changing the i (used by the for loop) within the while loop. You can do it but it is usually not recommended.
I don't have data to test the implications but most likely that's the cause.

egert
egert le 5 Mar 2012
Could you recommend a solution?
  2 commentaires
Oleg Komarov
Oleg Komarov le 5 Mar 2012
If you describe what your problem is and what is your data with a minimum working example it would be much easier. I also suspect that no loops are needed at all. It's a logical indexing problem.
egert
egert le 6 Mar 2012
Basically I have two loops in there, one calculates the "position" which is based on an array of zCO1, and another one which calculates the "returns" if position exists, which itself is based on retCO1.
Now when I change parameters manually (losing the for entry=en part), everything works like magic. But when adding this, it doesn't work. Basically I'm trying to do the thing mentioned in first paragraph multiple times, each time with different parameter (looping through 2, 2.5, 3 etc...). Somewhat of an optimization problem.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by