image thumbnail

Mean Variance Portfolio Optimization of S&P 500 Stocks

version (112 KB) by Moeti Ncube
Example Portfolio optimization that can be used for backtesting cross-sectional stock strategies


Updated 05 Jan 2015

View License

Main File: master_stock_code.m
The code is meant only as an example, but I believe it is a decent template for a medium-frequency algorithmic trading strategy. I have successfully implemented trading strategies based on the structure and ideas of this code in other markets; this code is the result of an initial attempt to apply that code to US stocks data.
Strategy overview: This code can be use to find an optimal weighting allocation across S&P500 stocks over a historical lag period. It is setup to download most recent s&p500 data (this step can be commented out) and optimize historical day to yesterday's date (yesterday would be an out-of-sample date)

The Algorithm takes each stock, within the s&p 500, and submits the following limit orders:
1) Bid Limit order: mean-alpha std deviations
2) Off Limit order: mean+alpha std deviations
The historical performance of each bidding strategy over
the past 'hist_lag' period is treated as individual strategy within a
portfolio basket of strategies.

The algorithm assigns a weighting, between 0 and 1, to each individual strategy,
so that the Mean-Variance criteria over the entire portfolio basket of
strategies is optimized.

This code applies a unique approach to this
optimization (see optimization section), using ideas from dynamic programming,
to quickly compute the optimization of a large portfolio matrix

The optimal allocation, determine over the previous hist_lag period, is
then applied the next day 'out of sample'.

This procedure is iteratively backtested from the 'begin_date' to the
'end_date'; the daily % return performance is computed and stored.

port_hist: The historical performance of the optimal collection of stocks

port_matrix: The optimized basket of stocks
column1: The stock location
column2: Long=1, Short=-1;
column3: weight of row, sum of column3 equals 1
column4: return of row out of sample.

Cite As

Moeti Ncube (2022). Mean Variance Portfolio Optimization of S&P 500 Stocks (, MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2013b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!