Saving multiple output in one variable from loop
显示 更早的评论
Dear all,
could somebody please help me with my following problem(s). I'm currently coding a moving average crossover trading rule. This rule needs to generate a buy signal (value "1") when the fast moving average is above the slow moving average and sell signals (value "-1") vice versa. Where a slow moving average (variable "n" days) is calculated over a greater number of days than the fast moving average (variable "m" days).
Question: How can I store all those different fast-slow combinations of "n" and "m" in one variable (in this case the "tr_ma_cross" variable)? So I would like that each fast-slow combination is written in a new column in the same variable.
The code at this moment:
%Moving average crossovers
for n=[2 5 10 15 20 25 30 40 50 75 100 125 150 200 250];
for m=[2 5 10 15 20 25 30 40 50 75 100 125 150 200 250];
if n==m; continue, end
MA_slow=tsmovavg(price,'s',n,1);
MA_fast=tsmovavg(price,'s',m,1);
for k=1:31225;
if MA_fast(k,1)>MA_slow(k,1)
tr_ma_cross(k,:)=1; %Buy
elseif MA_fast(k,1)<MA_slow(k,1)
tr_ma_cross(k,:)=-1; %Sell
else
tr_ma_cross(k,:)=0; %Neutral
end
end
end
end
Additional question: I also would like the code to only put a buy ("1") or sell ("-1") signal at the positive or negative move through the "intersection" of the fast and slow moving average (so when the fast moving average is the first time above the slow moving average put a "1" and then just zeros till the opposite happens, the slow moving average is above the fast moving average than I want it to put a "-1").
Thanks and have a nice day,
Wildman
3 个评论
dpb
2015-6-21
You doing this in real time or simply analyzing historical data?
Wildman
2015-6-29
dpb
2015-6-30
OK, in that case you have all the data already so can vectorize at least pieces; maybe all. If you were doing this in real time where didn't get the last observation until did the computation, have to wait...
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Mathematics 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!