Issue with multiple loops
1 view (last 30 days)
Show older comments
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
0 Comments
Answers (2)
Oleg Komarov
on 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.
0 Comments
egert
on 5 Mar 2012
2 Comments
Oleg Komarov
on 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.
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!