function varargout = RSI (price,m,thresh,scaling,cost)% rsi%%% Copyright, the MathWorks, inc.% all rights reserved.if ~exist (' scaling ', ' var ') scaling = 1;endif ~exist (' m ', ' var ') M = 0; % No Detrendingelse if Numel (m) > 1 N = M (2); m = m (1); else N = M; M = 15*m; Endendif ~exist (' thresh ', ' var ') Thresh = [30 70]; % default Thresholdelse if Numel (thresh) = = 1 Scalar Value Thresh = [100-thresh, Thresh]; else if Thresh (1) > Thresh (2) thresh= thresh (2:-1:1); End Endendif ~exist (' cost ', ' var ') cost = 0; % default costend%% detrend with a moving averageif M = = 0 Ma = zeros (Size (price)); Else Ma = movavg (price,m,m, ' e '); e Ndri = Rsindex (Price-ma, N), percent Position signals = zeros (size (price)),% Crossing the lower thresholdindx = ri < thr Esh (1); indx = [false; Indx (1:end-1) & ~indx (2:end)];s (indx) = 1;% Crossing the upper thresholdindx = ri > Thr Esh (2); indx = [false; Indx (1: end-1) & ~indx (2:end)];s (indx) = -1;% Fill in zero values with prior positionfor i = 2:length (s) if s (i) = = 0 S (i) = s (i-1); endend%% PNL Caclulationr = [0; s (1:end-1). *diff (price)-abs (diff (s)) *cost/2];sh = Scaling*sharpe (r,0); percent Plot if request EDIF Nargout = = 0 Ax (1) = subplot (3,1,1); Plot ([Price,ma]), grid on Legend (' Price ', [' Moving Average ', Num2str (M)]) title ([' RSI Results, Sharpe Ratio = ', num2s TR (sh,3)]) ax (2) = subplot (3,1,2); Plot ([Ri,thresh (1) *ones (Size (RI)), Thresh (2) *ones (Size (RI))]) grid on Legend ([' RSI ', Num2str (N)], ' Lower Threshold ', ' Upper Threshold ') title (' RSI ') ax (3) = subplot (3,1,3); Plot ([S,cumsum (R)]), grid on Legend (' Position ', ' cumulative return ', ' location ', ' best ') title ([' Final Return = ', num2s TR (SUM (r), 3), ' (', Num2str (sum (r)/price (1) *100,3), '% ') ') linkaxes (ax, ' X ') else percent Return values for i = 1:nargout Switch I case 1 varargout{1} = s; % Signal Case 2 Varargout{2} = r; % return (PNL) Case 3 varargout{3} = sh; % Sharpe ratio case 4 varargout{4} = ri; % RSI signal Case 5 varargout{5} = ma; % moving average case 6 varargout{6} = Thresh; % threshold otherwise warning (' Rsi:outputarg ',... ' Too Many output arguments requested, ignoring last ones '); End%switch End%forend%if%% examples%% supporting functions% Faster implementation of Rsindex found in financial Tool Boxfunction R=rsindex (x,n) L = Length (x);d x = diff ([0;x]); Up=dx;down=abs (DX);% up and down movesi=dx<=0;up (I) = 0;down (~i) =0;% calculate exponential moving averagesm1 = movavg (u P,n,n, ' e '); M2 = movavg (down,n,n, ' e '); warning OFFR = 100*m1./(m1+m2);%r (isNaN (R)) =50;i2=~ ((Up+down) >0); R (I2) =50;warning on
Writing your paper: the RSI function of MATLAB