Optimizing Moving Average System

조회 수: 3 (최근 30일)
Maisam Zaidi
Maisam Zaidi 2022년 4월 22일
댓글: Maisam Zaidi 2022년 4월 22일
Hello
I am trying to optimize a moving average crossover system (LONG ONLY: For the sake of simplicity). The rules are simple: BUY when fast moving average crosses above(over) slow moving average. I have created an objective function as follows:
function SMA_CROSS_NAV = macrossnav(x,prices)
fastMA = x(1);
slowMA = x(2);
returns = tick2ret(prices);
MAFAST = movavg(prices,'simple',fastMA);
MASLOW = movavg(prices,'simple',slowMA);
signal = MAFAST > MASLOW;
strategy_returns = returns.*signal(1:end-1);
strategy_nav = ret2tick(strategy_returns);
SMA_CROSS_NAV = -(strategy_nav(end)-strategy_nav(1));
end
I am trying to find out that which set of FAST & SLOW moving average will maximize the SMA_CROSS_NAV value!
I have created the following script for the optimization process:
%% Step 1: Load the input data
load UNITYdata.mat
figure
plot(dateIS,closeIS)
grid on;
xlabel('Time (years)')
ylabel('Price')
title('UNITY FOODS LIMITED (PSX)')
%% Step 2: Set up the optimisation problem
warning off;
%% Define objective function
fH = @(x) macrossnav(x,closeIS);
%% Define design variables
% Design variables and initial guess
fastMA = 1:100;
slowMA = 101:200;
x0 = [fastMA;slowMA];
%% Define constraints
% Upper and lower bounds
lb = [1;100];
ub = [101;200];
% Linear inequalities (fastMA must be smaller than slowMA)
A = 1:200;
b = -1;
% Linear equalities
Aeq = [];
Beq = [];
%% Step 3: Perform the three optimisation techniques
%% Pattern search optimization
x_ps = patternsearch(fH,x0,A,b,Aeq,Beq,lb,ub)
%% Use the genetic algorithm optimisation
x_ga = ga(fH,numel(x0),A,b,Aeq,Beq,lb,ub)
%% Use the fmincon solver
opt = optimoptions('fmincon','Algorithm','interior-point','Display','off');
opt.TolFun = 1e-20;
opt.OptimalityTolerance = 1e-20;
opt.StepTolerance = 1e-20;
opt.FiniteDifferenceStepSize = 1;
x_f = fmincon(fH,x0,A,b,Aeq,Beq,lb,ub,[],opt)
Running the above script gives an error. I have attached the picture of the error.
Any help on how to correct the mistake and run the optimization process in a correct manner would be hugely appreciated.
I have attached the data file as well.
Thank you.
Regards,
Maisam
  댓글 수: 4
Torsten
Torsten 2022년 4월 22일
The easiest way seems to be brute force: Call "macrossnav" for the possible integer combinations of x(1) and x(2) and take the combination for which you get back a minimum value for SMA_CROSS_NAV.
Maisam Zaidi
Maisam Zaidi 2022년 4월 22일
Alright. That seems possible.
I will do that.
Thank you.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with Optimization Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by