Loop large section of code

I have a large section of code which comes down to one single value  which is different each time you execute the section due to a

random component.  I want find a simple way I can loop the complete section of code and get the output 1, output 2, output 3 etc etc

without having to go in and put [ i , j ] on every single variable. I can do it manually by just start in the begining and press

enter all the way , write down the result and move the cursor to the begining again and start all over again but it is very time consuming.

Since the code section is very large putting   [ i, j ] notation is not an option.  Any help most appreciated !

 

acer's picture

procedure

How about putting the whole thing in a procedure called f (which might even take no arguments at all. Have it return that final result. Then call f() repeatedly, or call seq(f(),i=1..10).

acer

loop and print

Why not just enclose the section in a do loop, terminated with a colon (so the lines do not automatically generate printed output)  and add a print statement to the line that generates the output?  For example:

to 10 do
  < your code here >
  print(%); # print the last value
end do:

<p>ok, I give you guys the

<p>I was trying to give you guys the code so you can see but I have a hard time pasting it only get html notation hummm</p>

  ok I give you guys the

 

ok I give you guys the code so you can see for yourself

 

##########################################

restart;

with(Statistics):

 

# parameters

s[1]:=100: # Starting price stock

d:=4: # Trailing distance

n:=100: # Number of periods

 

# Stock price

randomize():

rand_:=Sample(RandomVariable(Normal(0,1)),n):

for i from 2 to n do s[i]:=s[i-1]+rand_[i] end do:

A:=[seq(s[i],i=1..n)]:

 

# Trailing Stop-Loss

B[1]:=(A[1]-d): for i from 2 to n do B[i]:=`if`(A[i]>A[i-1] and A[i]>(A[i]-d) and (A[i]-d)>B[i-1],(A[i]-d),B[i-1]) od:

C:=[seq(B[i],i=1..n)]:

r[1]:=0: for i from 2 to n do r[i]:=`if`(A[i]>C[i],0,1) od:

w:=[seq(r[i],i=1..n)]:

wp[1]:=0: for i from 2 to n do wp[i]:=(w[i]+wp[i-1]) od:

w_w_:=[seq(wp[i],i=1..n)]:

ww[1]:=0: for i from 2 to n do ww[i]:=(w_w_[i]+w_w_[i-1]) od:

w_w:=[seq(ww[i],i=1..n)]:

 

# Final Corrections

C_[1]:=(A[1]-d): for i from 2 to n do C_[i]:=`if`(w_w[i]=0,C[i],C_[i-1]) od:

C_C:=[seq(C_[i],i=1..n)]:

 

############## Results #########

 

# Exit period due to stop loss

u[1]:=0: for i from 2 to n do u[i]:=`if`(w_w[i]=1,i,0) od:

Exit_period:=convert([seq(u[i],i=1..n)],'`+`' );

 

# Exit price stop-loss

Exit_price:=`if`(Exit_period=0,0,C_C[n]);

 

# Last close stock price

Last_close:=`if`(A[n]<0,0,A[n]);

 

# Profit/loss with stop loss

prof_s:=`if`(Exit_price=0,Last_close-A[1],Exit_price-A[1]);

 

# Profit/loss without stop loss

prof_:=Last_close-A[1];

 

##############################

 

#########################################################

 

on each execut loop I want to have the value of prof_s and prof_

any ideas??

 

acer's picture

sample

fff := proc(dist, s_one, d, n)
option hfloat;
#
# parameters:
#   sample procedure
#   Starting price stock
#   Trailing distance#
#   Number of periods
#
# returns:
#   Profit/loss with stop loss,
#   Profit/loss without stop loss
#
local rand_, i, A, C, w, w_w_, w_w, C_C,
      Exit_period, Exit_price, Last_close;

    rand_:=dist(n):

    # Stock price
    A[1]:=s_one: # Starting price stock
    for i from 2 to n do
        A[i]:=A[i-1]+rand_[i];
    end do:

    # Trailing Stop-Loss
    C[1]:=(A[1]-d):
    for i from 2 to n do
        if A[i]>A[i-1] and A[i]>(A[i]-d)
          and (A[i]-d)>C[i-1] then
            C[i]:=(A[i]-d);
        else
            C[i]:=C[i-1];
        end if;
    end do:

    w[1]:=0:
    for i from 2 to n do
        if A[i]>C[i] then
            w[i]:=0;
        else
            w[i]:=1;
        end if;
    end do;

    w_w_[1]:=0:
    for i from 2 to n do
        w_w_[i]:=(w[i]+w_w_[i-1]);
    end do;

    w_w[1]:=0:
    for i from 2 to n do
        w_w[i]:=(w_w_[i]+w_w_[i-1]);
    end do;

    # Final Corrections
    C_C[1]:=(A[1]-d):
    for i from 2 to n do
        if w_w[i]=0 then
            C_C[i]:=C[i];
        else
            C_C[i]:=C_C[i-1];
        end if;
    end do:

    ############## Results #########
    # Exit period due to stop loss
    Exit_period:=add(`if`(w_w[i]=1,i,0),i=1..n);

    # Exit price stop-loss
    Exit_price:=`if`(Exit_period=0,0,C_C[n]);

    # Last close stock price
    Last_close:=`if`(A[n]<0,0,A[n]);

    # Profit/loss with stop loss,
    # Profit/loss without stop loss
    `if`(Exit_price=0,Last_close-A[1],Exit_price-A[1]),
    Last_close-A[1];

end proc:


randomize():
X := Statistics:-Sample(Statistics:-RandomVariable(Normal(0,1))):

fff( X, 100, 4, 100 );

seq( fff( X, 100, 4, 100 ), i=1..10 );

time( seq( fff( X, 100, 4, 100 ), i=1..1000 ) );

If you need this to be really fast, then the local tables (A, C_C, etc) could be created as float[8] Vectors outside of fff and then get passed in and re-used.

acer

thanx acer !  I am very

thanx acer !  I am very grateful! 

I now just have to spend some time to try to understand what you have done.  It looks great but I have to understand it.

thanx again

ok, a couple of

ok, a couple of questions
 
seq( fff( X, 100, 4, 100 ), i=1..10 );
 
is that the prof_  (profit without stop) or prof_s (profit with stop)  ? and where is the other one?
 
and
 
time( seq( fff( X, 100, 4, 100 ), i=1..1000 ) );

what is the purpose of that?

the notion :- means what??

also why do you assigne the dist parameter to rand_ ?? random variable??  . It is not meant to be a random varable

acer's picture

answers

A single call to fff returns a (Maple sequence) of two values. The first is the original code's prof_s and the second is prof_. They'll come back like this,

> fff( X, 100, 4, 100 );
                     -2.24688183307647, -23.3347550549661

If you do it 10 times, like seq(fff(...),i=1..10) then it will return 10 pairs: prof_s, prof_, prof_s, prof_, etc.

I gave the time() example, in case you were interested in seeing how fast it could compute 1000 runs.

The notation foo:-bar means the member bar from the module (package) foo.

I created X outside of fff, and passed it in (as the parameter `dist`). X is a procedure that takes a posint (n, say) and returns a Vector of sampled values from the distribution. Apart from being more efficient to have the creation of X outside of the procedure fff, I thought that it might be nice for you to be able to easily change the distribution details (if you wanted).

acer

ok, thanx for your patience

ok, thanx for your patience with me.

I can tell you one thing and that is that I would not have been able to set it up without your help.

I am not really at your level of programing skills yet .   but who knows maybe one day, ha ha....  thanx   :-)

