Optimizing Moving Average System

3 Ansichten (letzte 30 Tage)
Maisam Zaidi
Maisam Zaidi am 22 Apr. 2022
Kommentiert: Maisam Zaidi am 22 Apr. 2022
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 Kommentare
Torsten
Torsten am 22 Apr. 2022
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 am 22 Apr. 2022
Alright. That seems possible.
I will do that.
Thank you.

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Kategorien

Mehr zu Get Started with Optimization Toolbox finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by