Last active
August 29, 2015 14:01
-
-
Save caub/58dd9b71225c6b026aae to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% largely inspired from http://www.mathworks.fr/matlabcentral/fileexchange/37932-automated-trading-with-matlab-2012 | |
% small script to generate signals from rsi indicator, and calculate the return | |
function [s,r,sh,mar] = rsi(price,M,N,thresh,scaling,cost) | |
% returns the signals array, the returns array (profit and loss), the | |
% sharpe ratio, the MAR ratio | |
if nargin==0 | |
% fill params for you.. | |
M = 22; % Moving Average for rsi | |
N = 14; % rsi loopback | |
thresh = [20, 80];% signal threshold (buy, sell) for rsi | |
cost = 0.0001; % simulate a cost of 1pip per trade (approx the spread between bid and ask price) | |
scaling = sqrt(250*1440); %for sharpe ratio, depends on the frequency of the data, here minutes | |
price = 1.3 + 0.1*randn(100,1) + sin(linspace(0,10,100)'); | |
end | |
ma = movavg(price,M,M,'e'); % smooth it before applying rsi | |
ri = rsindex(price - ma, N); | |
%% Position signal | |
s = zeros(size(price)); | |
% Crossing the lower threshold | |
indx = ri < thresh(1); | |
indx = [false; indx(1:end-1) & ~indx(2:end)]; | |
s(indx) = 1; | |
% Crossing the upper threshold | |
indx = ri > thresh(2); | |
indx = [false; indx(1:end-1) & ~indx(2:end)]; | |
s(indx) = -1; | |
% Fill in zero values with prior position | |
for i = 2:length(s) | |
if s(i) == 0 | |
s(i) = s(i-1); | |
end | |
end | |
%% PNL Calculation | |
trades = [0; 0; diff(s(1:end-1))]; % shift trading by 1 period, time for the order to pass | |
cash = cumsum(-trades.*price-abs(trades)*cost/2); | |
pandl = [0; s(1:end-1)].*price + cash; | |
r = diff(pandl); | |
sh = scaling*sharpe(r,0); | |
[mdd, imdd] = maxdrawdown(pandl,'arithmetic'); | |
mar = 0; | |
if ~isnan(imdd) % most of the time | |
mar= pandl(end)/price(1) / mdd/price(imdd(1)); % scaling mdd with the value reached | |
end | |
%% Supporting Functions | |
% Faster implementation of rsindex found in Financial Toolbox | |
function r=rsindex(x,N) | |
L = length(x); | |
dx = diff([0;x]); | |
up=dx; | |
down=abs(dx); | |
% up and down moves | |
I=dx<=0; | |
up(I) = 0; | |
down(~I)=0; | |
% calculate exponential moving averages | |
m1 = movavg(up,N,N,'e'); m2 = movavg(down,N,N,'e'); | |
warning off | |
r = 100*m1./(m1+m2); | |
%r(isnan(r))=50; | |
I2=~((up+down)>0); | |
r(I2)=50; | |
warning on |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment