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.
Moeti Ncube (2021). Mean Variance Portfolio Optimization of S&P 500 Stocks (https://www.mathworks.com/matlabcentral/fileexchange/48766-mean-variance-portfolio-optimization-of-s-p-500-stocks), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Platform CompatibilityWindows macOS Linux
- Sciences > Business, Economics, and Finance > Financial Toolbox > Portfolio Optimization and Asset Allocation >
- Sciences > Business, Economics, and Finance > Datafeed Toolbox > Financial Data >
- Sciences > Business, Economics, and Finance > Datafeed Toolbox > Financial Data > Transaction Cost Analysis >
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!