clear; format short; % Parameters p = 1; % How often do we trade? (Range [0,1]; 1: always; 0: never) onehand=400; morecash=0; % Fetch the data from data file A=load "0005HK.csv"; % 2003-2007 price=A(:,7); time=A(:,1); sellprice=price(1); buyprice=price(1); cash=zeros(size(price)); stock=zeros(size(price)); cash(1)=200000; % initial cash available for t=1:length(time) if(rem(t,27)==0) % allocate more cash each month to buy the stock cash(t) = cash(t) + morecash; % set morecash=0 above to disable endif %Do nothing by default dc(t) = 0; ds(t) = 0; if(rand

50) % Buy? % if(1) if(maverage(price,t,2)(t)>maverage(price,t,19)(t)) % Buy (put advanced criteria (e.g. moving average) here) buyhand=floor(cash(t)/price(t)/onehand); dc(t) = -price(t)*buyhand*onehand; ds(t) = +buyhand*onehand; if(buyhand>0) buyprice=price(t); endif endif % Sell? % if(0) if(maverage(price,t,2)(t)0) sellprice=price(t); endif endif endif cash(t+1) = cash(t) + dc(t); stock(t+1) = stock(t) + ds(t); end % Analysis price(t+1) = price(t); time(t+1) = time(t) + 1; total = cash + stock.*price; % Display the final results [total(t+1)./total(1) price(t+1)./price(1)] % Output the results to data file output=[time cash./total(1) stock.*price./total(1) total./total(1) price./price(1)]; save -ascii "buysell.dat" output;