AppendTo[$Path, "c:\\Mathapps"];

Remove[MeanVector];

strmean = 
        OpenRead["c:\Dokumenty\Mathematica\mean.txt"];
mean = 
        ReadList[strmean, Number];
Close[strmean];
strcov = 
        OpenRead["c:\Dokumenty\Mathematica\covariance.txt"];
covariance = 
        ReadList[strcov, Number, 
          RecordLists -> True];
Close[strcov];
rf = 0.00165272294;

N[mean, 5]

m1={-0.000992488533927622, 0.00572524775783378, 0.00904818959590086, 
  -0.00144968966764537, -0.0174045537023702, 0.00570188394543127, 
  0.00333476815091662, 0.00215075479228363}

N[covariance, 5]

i1={{0.00135640293495777, 0.000256330097904098, 0.000333037161321956, 
   0.000180223328810003, 0.000281325992644196, 0.000593263545509886, 
   0.000713610711759175, 0.000320932535820455}, {0.000256330097904098, 
   0.00235439634554186, 0.000442407197078591, 6.57567906193998*^-6, 
   0.000401068448708833, 0.000593785356343409, 0.000130961261626908, 
   0.000293338399396577}, {0.000333037161321956, 0.000442407197078591, 
   0.00157895651834543, -0.000116804549527263, 0.000185336104268171, 
   0.000176059157865, 0.000341400743910472, 0.000186624552570071}, 
  {0.000180223328810003, 6.57567906193998*^-6, -0.000116804549527263, 
   0.00616786555694974, 0.000484828341822248, 0.000850333422445824, 
   0.0000774803938060802, 0.000439412705238888}, {0.000281325992644196, 
   0.000401068448708833, 0.000185336104268171, 0.000484828341822248, 
   0.00945147795376653, 0.00178331918975426, 0.000050987274991634, 
   0.00149823427374484}, {0.000593263545509886, 0.000593785356343409, 
   0.000176059157865, 0.000850333422445824, 0.00178331918975426, 
   0.00738754498647722, 0.00103084013803777, 0.000934434830622224}, 
  {0.000713610711759175, 0.000130961261626908, 0.000341400743910472, 
   0.0000774803938060802, 0.000050987274991634, 0.00103084013803777, 
   0.0021036055256453, 0.000240818723671803}, {0.000320932535820455, 
   0.000293338399396577, 0.000186624552570071, 0.000439412705238888, 
   0.00149823427374484, 0.000934434830622224, 0.000240818723671803, 
   0.00277726103166242}}

ef1 = 
      efffront[mean, covariance, w]
FindMinimum[
      ef1[[1]], {w,  .2}]
ef2 = 
      EfficientFrontier[mean, covariance, w]
FindMinimum[ef2[[1]], {w,  .2}]

