Basket Optimization in Matlab - Matlab, R project and Python | futures io social day trading
futures io futures trading


Basket Optimization in Matlab
Updated: Views / Replies:2,292 / 2
Created: by Oxymoron Attachments:0

Welcome to futures io.

(If you already have an account, login at the top of the page)

futures io is the largest futures trading community on the planet, with over 90,000 members. At futures io, our goal has always been and always will be to create a friendly, positive, forward-thinking community where members can openly share and discuss everything the world of trading has to offer. The community is one of the friendliest you will find on any subject, with members going out of their way to help others. Some of the primary differences between futures io and other trading sites revolve around the standards of our community. Those standards include a code of conduct for our members, as well as extremely high standards that govern which partners we do business with, and which products or services we recommend to our members.

At futures io, our focus is on quality education. No hype, gimmicks, or secret sauce. The truth is: trading is hard. To succeed, you need to surround yourself with the right support system, educational content, and trading mentors Ė all of which you can find on futures io, utilizing our social trading environment.

With futures io, you can find honest trading reviews on brokers, trading rooms, indicator packages, trading strategies, and much more. Our trading review process is highly moderated to ensure that only genuine users are allowed, so you donít need to worry about fake reviews.

We are fundamentally different than most other trading sites:
  • We are here to help. Just let us know what you need.
  • We work extremely hard to keep things positive in our community.
  • We do not tolerate rude behavior, trolling, or vendors advertising in posts.
  • We firmly believe in and encourage sharing. The holy grail is within you, we can help you find it.
  • We expect our members to participate and become a part of the community. Help yourself by helping others.

You'll need to register in order to view the content of the threads and start contributing to our community.  It's free and simple.

-- Big Mike, Site Administrator

Reply
 
Thread Tools Search this Thread
 

Basket Optimization in Matlab

  #1 (permalink)
Just starting out...
Chennai
 
Futures Experience: Intermediate
Platform: Matlab, Multicharts
 
Posts: 7 since Apr 2010
Thanks: 10 given, 5 received

Basket Optimization in Matlab