just for the record if

just for the record

if anyone wants to plot the original post ( one stock and one stop loss ) you can use

 

with(plots):

t:=[seq(i,i=1..n)]:

X:=plot(t,A, style=line, color=black):

Y:=plot(t,C_C, style=line, color=red,thickness=2):

q1:=`if`(Exit_price=0,Last_close,Exit_price): q2:=`if`(Exit_period=0,n,Exit_period):

Z:=PointPlot([q1], xcoords=[q2], thickness =20,`if`(Exit_price=0,color=white,color=black), symbol=solidbox, symbolsize = 15,labels=[Time,Stock_price]):

display({X,Y,Z});     

Axel Vogt's picture

and what is it good for?

And what is it good for? I mean: what does it calculate? A kind of discretization for a stock model or a contract on stocks?

I mean we now that markets

I mean we now that markets are volatile which means that we need to protect our profits.

So the interesting question that aries is can we achive higher profits from using a trailing stop loss

than for example taking a naked position ( no stop loss)  in that stock.

I think that we can claim that this is the case after have run acers simulation that we can actually achive higher profits by using a trailing stop loss.

Note that we can investigating this hypotheis for a pure unit root, unit root with drift or some trend stationary process with some iceberg risk component.

I am not sure though how useful it will be for a pure unit root  though since the expected value is zero.

just for the record Joe help

just for the record Joe help me with another one which is quite straight forward and working.

where everything after "to 10 do" should be without execute symbol >  (Achived by pressing shift-enter)

 

restart;
with(Statistics):