\(TraditionalForm\`portfolioriskless[mean_, 
        covariance_, μ_ (*\ desired\ return\ *) , \ 
        r0_ (*\ riskless\ return\ *) ] := 
      Module[{n = Length[mean], λ1, λ2, x, xx, 
          x0}, 
x = Array[xx, n]; 
        ones = Table[1, {n}]; 
{x0, x} /. 
            Solve[{covariance . 
                    x == λ1*ones + λ2*
                      mean, \ λ1 + λ2*r0 == 0, 
                mean . x + r0*x0 == μ, 
                ones . x + x0 == 1}, {x0, x, λ1, λ2} // 
                Flatten] // 
          Flatten
	\ \ \ \ \ \ \ \ ]\)
res1 = 
        portfolioriskless[{r1, r2}, {{v11, v12}, {v12, v22}}, μ  ,  
          r0  ];
  
Apply[Plus, res1]
res1 . {r0, r1, r2} // Simplify

pexam = 
      portfolio[{0.04, 
          0.06}, {{0.005^2, 0.00002}, {0.00002, 
            0.01^2}}, δ]

portfolioriskless[{0.04, 
        0.06}, {{0.005^2, 0.00002}, {0.00002, 0.01^2}}, 0.032, 
      0.02]

Table[{μ, 
          portfolioriskless[{0.04, 
              0.06}, {{0.005^2, 0.00002}, {0.00002, 0.01^2}}, μ, 
            0.02]}, {μ, 0.02, 0.06, 
          0.01}]//TableForm

Table[{μ, 
          portfolioriskless[{4, 6}, {{0.5^2, 0.2}, {0.2, 1^2}}, μ, 
            2]}, {μ, 2, 6, 1}] // TableForm

globportfol[
        mean_, covariance_] := 
      Module[{ones = Table[1, {Length[mean]}], 
          au = Inverse[
              covariance]}, 
Print["Portfolio =  ", 
          au = au . 
                ones/(ones . au . 
                  ones)]; 
Print["Expected return =  \
", mean . au];  
Print["Variance = ", 
          au . covariance . au]]

globportfol[{0.04, 
        0.06}, {{0.005^2, 0.00002}, {0.00002, 
          0.01^2}}]
globportfol[{4, 
        6}, {{ .5^2,  .2}, { .2, 1}}]

ParametricPlot[
        efffront({0.04, 0.06}, {{0.005^2, 0.00002}, {0.00002, 0.01^2}}, 
          x), 
{x, 0, 1}, PlotLabel -> label1, 
        FrameLabel -> label2];

{0.9411764705882353, 
        0.05882352941176469} . {{ .5^2,  .2}, { .2, 
          1}} . {0.9411764705882353, 
        0.05882352941176469}

butter[c1_, c2_, c3_, X1_, 
        X3_, S_] := -c1 - c3 + Max[X1 - S, 0] + Max[X3 - S, 0] + 2  c2 - 
          2*Max[(X1 + X3)/2 - S, 0] // 
        Simplify
Plot[butter[15, 4, 1, 100, 150, S], {S, 50, 200}, 
        PlotRange -> All];

(* Uvod do financi  Test 3 *)
Table[{r, (1000 + 1000*r/100)/(1000 + 
                    r) - 1}, {r, 10.0, 11.2, 0.1}]

n = 2; x = Array[xx, n]; 
    covariance = {{v11, v12}, {v12, v22}};
covariance . x
ones=Table[
        1, {n}]

portfolio[mean_, 
        covariance_, δ_]:=Module[{x1, x2, inv, 
          ones = Table[1, {Length[mean]}]}, 
inv = 
          Inverse[covariance]; 
x1 = 
          inv . mean/(ones . inv . mean); 
x2 = 
          inv . ones/(ones . inv . ones); 
δ*
              x1 + (1 - δ)*x2 // 
          Simplify]

portfolio[mean, covariance, 
      1]
portfolio[mean - rf, covariance, 
      1]
(Inverse[
              covariance] . (mean - 
                rf)/((Inverse[covariance] . (mean - rf)) . 
              Table[1, {Length[mean]}])) . 
      Table[1, {Length[mean]}]

portfolio[mean, covariance, δ]

portfolio[mean, 
      covariance, δ]
xglob = 
      FindMinimum[
        portfolio[mean, covariance, δ] . covariance . 
          portfolio[mean, 
            covariance, δ], {δ,  .5}]
Sqrt[xglob[[1]]]
portfolio[mean, covariance, 
      0]
mean . 
      portfolio[mean, covariance, 0]
portfolio[mean, covariance, 0] . covariance . 
      portfolio[mean, covariance, 0]
portfpesek = { .14369,  .7887, 0.0674, 0, 0, 0, 0, 
          0};
portfpesek . mean
\(TraditionalForm\`portfpesek . covariance . 
    portfpesek

\)
Table[{mean . portfolio[mean, covariance, δ], 
        portfolio[mean, covariance, δ] . covariance . 
          portfolio[mean, covariance, δ]}, {δ, 0, 1, 
        0.1}]

portfpesek = { .14369,  .7887, 0.0674, 0, 0, 0, 0, 
          0};
portfpesek . mean
portfpesek.covariance.portfpesek

portfpesek

nn = Length[mean]
xar = 
      ToExpression[
        Map[StringJoin[{"x"}, #] &, 
          Table[ToString[i], {i, nn}]]]
ones = 
        Table[1, {nn}];
  
f = (xar . covariance . xar/2 // 
            Simplify);
  
g = {xar . ones - 1, 
          xar . mean -    
            0.0064646};
  
h = {-xar} // 
        Flatten
  
xar0 = Table[1. /nn, {nn}];

sol = 
      MultiplierMethod[f, g, h, xar, xar0]
(xar /. sol[[2]]) . mean

sol[[2]]

optpesek = xar/.sol[[2]]

optpesek . mean
optpesek . covariance . optpesek

?? AppendTo

\(TraditionalForm\`\(x0 := 
        Module[{n = Length[xar], au}, 
	
          au = Table[Random[], {n}]; 
	
          au/Apply[Plus, au]];\)\)
ranres = {};
Do[
      AppendTo[ranres, 
        MultiplierMethod[f, g, h, xar, 
          x0]], 
{10}]

ranres

(xar /. ranres[[1, 2]]) . 
      mean
Map[mean . (xar /. (ranres[[#, 2]] &)), 
      Range[8]]

\(TraditionalForm\`\(\(
\)\(x0 = 
      Module[{n = Length[xar], au}, 
	
        au = Table[Random[], {n}]; 
	
        au/Apply[Plus, au]]\)\)\)

Needs["Optimization`MultiplierMethod`"];
Needs["Finance`Master`"];

?MultiplierMethod

EfficientFrontier[mean_, covariance_, w_] := 
      Module[{c, temp, weights, x}, c = {0, Apply[Plus, mean]}; 
        x = Map[Inverse[covariance] . (mean - #) &, c]; 
        x /= Apply[Plus, 
            Transpose[x]]; 
  
weights = {w, 1 - w} . 
            x; {weights . covariance . weights, weights . mean} // 
          Simplify
]

efffront[mean_, covariance_, 
        w_] := 
Module[{c, temp, weights, 
          x}, 
x = {mean, Table[1, {Length[mean]}]} . 
            Inverse[covariance]; 
x /= 
          Apply[Plus, 
            Transpose[x]]; 
weights = {w, 1 - w} . 
            x; {weights . covariance . weights, weights . mean} // 
          Simplify
]

stream = OpenRead["Finance\\Data\\stocks1.ret"];
n = Read[stream, Number]
tickers = Rest[Read[stream, Table[Word,{n+1}], 
   RecordSeparators -> {"\n"," ", "\t"}]]
   aux = Transpose[Partition[ReadList[stream, Number], n+1]];
Close[stream];

{months, returns} = {First[aux], Transpose[Rest[aux]]};

(* Expected returns and covariance matrix of the returns *)
mean1 = MeanVector[returns]
cov1=CovarianceMatrix[returns]

(* Definition of the objective function and the constraints *)

nn=Length[mean1]
xar=ToExpression[Map[StringJoin[{"x"},#]&,
	Table[ToString[i],{i,nn}]]]
ones=Table[1,{nn}];
(* Objective function *)
f=xar.cov1.xar/2 //Simplify
(* Equality constraints, portfolio, desired return = 3 *)
g={xar.ones-1,xar.mean1-3};
(* Inequality constraints, nonnegativity *)
h={-xar}//Flatten
(* Initial guess *)
xar0={0.1,0.2,0.4,0,0.3};

MultiplierMethod[f, g, h, xar, xar0] // 
      Timing

PaddedForm[TableForm[mean1, 
   TableHeadings -> {tickers}, 
   TableAlignments -> {Right}], {6, 3}]

cov1 = CovarianceMatrix[returns];

PaddedForm[TableForm[Prepend[cov1, 
   Map[StringJoin["    ",  #]&, tickers]], 
   TableHeadings->{tickers}], {6,  3}]

label1 = "Markowitz Efficient Frontier";
label2 = {"Portfolio Variance", "Portfolio Mean"};
label3 = {"Portfolio Standard Deviation", 
   "Portfolio Mean"};

ParametricPlot[EfficientFrontier[mean1, cov1, x], 
   {x, -.1, 1}, 
   PlotLabel -> label1, FrameLabel -> label2];

ParametricPlot[efffront[mean1, cov1, x], 
   {x, -.1, 1}, 
   PlotLabel -> label1, FrameLabel -> label2];

EfficientFrontier[mean1, cov1, xxx]
efffront[mean1, cov1, xxx]

x = 
        Map[Inverse[cov1] . # &, {mean1, 
            Table[1, {Length[mean1]}]}];
x /= Apply[Plus, Transpose[x]]; 
    weights = {w, 1 - w} . x; {weights . cov1 . weights, 
        weights . 
          mean1}//Simplify

Solve[{1 == la1*aa + la2*bb, mu == la1*bb + la2*cc}, {la1, 
          la2}] // Simplify

aarray = Array[a, 3];
aa = Outer[Times, aarray, aarray];
Eigenvalues[aa]
Eigenvectors[aa]

yy = Array[y, 5]
res = Solve[cov1 . Table[1, {5}] . yy == 0, yy]

reseni = yy /. res  // Flatten

reseni = 
      reseni /. {y[2] -> 1, y[3] -> 1, y[4] -> 1, 
          y[5] -> 1}

reseni . cov1 . Table[1, {5}]

cfa[r_] := {-100000, 
        40000 + 1000*r, 60000 + 1000*r}
cfb[r_] := {-50000, 25000 + 1000*r, 
        20000 + 1000*r}
pv[cf_, i_] := 
      cf . (1/((1 + i)^(Range[Length[cf]] - 
                    1)))
irr[cf_]:=FindRoot[
        pv[cf, x] == 0, {x, 
          0.1}]

Plot[
      Table[pv[cfa[r], i], {r, 10.1, 11.2, 0.1}] // Evaluate, {i, 
        0,  .7}]
Plot[
      Table[pv[cfb[r], i], {r, 10.1, 11.2, 0.1}] // Evaluate, {i, 0, 
        1.7}]
Plot[
      Table[pv[cfa[r], i] - pv[cfb[r], i], {r, 10.1, 11.2, 0.1}] // 
        Evaluate, {i, 0, 1.7}]
Table[
      irr[cfa[r]], {r, 10.1, 11.2, 0.1}]
Table[
      irr[cfb[r]], {r, 10.1, 11.2, 0.1}]
Table[
      irr[cfa[r] - cfb[r]], {r, 10.1, 11.2, 0.1}]

irr[{-1010, 100, 
        1100}]