Data Arrangement : Closing price of N stocks, arranged as T*N matrix (name this matrix as 'data' and save it as MABasketOptData.mat if you don't want to modify the code below).
Example System : MA-Price crossover
Customizable Parameters: Initial Capital, Execution Lag, Starting Optimization Value, Increments, Ending Optimization Value, Transaction Cost
Optimization Objective: Maximize slope of equity curve, calculated via least squares regression (Without intercept term), with respect to time

Results Image:
Please register on futures.io to view futures trading content such as post attachment(s), image(s), and screenshot(s).


I've regressed log of equity value w.r.t time unit (as 1,2,3...), so the beta appears as .01 in all cases owing to short formatting. In actual case, it looks more like:
0.012439499782394
0.011914742989712
0.012889507971229 etc

You can see this by using 'format long' and typing BSBeta.

 
Code
load MABasketOptData.mat
tic
format bank

%Inputs
InitialCapital = 100000;
ExecutionLag = 0; %In days
BeginOpt = 10;
EndOpt = 100;
Increments = 5;
MAPds = BeginOpt:Increments:EndOpt;
TransactionCost = 0.3; % In Percentage


[~,StocksInPortfolio] = size(data);

BSFinalEquityValue = zeros(StocksInPortfolio,1);
BSSharpeRatio = zeros(StocksInPortfolio,1);
BSPercentProfitable = zeros(StocksInPortfolio,1);
BSDrawdown = zeros(StocksInPortfolio,1);
BSBeta = zeros(StocksInPortfolio,1);
BSBestMAInput = zeros(StocksInPortfolio,1);

for StockNumber = 1:StocksInPortfolio
Input = data(:,StockNumber);

[rows,~] = size(Input);
[~,columns] = size(MAPds);
Time = cumsum(ones(rows,1));

%Variables
MovAvg = zeros(rows,1);
position = zeros(rows,1);
returns = zeros(rows,1);
PositionProfit = [];
FinalEquityValue = zeros(columns,1);
SharpeRatio = zeros(columns,1);
PercentProfitable  = zeros(columns,1);
Drawdown  = zeros(columns,1);
Beta  = zeros(columns,1);

for j = 1:columns
    for i = MAPds(1,j):rows
        
        %Calculation of Moving Average
        MovAvg(i,1) = sum(Input(i-(MAPds(1,j)-1):i,1))/MAPds(1,j);
        
        %Calculation of Position Direction
        if Input(i,1) > MovAvg(i,1)
            position(i,1) = 1;
        else
            position(i,1) = 0;
        end
        
        %Calculation of returns
        returns(i,1) = Input(i,1)/Input(i-1,1);
    end
    
    %Calculation of Percent Profitable
    EntryPrice = Input(position > lagmatrix(position,1));
    ExitPrice  = Input(position < lagmatrix(position,1));
    [NoOfTrades,~] = size(ExitPrice);
    
    PositionProfit = EntryPrice(1:NoOfTrades) < ExitPrice(1:NoOfTrades);
    
    Signal = or(position > lagmatrix(position,1),position < lagmatrix(position,1));
    TransactionHit = Signal.*TransactionCost/100;
    
    %Time Series Statistics
    positionLag = lagmatrix(position,ExecutionLag+1);
    PositionalReturns = 1 + positionLag.*(returns - 1) - TransactionHit;
    PositionalReturns(isnan(PositionalReturns)) = 1;
    EquityCurve = InitialCapital*cumprod(PositionalReturns);
    
    %Specific Statistics
    FinalEquityValue(j,1) = EquityCurve(end);
    SharpeRatio(j,1) = (EquityCurve(end) - InitialCapital)/std(EquityCurve);
    PercentProfitable(j,1) = sum(PositionProfit)/NoOfTrades;
    Drawdown(j,1) = maxdrawdown(EquityCurve);
    Beta(j,1) = regress(log(EquityCurve),Time);
end
%%%%%%%%%%%%%%%%%%%%%%%%%End of Optimization Stage%%%%%%%%%%%%%%%%%%%%%%%%%

%Find the best combination
[j,~] = find(Beta == max(Beta));
j = j(1,1);

for i = MAPds(1,j):rows
    
    %Calculation of Moving Average
    MovAvg(i,1) = sum(Input(i-(MAPds(1,j)-1):i,1))/MAPds(1,j);
    
    %Calculation of Position Direction
    if Input(i,1) > MovAvg(i,1)
        position(i,1) = 1;
    else
        position(i,1) = 0;
    end
    
    %Calculation of returns
    returns(i,1) = Input(i,1)/Input(i-1,1);
end

%Calculation of Percent Profitable
EntryPrice = Input(position > lagmatrix(position,1));
ExitPrice  = Input(position < lagmatrix(position,1));
[NoOfTrades,~] = size(ExitPrice);

PositionProfit = EntryPrice(1:NoOfTrades) < ExitPrice(1:NoOfTrades);

Signal = or(position > lagmatrix(position,1),position < lagmatrix(position,1));
TransactionHit = Signal.*TransactionCost/100;

%Time Series Statistics
positionLag = lagmatrix(position,ExecutionLag+1);
PositionalReturns = 1 + positionLag.*(returns - 1) - TransactionHit;
PositionalReturns(isnan(PositionalReturns)) = 1;
EquityCurve = InitialCapital*cumprod(PositionalReturns);

%Specific Statistics
BSFinalEquityValue(StockNumber,1) = EquityCurve(end);
BSSharpeRatio(StockNumber,1) = (EquityCurve(end) - InitialCapital)/std(EquityCurve);
BSPercentProfitable(StockNumber,1) = sum(PositionProfit)/NoOfTrades;
BSDrawdown(StockNumber,1) = maxdrawdown(EquityCurve);
BSBeta(StockNumber,1) = regress(log(EquityCurve),Time);
BSBestMAInput(StockNumber,1) = MAPds(1,j);

end

StockNumber = cumsum(ones(StocksInPortfolio,1));

Statistics = [StockNumber BSBestMAInput,BSFinalEquityValue,BSSharpeRatio,BSPercentProfitable,BSDrawdown,BSBeta];
disp('StockNumber  BSBestMAInput  BSFinalEquityValue  BSSharpeRatio  BSPercentProfitable  BSDrawdown  BSBeta');
disp(Statistics);

clear PositionalReturns EntryPrice ExitPrice ExecutionLag TransactionHit TransactionCost Signal i position positionLag
clear rows returns PositionProfit MovAvg BeginOpt Beta Drawdown EndOpt EquityCurve FinalEquityValue Increments MAPds NoOfTrades
clear Time columns j StockNumber SharpeRatio PercentProfitable
toc


Last edited by Oxymoron; December 28th, 2010 at 03:05 AM.
Reply With Quote
The following 2 users say Thank You to Oxymoron for this post:
 
  #2 (permalink)
Quick Summary
Quick Summary Post

Quick Summary is created and edited by users like you... Add FAQ's, Links and other Relevant Information by clicking the edit button in the lower right hand corner of this message.

 
  #3 (permalink)
Site Administrator
Manta, Ecuador
 
Futures Experience: Advanced
Platform: My own custom solution
Favorite Futures: E-mini ES S&P 500
 
Big Mike's Avatar
 
Posts: 46,240 since Jun 2009
Thanks: 29,353 given, 83,234 received


Thanks for sharing

Mike

Due to time constraints, please do not PM me if your question can be resolved or answered on the forum.

Need help?
1) Stop changing things. No new indicators, charts, or methods. Be consistent with what is in front of you first.
2) Start a journal and post to it daily with the trades you made to show your strengths and weaknesses.
3) Set goals for yourself to reach daily. Make them about how you trade, not how much money you make.
4) Accept responsibility for your actions. Stop looking elsewhere to explain away poor performance.
5) Where to start as a trader? Watch this webinar and read this thread for hundreds of questions and answers.
6)
Help using the forum? Watch this video to learn general tips on using the site.

