-
Notifications
You must be signed in to change notification settings - Fork 101
/
PortfolioSupport.cs
1397 lines (1241 loc) · 55.4 KB
/
PortfolioSupport.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//==============================================================================
// Project: TuringTrader, simulator core
// Name: PortfolioSupport
// Description: portfolio support functionality
// History: 2019iii06, FUB, created
//------------------------------------------------------------------------------
// Copyright: (c) 2011-2023, Bertram Enterprises LLC dba TuringTrader.
// https://www.turingtrader.org
// License: This file is part of TuringTrader, an open-source backtesting
// engine/ trading simulator.
// TuringTrader is free software: you can redistribute it and/or
// modify it under the terms of the GNU Affero General Public
// License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
// TuringTrader is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public
// License along with TuringTrader. If not, see
// https://www.gnu.org/licenses/agpl-3.0.
//==============================================================================
#region libraries
using MathNet.Numerics.LinearAlgebra;
using System;
using System.Collections.Generic;
using System.Linq;
using TuringTrader.Indicators;
using TuringTrader.Simulator;
#endregion
namespace TuringTrader.Support
{
/// <summary>
/// Support class for portfolio construction
/// </summary>
public class PortfolioSupport
{
#region public class MarkowitzCLA
/// <summary>
/// Class encapsulating Markowitz CLA algorithm to calculate the
/// the efficient frontier.
/// </summary>
public class MarkowitzCLA
{
#region private class CLA
/// <summary>
/// Markowitz CLA algorithm. Based on Python implementation,
/// as presended in paper by David H. Bailey and Marcos Lopez de Prado.
/// <see href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=2197616"/>
/// <see href="http://www.quantresearch.info/Software.htm"/>
/// <see href="https://www.davidhbailey.com/dhbpapers/"/>
/// In case you are wondering why this code smells a bit like Python:
/// This implementation follows the paper closely; the overall structure,
/// as well as the names of methods and fields are (mostly) identical.
/// For an extensive discussion of the implementation, refere to the paper.
/// </summary>
private class CLA
{
#region internal data
/// <summary>
/// Vector w/ mean returns
/// </summary>
private readonly Vector<double> _mean;
/// <summary>
/// Covariance matrix
/// </summary>
private readonly Matrix<double> _covar;
/// <summary>
/// Lower bounds
/// </summary>
private readonly Vector<double> _lb;
/// <summary>
/// Upper bounds
/// </summary>
private readonly Vector<double> _ub;
/// <summary>
/// Solution
/// </summary>
private List<Vector<double>> _w;
/// <summary>
/// Lambdas
/// </summary>
private List<double?> _l;
/// <summary>
/// Gammas
/// </summary>
private List<double?> _g;
/// <summary>
/// Free weights
/// </summary>
private List<List<int>> _f;
#endregion
#region internal helpers
#region private void DumpTestVectors()
private void DumpTestVectors()
{
#if true
Output.WriteLine("double[] mean = {");
for (int i = 0; i < _mean.Count; i++)
Output.WriteLine(" {0:E15}, ", _mean[i]);
Output.WriteLine("};");
Output.WriteLine("double[,] covar = {");
for (int i = 0; i < _covar.RowCount; i++)
{
Output.Write(" { ");
for (int j = 0; j < _covar.ColumnCount; j++)
{
Output.Write("{0:E15}, ", _covar[i, j]);
}
Output.WriteLine("},");
}
Output.WriteLine("};");
Output.WriteLine("double[] lbound = {");
for (int i = 0; i < _lb.Count; i++)
Output.WriteLine(" {0:E15},", _lb[i]);
Output.WriteLine("};");
Output.WriteLine("double[] ubound = {");
for (int i = 0; i < _lb.Count; i++)
Output.WriteLine(" {0:E15},", _ub[i]);
Output.WriteLine("};");
#endif
}
#endregion
#region private void Solve()
private void Solve()
{
// compute the turning points, free sets and weights
var f_w = InitAlgo();
var f = f_w.Item1;
var w = f_w.Item2;
if (f == null)
{
// InitAlgo failed. The weights returned are
// still the best possible solution.
for (int i = 0; i < 2; i++)
{
_w.Add(w.Clone());
_l.Add(null);
_g.Add(null);
_f.Add(null);
}
return;
}
_w.Add(w.Clone());
_l.Add(null);
_g.Add(null);
_f.Add(new List<int>(f));
Matrix<double> covarF = null;
Matrix<double> covarF_inv = null;
Matrix<double> covarFB = null;
Vector<double> meanF = null;
Vector<double> wB = null;
int iter = 0;
while (true)
{
iter++;
//----------
// #1) case a) Bound one free weight
double l_in = -1.0;
int i_in = 0;
double bi_in = 0.0;
if (f.Count > 1)
{
var m = GetMatrices(f);
covarF = m.Item1;
covarFB = m.Item2;
meanF = m.Item3;
wB = m.Item4;
covarF_inv = covarF.Inverse();
int j = 0;
foreach (var i in f)
{
var l_bi = ComputeLambda(covarF_inv, covarFB, meanF, wB, j, new List<double> { _lb[i], _ub[i] });
var l = l_bi.Item1;
var bi = l_bi.Item2;
if (l > l_in)
{
l_in = l;
i_in = i;
bi_in = bi;
}
j++;
}
}
//----------
// #2) case b): Free one bounded weight
double l_out = -1.0;
int i_out = 0;
if (f.Count() < _mean.Count())
{
List<int> b = GetB(f);
foreach (int i in b)
{
var fi = new List<int>(f) { i };
var m = GetMatrices(fi);
covarF = m.Item1;
covarFB = m.Item2;
meanF = m.Item3;
wB = m.Item4;
covarF_inv = covarF.Inverse();
var ll = ComputeLambda(covarF_inv, covarFB, meanF, wB, fi.FindIndex(v => v == i), new List<double> { _w.Last()[i] });
var l = ll.Item1;
var bi = ll.Item2;
if ((_l.Last() == null || l < _l.Last())
&& (l > l_out))
{
l_out = l;
i_out = i;
}
}
}
#if true
// FIXME: sometimes method doesn't converge. It is unclear why
// that is, and it seems the issue can't be reproduced in the
// testbench. Probably, the numerical resolution of the test
// vectors dumped by the code below, is not sufficient to do so.
// It was observed that lambdas have been going in circles,
// while it seems they should be monotonically falling?
// For now, we just abort the method here.
bool noConvergence = _w.Count > 50 * _mean.Count;
#else
bool noConvergence = false;
#endif
if (l_in < 0.0 && l_out < 0.0
|| noConvergence)
{
if (noConvergence)
{
Output.WriteLine("MarkowitzCLA: aborted after {0} iterations", iter);
DumpTestVectors();
}
//----------
// #3) compute minimum variance solution
_l.Add(0.0);
var m = GetMatrices(f);
covarF = m.Item1;
covarFB = m.Item2;
meanF = m.Item3;
wB = m.Item4;
covarF_inv = covarF.Inverse();
meanF = Vector<double>.Build.Dense(meanF.Count, 0.0);
}
else
{
//----------
// #4) decide lambda
if (l_in > l_out)
{
_l.Add(l_in);
f.Remove(i_in);
w[i_in] = bi_in; // set value at the correct boundary
}
else
{
_l.Add(l_out);
f.Add(i_out);
}
var m = GetMatrices(f);
covarF = m.Item1;
covarFB = m.Item2;
meanF = m.Item3;
wB = m.Item4;
covarF_inv = covarF.Inverse();
}
//----------
// #5) compute solution vector
var wF_g = ComputeW(covarF_inv, covarFB, meanF, wB);
var wf = wF_g.Item1;
var g = wF_g.Item2;
for (var i = 0; i < f.Count; i++)
w[f[i]] = wf[i];
_w.Add(w.Clone());
_g.Add(g);
_f.Add(new List<int>(f));
if (_l.Last() == 0.0)
break;
}
//----------
// #6) Purge turning points
PurgeNumErr(10e-10);
PurgeExcess();
PurgeDuplicates(10e-10);
if (_w.Count <= 1)
{
Output.WriteLine("MarkowitzCLA: no turning points");
DumpTestVectors();
}
}
#endregion
#region private Tuple<List<int>, Vector<double>> InitAlgo()
private Tuple<List<int>, Vector<double>> InitAlgo()
{
// initialize all weights to lower bounds,
// assume all assets are free
var w = _lb.Clone();
// increase weights from lower bound to upper bound
var indicesDescendingMean = Enumerable.Range(0, _mean.Count)
.OrderByDescending(idx => _mean[idx])
.ToList();
foreach (var i in indicesDescendingMean)
{
w[i] = _ub[i];
// exceeding total weight of 1.0
if (w.Sum() >= 1.0)
{
// reduce weight to comply w/ constraints
w[i] += 1.0 - w.Sum();
// return first turning point
return new Tuple<List<int>, Vector<double>>
(
new List<int> { i },
w
);
}
}
return new Tuple<List<int>, Vector<double>>
(
null,
w
);
}
#endregion
#region private double ComputeBi(double c, List<double> bi)
private double ComputeBi(double c, List<double> bi)
{
return c > 0 ? bi[1] : bi[0];
}
#endregion
#region private Tuple<Vector<double>, double> ComputeW(...)
private Tuple<Vector<double>, double> ComputeW(
Matrix<double> covarF_inv, Matrix<double> covarFB,
Vector<double> meanF, Vector<double> wB)
{
// #1) compute gamma
var onesF = Vector<double>.Build.Dense(meanF.Count, 1.0);
double g1 = (onesF.ToRowMatrix().Multiply(covarF_inv).Multiply(meanF)).Single();
double g2 = (onesF.ToRowMatrix().Multiply(covarF_inv).Multiply(onesF)).Single();
double g;
Vector<double> w1 = null;
if (wB == null)
{
g = -(double)_l.Last() * g1 / g2 + 1 / g2;
w1 = Vector<double>.Build.Dense(onesF.Count, 0.0);
}
else
{
var onesB = Vector<double>.Build.Dense(wB.Count, 1.0);
var g3 = onesB.ToRowMatrix().Multiply(wB).Single();
var g4x = covarF_inv.Multiply(covarFB);
w1 = g4x.Multiply(wB);
var g4 = onesF.ToRowMatrix().Multiply(w1).Single();
g = -(double)_l.Last() * g1 / g2 + (1.0 - g3 + g4) / g2;
}
// #2) compute weights
var w2 = covarF_inv.Multiply(onesF);
var w3 = covarF_inv.Multiply(meanF);
var w = -w1 + g * w2 + (double)_l.Last() * w3;
return new Tuple<Vector<double>, double>(
w,
g);
}
#endregion
#region private Tuple<double, double> computeLambda(...)
private Tuple<double, double> ComputeLambda(
Matrix<double> covarF_inv, Matrix<double> covarFB,
Vector<double> meanF, Vector<double> wB,
int i, List<double> bix)
{
// #1) C
var onesF = Vector<double>.Build.Dense(meanF.Count, 1.0);
var c1 = onesF.ToRowMatrix().Multiply(covarF_inv).Multiply(onesF);
var c2 = covarF_inv.Multiply(meanF);
var c3 = onesF.ToRowMatrix().Multiply(covarF_inv).Multiply(meanF);
var c4 = covarF_inv.Multiply(onesF);
var c = (-c1 * c2[i] + c3 * c4[i]).Single();
if (c == 0.0)
{
return new Tuple<double, double>(0.0, 0.0);
}
// #2) bi
double bi = bix.Count > 1
? ComputeBi(c, bix)
: bix[0];
// #3) Lambda
if (wB == null)
{
// All free assets
return new Tuple<double, double>(
((c4[i] - c1 * bi) / c).Single(),
bi);
}
else
{
var onesB = Vector<double>.Build.Dense(wB.Count, 1.0);
var l1 = onesB.ToRowMatrix().Multiply(wB);
var l2x = covarF_inv.Multiply(covarFB);
var l3 = l2x.Multiply(wB);
var l2 = onesF.ToRowMatrix().Multiply(l3);
return new Tuple<double, double>(
(((1 - l1 + l2) * c4[i] - c1 * (bi + l3[i])) / c).Single(),
bi);
}
}
#endregion
#region private Tuple<Matrix<double>, Matrix<double>, Vector<double>, Vector<double>> GetMatrices(...)
private Tuple<Matrix<double>, Matrix<double>, Vector<double>, Vector<double>> GetMatrices(List<int> f)
{
var covarF = Matrix<double>.Build.Dense(
f.Count(), f.Count(),
(i, j) => _covar[f[i], f[j]]);
var meanF = Vector<double>.Build.Dense(
f.Count(),
i => _mean[f[i]]);
var b = GetB(f);
Matrix<double> covarFB = null;
Vector<double> wB = null;
if (b.Count > 0)
{
covarFB = Matrix<double>.Build.Dense(
f.Count(), b.Count(),
(i, j) => _covar[f[i], b[j]]);
wB = Vector<double>.Build.Dense(
b.Count(),
i => _w.Last()[b[i]]);
}
return new Tuple<Matrix<double>, Matrix<double>, Vector<double>, Vector<double>>(
covarF,
covarFB,
meanF,
wB);
}
#endregion
#region private List<Instrument> GetB(List<Instrument> f)
private List<int> GetB(List<int> f)
{
return Enumerable.Range(0, _mean.Count)
.Where(idx => !f.Contains(idx))
.ToList();
}
#endregion
#region private void PurgeNumErr(double tol)
private void PurgeNumErr(double tol)
{
// # Purge violations of inequality constraints (associated with ill-conditioned covar matrix)
int i = 0;
while (true)
{
var flag = false;
if (i == _w.Count())
break;
if (Math.Abs(_w[i].Sum() - 1.0) > tol)
{
flag = true;
}
else
{
foreach (var j in Enumerable.Range(0, _w[i].Count))
{
if (_w[i][j] - _lb[j] < -tol
|| _w[i][j] - _ub[j] > tol)
{
flag = true;
break;
}
}
}
if (flag)
{
//Output.WriteLine("CLA: purgeNumErr removing turning point");
_w.RemoveAt(i);
_l.RemoveAt(i);
_g.RemoveAt(i);
_f.RemoveAt(i);
}
else
{
i++;
}
}
}
#endregion
#region private void PurgeExcess()
private void PurgeExcess()
{
// # Remove violations of the convex hull
var i = 0;
var repeat = false;
while (true)
{
if (!repeat)
i++;
if (i >= _w.Count() - 1)
break;
var w1 = _w[i];
var mu1 = w1.ToRowMatrix().Multiply(_mean).Single();
var j = i + 1;
repeat = false;
while (true)
{
if (j >= _w.Count())
break;
var w2 = _w[j];
var mu2 = w2.ToRowMatrix().Multiply(_mean).Single();
if (mu1 < mu2)
{
//Output.WriteLine("CLA: purgeExcess removing turning point");
_w.RemoveAt(i);
_l.RemoveAt(i);
_g.RemoveAt(i);
_f.RemoveAt(i);
repeat = true;
break;
}
else
{
j++;
}
}
}
}
#endregion
#region private void PurgeDuplicates(double tolerance)
private void PurgeDuplicates(double tolerance)
{
// added by FUB, not part ofBailey & de Prado's
// original implementation
int i = 0;
while (i < _w.Count() - 2) // last member is min variance p/f
{
bool isDuplicate = true;
foreach (var j in Enumerable.Range(0, _w[i].Count()))
{
if (Math.Abs(_w[i][j] - _w[i + 1][j]) > tolerance)
{
isDuplicate = false;
break;
}
}
if (isDuplicate)
{
_w.RemoveAt(i);
_l.RemoveAt(i);
_g.RemoveAt(i);
_f.RemoveAt(i);
}
else
{
i++;
}
}
}
#endregion
#region private void EvalSR()
private double EvalSR(double a, Vector<double> w0, Vector<double> w1)
{
// Evaluate SR of the portfolio within the convex combination
var w = w0.Multiply(a).Add(w1.Multiply(1.0 - a));
return CalcReturn(w) / CalcVolatility(w);
}
#endregion
#region public void GoldenSection(...)
public Tuple<double, double> GoldenSection(Func<double, double> obj, double a, double b, bool minimum = false)
{
double tol = 1e-9;
double sign = minimum ? 1.0 : -1.0;
int numIter = (int)(Math.Ceiling(-2.078087 * Math.Log(tol / Math.Abs(b - a))));
var r = 0.618033989;
var c = 1.0 - r;
// Initialize
var x1 = r * a + c * b;
var x2 = c * a + r * b;
var f1 = sign * obj(x1);
var f2 = sign * obj(x2);
// Loop
for (var i = 0; i < numIter; i++)
{
if (f1 > f2)
{
a = x1;
x1 = x2;
f1 = f2;
x2 = c * a + r * b;
f2 = sign * obj(x2);
}
else
{
b = x2;
x2 = x1;
f2 = f1;
x1 = r * a + c * b;
f1 = sign * obj(x1);
}
}
return f1 < f2
? new Tuple<double, double>(x1, sign * f1)
: new Tuple<double, double>(x2, sign * f2);
}
#endregion
#endregion
#region public _MarkowitzCLA(...)
public CLA(
Vector<double> means,
Matrix<double> covariances,
Vector<double> lowerBounds,
Vector<double> upperBounds)
{
_mean = means;
_covar = covariances;
_lb = lowerBounds;
_ub = upperBounds;
#if true
for (var i = 0; i < _lb.Count; i++)
{
// FUB addition
// ill-conditioned vector. we assume that it is more likely
// for an algorithm to dynamically control the upper bounds,
// which is why we set the lower bound to those.
if (_lb[i] > _ub[i])
_lb[i] = _ub[i];
}
#endif
// TODO: not sure what this does
// if (mean == np.ones(mean.shape) * mean.mean()).all():mean[-1, 0] += 1e-5
_w = new List<Vector<double>>();
_l = new List<double?>();
_g = new List<double?>();
_f = new List<List<int>>();
Solve();
}
#endregion
//--- APIs to calc risk & return, based on weights
#region public double CalcReturn(Vector<double> w)
public double CalcReturn(Vector<double> w)
{
return w.ToRowMatrix().Multiply(_mean).Single();
}
#endregion
#region public double CalcVolatility(Vector<double> w)
public double CalcVolatility(Vector<double> w)
{
var variance = w.ToRowMatrix().Multiply(_covar).Multiply(w).Single();
return Math.Sqrt(variance);
}
#endregion
#region public bool CheckValidity(Vector<double> w)
public bool CheckValidity(Vector<double> w)
{
for (int i = 0; i < w.Count; i++)
{
if (w[i] < _lb[i] || w[i] > _ub[i])
return false;
}
return true;
}
#endregion
//--- APIs to return efficient frontier
#region public IEnumerable<Vector<double>> TurningPoints()
public IEnumerable<Vector<double>> TurningPoints()
{
foreach (var w in _w)
{
yield return w;
}
yield break;
}
#endregion
#region public IEnumerable<Tuple<double, double, Vector<double>>> EfFrontier(int points)
public IEnumerable<Tuple<double, double, Vector<double>>> EfFrontier(int points)
{
var n = points / (_w.Count - 1); // last is min-variance portfolio
var a = Enumerable.Range(0, n)
.Take(n - 1) // remove the 1, to avoid duplications
.Select(i => (double)i / (n - 1))
.ToList();
var b = Enumerable.Range(0, _w.Count - 1)
.ToList();
foreach (var i in b)
{
var w0 = _w[i];
var w1 = _w[i + 1];
if (i == b.Last())
a.Add(1.0); // include the 1 in the last iteration
foreach (var j in a)
{
var w = w1.Multiply(j).Add(w0.Multiply(1.0 - j));
var mu = w.ToRowMatrix().Multiply(_mean).Single();
var sigma = Math.Sqrt(w.ToRowMatrix().Multiply(_covar).Multiply(w).Single());
yield return new Tuple<double, double, Vector<double>>(
mu,
sigma,
w);
}
}
yield break;
}
#endregion
//--- APIs to return specific portfolios
#region public Tuple<double, Vector<double>> GetMaxSR()
public Tuple<double, Vector<double>> GetMaxSR()
{
if (_w.Count == 1)
{
// BUGBUG: sometimes we get here with only a single weight vector
var portfolio = new Tuple<double, Vector<double>>(0.0, _w[0]);
return portfolio;
}
var portfolioCandidates = new List<Tuple<double, Vector<double>>>();
for (var i = 0; i < _w.Count - 1; i++)
{
var w0 = _w[i];
var w1 = _w[i + 1];
var a_b = GoldenSection(
x => EvalSR(x, w0, w1),
0.0, 1.0,
false);
var a = a_b.Item1;
var b = a_b.Item2;
var w = w0.Multiply(a).Add(w1.Multiply(1.0 - a));
var portfolio = new Tuple<double, Vector<double>>(b, w);
portfolioCandidates.Add(portfolio);
}
return portfolioCandidates
.OrderByDescending(p => p.Item1)
.First();
}
#endregion
#region public Tuple<double, Vector<double>> GetMinVar()
public Tuple<double, Vector<double>> GetMinVar()
{
var variance = new List<double>();
foreach (var w in _w)
{
var a = w.ToRowMatrix().Multiply(_covar).Multiply(w).Single();
variance.Add(a);
}
var min = variance.Min();
var index = variance.FindIndex(v => v == min);
return new Tuple<double, Vector<double>>(min, _w[index]);
}
#endregion
}
#endregion
#region public class Portfolio
/// <summary>
/// Container to hold Markowitz Portfolio
/// </summary>
public class Portfolio
{
/// <summary>
/// Portfolio return (mu)
/// </summary>
public double Return;
/// <summary>
/// Portfolio risk (sigma)
/// </summary>
public double Risk;
/// <summary>
/// Instrument weights
/// </summary>
public Dictionary<Instrument, double> Weights;
/// <summary>
/// Weights meeting constraints
/// </summary>
public bool IsValid = true;
/// <summary>
/// Convert portfolio to human-readable string.
/// </summary>
/// <returns>portfolio string</returns>
override public string ToString()
{
string retvalue = string.Format("Return={0:P2}, Risk={1:P2}", Return, Risk);
foreach (var i in Weights.Keys)
if (Weights[i] > 0.0)
retvalue += string.Format(", {0}={1:P2}", i.Symbol, Weights[i]);
return retvalue;
}
}
#endregion
#region internal data
private CLA _cla;
private List<Instrument> _instruments;
#endregion
#region public MarkowitzCLA(...)
/// <summary>
/// Create new CLA object.
/// </summary>
/// <param name="universe">instrument universe</param>
/// <param name="meanFunc">instrument mean vector</param>
/// <param name="covarianceFunc">instrument covariance matrix</param>
/// <param name="lowerBoundFunc">portfolio lower bound vector</param>
/// <param name="upperBoundFunc">portfolio upper bound vector</param>
public MarkowitzCLA(
IEnumerable<Instrument> universe,
Func<Instrument, double> meanFunc,
Func<Instrument, Instrument, double> covarianceFunc,
Func<Instrument, double> lowerBoundFunc,
Func<Instrument, double> upperBoundFunc)
{
_instruments = universe
.ToList();
var mean = Vector<double>.Build.Dense(
_instruments.Count,
idx => meanFunc(_instruments[idx]));
var covar = Matrix<double>.Build.Dense(
_instruments.Count, _instruments.Count,
(row, col) => covarianceFunc(_instruments[row], _instruments[col]));
var lowerBound = Vector<double>.Build.Dense(
_instruments.Count,
idx => lowerBoundFunc(_instruments[idx]));
var upperBound = Vector<double>.Build.Dense(
_instruments.Count,
idx => upperBoundFunc(_instruments[idx]));
int numParams = Enumerable.Range(0, _instruments.Count)
.Where(i => upperBound[i] - lowerBound[i] > 0.0)
.Count();
_cla = new CLA(mean, covar, lowerBound, upperBound);
}
#endregion
#region public IEnumerable<Portfolio> TurningPoints()
/// <summary>
/// Return all turning points for efficient frontier.
/// </summary>
/// <returns>enumerable of portfolios</returns>
public IEnumerable<Portfolio> TurningPoints()
{
foreach (var w in _cla.TurningPoints())
{
var pf = new Portfolio
{
Return = _cla.CalcReturn(w),
Risk = _cla.CalcVolatility(w),
Weights = Enumerable.Range(0, w.Count)
.ToDictionary(
idx => _instruments[idx],
idx => w[idx]),
};
yield return pf;
}
yield break;
}
#endregion
#region public IEnumerable<Portfolio> EfficientFrontier(int points)
/// <summary>
/// Return efficient frontier, w/ specified # of points
/// </summary>
/// <param name="points">number of points</param>
/// <returns>portfolios at each point</returns>
public IEnumerable<Portfolio> EfficientFrontier(int points = 100)
{
foreach (var t in _cla.EfFrontier(points))
{
var mu = t.Item1;
var sigma = t.Item2;
var w = t.Item3;
var pf = new Portfolio
{
Return = mu,
Risk = sigma,
Weights = Enumerable.Range(0, w.Count)
.ToDictionary(
idx => _instruments[idx],
idx => w[idx])
};
yield return pf;
}
yield break;
}
#endregion
#region public Portfolio MaximumSharpeRatio()
/// <summary>
/// Return portfolio w/ maximum sharpe ratio.
/// </summary>
/// <returns>portfolio</returns>
public Portfolio MaximumSharpeRatio()
{
var p = _cla.GetMaxSR();
var pf = new Portfolio
{
Return = _cla.CalcReturn(p.Item2),
Risk = _cla.CalcVolatility(p.Item2),
//Sharpe = p.Item1,
Weights = Enumerable.Range(0, p.Item2.Count)
.ToDictionary(
idx => _instruments[idx],
idx => p.Item2[idx])
};