Portfolio Optimization​
​

Andres Lopez Martinez

Asset Definitions

We define the assets that are going to be used. In this example, they were chosen among the top 10 performing stocks in S&P.
(*"AAPL","MSFT","AMZN","JNJ","XOM","JPM","GOOG"*)​​(*"FAS","FIW","FYX","PBP","GEX","PSP"*)​​(*"OIH","MUB","PSI","GDX","KRE","ITA","TLT"*)​​portfolio={"OIH","MUB","PSI","GDX","KRE","ITA","TLT"};
We get the pricing data by specifying 1/1/10 as a starting date and then proceed to plot it.
data=FinancialData[#,"Close",{2010,1,1},"Value"]&/@portfolio;
ListPlot[data,PlotRangeAll,JoinedTrue,PlotLegendsSwatchLegend[portfolio]]
500
1000
1500
50
100
150
OIH
MUB
PSI
GDX
KRE
ITA
TLT

Returns

What we are interested in are returns—that is, the percentage change of each asset price with respect to the one from the previous trading day.
getReturns[lst_]:=(lst[[#+1]]/lst[[#]])-1&/@Range[Length[lst]-1];
returns=getReturns[data[[#]]]&/@Range[Length[portfolio]];
Having calculated the returns with the defined function, we can proceed to plot the data.
ListPlot[returns,PlotRangeAll,JoinedTrue,PlotLegendsSwatchLegend[portfolio]]
500
1000
1500
-0.10
-0.05
0.05
0.10
OIH
MUB
PSI
GDX
KRE
ITA
TLT

Optimization

Testing

Efficient Frontier

Backtesting

An important part of building models is to test them to analyze their performance on real scenarios. Backtesting consists of doing this with past data—that is, testing the model with information we already know.
We begin by extracting the asset’s weights.
alloc=Last[mv[[2]][[#]]]&/@Range[Length[portfolio]]
{0.05,0.25,0.05,0.05,0.1,0.25,0.25}
port=TimeSeriesThread[alloc.#&,data];
pc=PieChart[alloc,ChartLabelsPlaced[Style[#,Small,Italic,FontFamily"Helvetica"]&/@portfolio,"RadialCallout"],ColorFunction"DarkBands",SectorOrigin{{π/4,"Clockwise"},0},ChartStyleOpacity[.6],ImageSize200,ImagePadding{{15,15},{0,0}}];
ListLinePlot[port,FillingAxis,EpilogInset[pc,{400,95}],ImageSizeLarge]
backtestShort[startDate_,window_,period_]:=Block[{data,endDate,ret,weights,meanRet,portfolioMean,covMat,portfolioVar,mv,alloc,futureData,port},(​​Clear[data,endDate,ret,weights,meanRet,portfolioMean,covMat,portfolioVar,mv,alloc,futureData,port];​​endDate=DayPlus[startDate,window*period,"BusinessDay"];​​data=FinancialData[#,"Close",{startDate,endDate}]&/@portfolio;​​ret=FinancialData[#,"FractionalChange",{startDate,endDate},"Value"]&/@portfolio;​​weights=Transpose[{Subscript[w,#]&/@portfolio}];​​meanRet={Mean[#]&/@ret};​​portfolioMean=Flatten[meanRet.weights][[1]];​​covMat=Covariance[Transpose[ret]];​​portfolioVar=Flatten[Transpose[weights].covMat.weights][[1]];​​mv=NMinimize[{portfolioVar,Union[​​GreaterEqualThan[0.05][#]&/@Flatten[Transpose[weights]],​​LessEqualThan[0.25][#]&/@Flatten[Transpose[weights]],​​List[Total[weights][[1]]1],​​List[GreaterEqualThan[0.0][portfolioMean]]​​]},​​Flatten[weights]];;​​alloc=Last[mv[[2]][[#]]]&/@Range[Length[portfolio]];​​futureData=FinancialData[#,"Close",{endDate,DayPlus[endDate,window,"BusinessDay"]}]&/@portfolio;​​List[mv[[2]]TimeSeriesThread[alloc.#&,futureData]]​​)];
portChart[port_]:=Block[{alloc},(​​alloc=Last[port[[#]]]&/@Range[Length[portfolio]];​​PieChart[alloc,ChartLabelsPlaced[Style[#,Small,Italic,FontFamily"Helvetica"]&/@portfolio,"RadialCallout"],ColorFunction"DarkBands",SectorOrigin{{π/4,"Clockwise"},0},ChartStyleOpacity[.6],ImageSize150,ImagePadding{{15,15},{0,0}}]​​)];
backtestLong[startDate_,window_,periods_]:=backtestShort[startDate,window,#]&/@Range[periods];
date=DateObject[{2010,1,1}];​​wind=252;​​period=6;
test=backtestLong[date,wind,period];
bla=Last[test[[#]][[1]]]&/@Range[period];​​nf=Nearest[Flatten[bla,1]];​​DateListPlot[bla,EpilogDynamic@DynamicModule[​​{pt=nf[MousePosition[{"Graphics",Graphics},{0,0}]],scaled=MousePosition[{"GraphicsScaled",Graphics},None]},If[scaled===None,{},{Text[{DateString[pt[[1]][[1]],{"Month","/","Day","/","Year"}],pt[[1]][[2]]},pt[[1]],{1.5Sign[scaled[[1]]-.5],0},BackgroundNone],AbsolutePointSize[7],Point[pt],Blue,AbsolutePointSize[5],Point[pt]}]​​],​​FillingAxis,ImageSizeLarge,FrameTrue,FrameLabel{"Year","Portfolio balance"},BaseStyle14,PlotRangeAll]//Quiet
FURTHER EXPLORATIONS
​
AUTHORSHIP
Andres Lopez Martinez