Issue with multiple loops

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

답변 (2개)

Oleg Komarov
Oleg Komarov 2012년 3월 5일

0 개 추천

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 2012년 3월 5일

0 개 추천

Could you recommend a solution?

댓글 수: 2

Oleg Komarov
Oleg Komarov 2012년 3월 5일
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 2012년 3월 6일
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.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2012년 3월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by