tags:

views:

94

answers:

3

I am trying to write a program which will find the total # of pips (price gained) with a strategy.

Basically, the strategy is whenever the stock price is 5, and we will start trading and we will continue trading as long as the stock price is higher than 2 and lower than 9, meaning in the range (2,9). When the price hits 2 or 9, we stop trading.

When I run the program it doesn't execute correctly, it does not enter the second while loop . What is missing?

% total : the total # of pips gained with a strategy % diff: the difference of the stock price btw 2 consecutive dates % Sheet1: a data matrix loaded from excel, where the first column is date and second one is stock stock price

total = 0;
diff = 0;
i =1;
j = 1;

while i <= length(Sheet1)
      i
        if Sheet1(i,2)==5
                 while  Sheet1(j,2) > 2 
                          j
                         diff = Sheet1(j+1,2) - Sheet1(j,2);
                         total = total + diff;
                         j = j + 1 ;

                         total
                         diff

                  end
        end
     i = i+ 1 ; 
end 
+2  A: 

first the code will only go on the first row as i=1 always and never increased it will go infinite loop
if i increased you should go until "length(Sheet1)-1" because out of index

could you be more specific as i don't understand what you mean to help you in the algorithm

mohamed sakr
I have added the increments for the variables i and j. Seems that the program does not enter the second while loop.
mtlb
+1  A: 

Here's my attempt at this problem (the way I understood it!):

p = rand(100,1) * 10;              %# generate some prices with values in [0,10]

s = 0;                             %# index when we started trading
flag = false;                      %# flag to indicate trading
total = 0;                         %# total gain
for i=1:length(p)-1
    if p(i)>5 && ~flag             %# if price>5 and we're not currently trading
        %# start trading
        flag = true;
        s = i;
    elseif flag && (p(i)<=2||p(i)>=9)        %# if trading and price not in [2,9]
        %# stop trading
        flag = false;
        total = total + sum( diff(p(s:i)) ); %# interval from p(s) to p(i)
    end
end
if flag                                      %# in case still trading past end
    %# stop trading
    flag = false;
    total = total + sum( diff(p(s:end)) );   %# interval from p(s) to p(end)
end

%# display total price gains
disp(total)

Basically, we loop over the vector of prices. When price>5 we start trading until the price is not in the range [2,9], at which point we calculate the sum of differences from when we started to this location (is that what you are trying to do??) and add it to a grand total.

Unfortunately it uses a for-loop, maybe someone can improve it by vectorization...

Amro
A: 

i think you should use only i or j not both

mohamed sakr

related questions