If you want
to support our community, become an Elite Member.

Reply With Quote
The following user says Thank You to Big Mike for this post:

Reply



futures io > > > > Basket Optimization in Matlab

Thread Tools Search this Thread
Search this Thread:

Advanced Search



Upcoming Webinars and Events (4:30PM ET unless noted)

Jigsaw Trading: TBA

Elite only

FuturesTrader71: TBA

Elite only

NinjaTrader: TBA

Jan 18

RandBots: TBA

Jan 23

GFF Brokers & CME Group: Futures & Bitcoin

Elite only

Adam Grimes: TBA

Elite only

Ran Aroussi: TBA

Elite only
     

Similar Threads
Thread Thread Starter Forum Replies Last Post
MATLAB Dates on the x - axis jakfourie Matlab, R project and Python 11 June 27th, 2011 03:55 AM
matlab c# wh The Elite Circle 3 June 14th, 2011 09:22 PM
Rithmic and matlab tradersheldon Matlab, R project and Python 1 January 28th, 2011 01:16 PM
Matlab and ESignal MXASJ Matlab, R project and Python 3 July 29th, 2010 08:43 AM


All times are GMT -4. The time now is 12:12 PM.

Copyright © 2017 by futures io, s.a., Av Ricardo J. Alfaro, Century Tower, Panama, +507 833-9432, info@futures.io
All information is for educational use only and is not investment advice.
There is a substantial risk of loss in trading commodity futures, stocks, options and foreign exchange products. Past performance is not indicative of future results.
no new posts
Page generated 2017-12-15 in 0.41 seconds with 19 queries on phoenix via your IP 54.226.34.209