# parameters
s[1]:=100:
d:=4:
n:=100:

# stock price
randomize():
to 10 do
rand_:=Sample(RandomVariable(Normal(0,1)),n):
for i from 2 to n do s[i]:=s[i-1]+rand_[i] end do:
A:=[seq(s[i],i=1..n)]:

# Trailing stop-loss
B[1]:=(A[1]-d):  
for i from 2 to n do
B[i]:=`if`(A[i]>A[i-1] and A[i]>(A[i]-d) and (A[i]-d)>B[i-1],(A[i]-d),B[i-1])
od:
C:=[seq(B[i],i=1..n)]:
r[1]:=0: for i from 2 to n do r[i]:=`if`(A[i]>C[i],0,1) od:
w:=[seq(r[i],i=1..n)]:
wp[1]:=0: for i from 2 to n do wp[i]:=(w[i]+wp[i-1]) od:
w_w_:=[seq(wp[i],i=1..n)]:
ww[1]:=0: for i from 2 to n do ww[i]:=(w_w_[i]+w_w_[i-1]) od:
w_w:=[seq(ww[i],i=1..n)]:

# Final Corrections
C_[1]:=(A[1]-d): for i from 2 to n do C_[i]:=`if`(w_w[i]=0,C[i],C_[i-1]) od:
C_C:=[seq(C_[i],i=1..n)]:

########### Results #########

# Exit period due to stop loss
u[1]:=0: for i from 2 to n do u[i]:=`if`(w_w[i]=1,i,0) od:
Exit_period:=convert([seq(u[i],i=1..n)],'`+`' );

# Exit price stop loss
Exit_price:=`if`(Exit_period=0,0,C_C[n]);

# Last close stock price
Last_close:=`if`(A[n]<0,0,A[n]);

# profit loss with stop loss
prof_s:=`if`(Exit_price=0,Last_close-A[1],Exit_price-A[1]);

# profit loss without stop loss
prof_:=Last_close-A[1];
#############################
print(prof_);   # or print(prof_s) for that matter
end do:

 

Again, just for the

Again, just for the record

Based upon further disussion with Joe Riel  we can put the output from the do-loop in a list by using the below code

Again everything after "for cnt to to nq do" should be without execute symbol >  (Achived by pressing shift-enter)

 

restart;
with(Statistics):

# parameters
s[1]:=100:     # Starting price stock
d:=4:              # Trailing distance
n:=100:         # Number of periods
nq:=100:       # Number of simulations

# stock price
randomize():
T := table():      # Assign table used to temporarily store results for do-loop

for cnt to nq do   # The starting point for the do-loop
rand_:=Sample(RandomVariable(Normal(0,1)),n):
for i from 2 to n do s[i]:=s[i-1]+rand_[i] end do:
A:=[seq(s[i],i=1..n)]:

# Trailing stop-loss
B[1]:=(A[1]-d):  
for i from 2 to n do
B[i]:=`if`(A[i]>A[i-1] and A[i]>(A[i]-d) and (A[i]-d)>B[i-1],(A[i]-d),B[i-1])
od:
C:=[seq(B[i],i=1..n)]:
r[1]:=0: for i from 2 to n do r[i]:=`if`(A[i]>C[i],0,1) od:
w:=[seq(r[i],i=1..n)]:
wp[1]:=0: for i from 2 to n do wp[i]:=(w[i]+wp[i-1]) od:
w_w_:=[seq(wp[i],i=1..n)]:
ww[1]:=0: for i from 2 to n do ww[i]:=(w_w_[i]+w_w_[i-1]) od:
w_w:=[seq(ww[i],i=1..n)]:

# Final Corrections
C_[1]:=(A[1]-d): for i from 2 to n do C_[i]:=`if`(w_w[i]=0,C[i],C_[i-1]) od:
C_C:=[seq(C_[i],i=1..n)]:

########### Results #########

# Exit period due to stop loss
u[1]:=0: for i from 2 to n do u[i]:=`if`(w_w[i]=1,i,0) od:
Exit_period:=convert([seq(u[i],i=1..n)],'`+`' );

# Exit price stop loss
Exit_price:=`if`(Exit_period=0,0,C_C[n]);

# Last close stock price
Last_close:=`if`(A[n]<0,0,A[n]);

# profit loss with stop loss
prof_s:=`if`(Exit_price=0,Last_close-A[1],Exit_price-A[1]);

# profit loss without stop loss
prof_:=Last_close-A[1];
#############################
T[cnt]:=prof_s;
end do:

h:= convert(T,'list'):

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
}