Issue with multiple loops
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Oleg Komarov
2012-3-5
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 个评论
egert
2012-3-5
2 个评论
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!