-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdoc_pyPortfolioAnalysis.txt
2295 lines (1932 loc) · 87.8 KB
/
doc_pyPortfolioAnalysis.txt
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
Help on module pyPortfolioAnalysis:
NAME
pyPortfolioAnalysis
DESCRIPTION
pyPortfolioAnalysis: Methods to optimize portfolio
==================================================
Documentation is available as docstring or as HTML on https://github.com/anuragagrawaal/pyPortfolioAnalysis
Functions and Classes
Optimization Methods
====================
'HHI'
'VaR'
'VaR_portfolio'
'add_constraint'
'add_objective'
'black_litterman'
'box_constraint'
'cVaR_portfolio'
'constrained_objective'
'diversification'
'diversification_constraint'
'equal_weight'
'extract_groups'
'extract_objective_measure'
'extract_weights'
'factor_exposure_constraint'
'fn_map'
'generate_sequence'
'get_constraints'
'group_constraint'
'group_fail'
'inverse_volatility_weights'
'leverage_exposure_constraint'
'leverage_fail'
'max_sum_fail'
'min_sum_fail'
'minmax_objective'
'normalize_weights'
'optimize_portfolio'
'performance_metrics_objective
'port_mean'
'portfolio_risk_objective'
'portfolio_spec'
'pos_limit_fail'
'position_limit_constraint'
'return_constraint'
'return_objective'
'risk_budget_objective'
'rp_decrease'
'rp_decrease_leverage'
'rp_increase'
'rp_position_limit'
'rp_transform'
'transaction_cost_constraint'
'turnover'
'turnover_constraint'
'turnover_objective'
'var_portfolio'
'weight_concentration_objective'
'weight_sum_constraint'
Plots
=====
'chart_efficient_frontier'
'chart_group_weights'
'chart_weights'
References
----------
Brian G. Peterson and Peter Carl (2018). PortfolioAnalytics: Portfolio Analysis, Including Numerical Methods for Optimization of Portfolios. R package version 1.1.0. https://CRAN.R-project.org/package=PortfolioAnalytics
Boudt, Kris and Lu, Wanbo and Peeters, Benedict, Higher Order Comoments of Multifactor Models and Asset Allocation (June 16, 2014). Available at SSRN: http://ssrn.com/abstract=2409603 or http://dx.doi.org/10.2139/ssrn.2409603
Chriss, Neil A and Almgren, Robert, Portfolios from Sorts (April 27, 2005). Available at SSRN: http://ssrn.com/abstract=720041 or http://dx.doi.org/10.2139/ssrn.720041
Meucci, Attilio, The Black-Litterman Approach: Original Model and Extensions (August 1, 2008). Shorter version in, THE ENCYCLOPEDIA OF QUANTITATIVE FINANCE, Wiley, 2010. Avail- able at SSRN: http://ssrn.com/abstract=1117574 or http://dx.doi.org/10.2139/ssrn.1117574
Meucci, Attilio, Fully Flexible Views: Theory and Practice (August 8, 2008). Fully Flexible Views: Theory and Practice, Risk, Vol. 21, No. 10, pp. 97-102, October 2008. Available at SSRN: http://ssrn.com/abstract=1213325
Scherer, Bernd and Martin, Doug, Modern Portfolio Optimization. Springer. 2005.
Shaw, William Thornton, Portfolio Optimization for VAR, CVaR, Omega and Utility with General Return Distributions: A Monte Carlo Approach for Long-Only and Bounded Short Portfolios with Optional Robustness and a Simplified Approach to Covariance Matching (June 1, 2011). Available at SSRN: http://ssrn.com/abstract=1856476 or http://dx.doi.org/10.2139/ssrn.1856476
CLASSES
black_litterman
portfolio_spec
class black_litterman
| A class to call black_litterman object.
|
| Black-litterman formula is popular to get posterior moments of the portfolio.
|
| ...
|
| Attributes
| ----------
| R : pandas.DataFrame
| dataframe of returns series.
| P : matrix-like,
| KXN link matrix where N is the number of assets and K are the views
|
| Methods
| -------
| fit(Mu = None, S = None, Views = None, tau = 1):
| returns a matrix of posterior returns based on Views and returns data.
|
| Methods defined here:
|
| __init__(self, R, P)
| Constructor for all necessary attributes of class black_litterman
|
| ...
|
| Attributes
| ----------
| R : pandas.DataFrame
| dataframe of returns series.
| P : matrix-like,
| KXN link matrix where N is the number of assets and K are the views
|
| fit(self, Mu=None, S=None, Views=None, tau=1)
| fit method of black_litterman object
|
| Main function to call in order to return the posterior mean of the portfolio given the views and return.
|
| Parameters
| ----------
| Mu : array-like, optional
| prior mean of the returns. numpy.mean is called if Mu is None
| S : matrix-like, optional
| NXN covariance matrix. numpy.cov is called if S is None
| Views: array-like, default = None
| array of K views held by investor.
| Tau: float, default = 1
| multiplying factor to be used.
|
| Returns
| -------
| array:
| returns an array of posterior moments of portfolio given the returns and weights
|
| See Also
| --------
| portfolio_spec
| optimize_portfolio
|
| Notes
| -----
|
| Black-litterman formula is very useful if an investor believes that a particular stock is going to rise
| compared to others although this information is not incorporated in the stock price. Essentially, it captures
| the views an investor holds for a particular asset.
|
| Examples
| --------
| >>> import pandas_datareader as pdr
| >>> aapl = pdr.get_data_yahoo('AAPL')
| >>> msft = pdr.get_data_yahoo('MSFT')
| >>> tsla = pdr.get_data_yahoo('TSLA')
| >>> port = pd.DataFrame({'aapl': pd.DataFrame.reset_index(aapl).iloc[:,6], 'msft':pd.DataFrame.reset_index(msft).iloc[:,6],
| 'tsla': pd.DataFrame.reset_index(tsla).iloc[:,6]})
| >>> port_ret = port.pct_change().dropna()
| >>> P = np.matrix([[-1, 0, 1],[0,-1,1]])
| >>> Views = np.matrix([[0.02],
| [0.05]])
| >>> bl = black_litterman(R = port_ret, P = P)
| >>> bl.fit(Views = Views)
class portfolio_spec
| A class to call portfolio_spec object.
|
| portfolio_spec object is the main class that contains all the constraints, objectives, optimal weights;
| it is called by many functions to get relevant attributes and store attributes.
|
| ...
|
| Attributes
| ----------
|
| assets : int, or array-like,
| add assets to portfolio either via name of assets in the form of an array or int of number of assets.
| category_label: dict, optional
| dictionary of different categories assigned to different assets. similar to group_constraint.
| See group_constraint.
| weights_seq : sequence, optional
| sequence of random weights. These weights will be used to optimize weights. See generate_sequence
| message : bool, default = False
| bool to enable or diable message
|
| Methods
| -------
| port_summary():
| returns a dictionary of the summary of constraints and objective added by add_consraint and add_objective
| funtions. See add_constraint, add_objective
| optimal_portfolio():
| returns a dictionary of optimal weights, objective measure and minimum value calculated by the specified solver
| NOTE: optimal_portfolio will only return result if optimize_portfolio is called. See optimize_portfolio
|
| Methods defined here:
|
| __init__(self, assets, category_labels=None, weights_seq=None, message=False)
| Constructor for all necessary attributes of class black_litterman
|
| ...
|
| Attributes
| ----------
|
| assets : int, or array-like,
| add assets to portfolio either via name of assets in the form of an array or int of number of assets.
| category_label: dict, optional
| dictionary of different categories assigned to different assets. similar to group_constraint.
| See group_constraint.
| weights_seq : sequence, optional
| sequence of random weights. These weights will be used to optimize weights. See generate_sequence
| message : bool, default = False
| bool to enable or diable message
|
| optimal_portfolio(self)
| summary of the portfolio
|
| method to provide a summary of the optimal weights, objective and minimum output of portfolio.
|
| Returns
| -------
| dict:
| returns a dictionary of optimal weights, objective and minimum output of portfolio
|
| See Also
| --------
| portfolio_spec
| optimize_portfolio
|
| Examples
| --------
| >>> import pandas_datareader as pdr
| >>> aapl = pdr.get_data_yahoo('AAPL')
| >>> msft = pdr.get_data_yahoo('MSFT')
| >>> tsla = pdr.get_data_yahoo('TSLA')
| >>> uber = pdr.get_data_yahoo('UBER')
| >>> amzn = pdr.get_data_yahoo('AMZN')
| >>> port = pd.DataFrame({'aapl': pd.DataFrame.reset_index(aapl).iloc[:,6], 'msft':pd.DataFrame.reset_index(msft).iloc[:,6],
| 'tsla': pd.DataFrame.reset_index(tsla).iloc[:,6], 'uber':pd.DataFrame.reset_index(uber).iloc[:,6],
| 'amzn': pd.DataFrame.reset_index(amzn).iloc[:,6]})
| >>> port_ret = port.pct_change().dropna()
| >>> R = port_ret
| >>> p1 = portfolio_spec(assets = 3)
| >>> add_constraint(portfolio = p1, kind = 'factor_exposure', B = [0.2,0.2,0.4], lower = 1.0, upper = 0.9)
| >>> add_constraint(portfolio = p1, kind = 'group', groups = dict(zip(['equity','debt'],[[0,1], [2]])), group_min = 0.2, group_max = 0.5)
| >>> add_constraint(portfolio = p1, kind = 'transaction', ptc = 0.2)
| >>> add_objective(portfolio = p1, kind = 'return', target = 0.1, name = 'return_obj')
| >>> add_objective(portfolio = p1, kind = 'minmax', minimum = 0.2, maximum = 0.3,name = 'risk')
| >>> optimize_portfolio(R, p1, optimize_method = 'DEoptim')
| >>> p1.optimal_weights()
|
| port_summary(self)
| summary of the portfolio
|
| method to provide a summary of the portfolio.
|
| Returns
| -------
| dict:
| returns a dictionary of all constraints and objective
|
| See Also
| --------
| portfolio_spec
| optimize_portfolio
|
| Examples
| --------
| >>> import pandas_datareader as pdr
| >>> aapl = pdr.get_data_yahoo('AAPL')
| >>> msft = pdr.get_data_yahoo('MSFT')
| >>> tsla = pdr.get_data_yahoo('TSLA')
| >>> uber = pdr.get_data_yahoo('UBER')
| >>> amzn = pdr.get_data_yahoo('AMZN')
| >>> port = pd.DataFrame({'aapl': pd.DataFrame.reset_index(aapl).iloc[:,6], 'msft':pd.DataFrame.reset_index(msft).iloc[:,6],
| 'tsla': pd.DataFrame.reset_index(tsla).iloc[:,6], 'uber':pd.DataFrame.reset_index(uber).iloc[:,6],
| 'amzn': pd.DataFrame.reset_index(amzn).iloc[:,6]})
| >>> port_ret = port.pct_change().dropna()
| >>> R = port_ret
| >>> p1 = portfolio_spec(assets = 3)
| >>> add_constraint(portfolio = p1, kind = 'factor_exposure', B = [0.2,0.2,0.4], lower = 1.0, upper = 0.9)
| >>> add_constraint(portfolio = p1, kind = 'group', groups = dict(zip(['equity','debt'],[[0,1], [2]])), group_min = 0.2, group_max = 0.5)
| >>> add_constraint(portfolio = p1, kind = 'transaction', ptc = 0.2)
| >>> add_objective(portfolio = p1, kind = 'return', target = 0.1, name = 'return_obj')
| >>> add_objective(portfolio = p1, kind = 'minmax', minimum = 0.2, maximum = 0.3,name = 'risk')
| >>> p1.port_summary()
FUNCTIONS
HHI(weights, groups=None)
The Herfindahl Hirschman Index measures the concentration of weights using this function.
Concentration of weights
Parameters
----------
weights : array-like,
collection of weights of the portfolio.
groups : dict,
dictionary of groups.
Returns
-------
returns the weight concentration given the weights
See Also
--------
port_mean
var_portfolio
VaR
cVaR
Examples
--------
>>> # calculate HHI
>>> w = [0.2,0.3,-0.1,0.6,0.8]
>>> HHI(w)
VaR(R, p=0.05)
Calculate the value at risk (VaR)
This function calculates the value at risk (VaR) assuming gaussian distribution
Parameters
----------
R : pd.DataFrame object,
returns dataframe
p : float, optional
quantile estimate
Returns
-------
Calculates the VaR given returns
See Also
--------
cVaR
VaR_portfolio
Examples
--------
>>> VaR(R,p = 0.01)
VaR_portfolio(w, R, p=0.05, mean=True)
calculate the value at risk (VaR) of a portfolio
This function calculates the value at risk (VaR) assuming gaussian distribution
Parameters
----------
w : array-like,
list of weights of portfolio
R : pd.DataFrame object,
returns dataframe
p : float, optional
quantile estimate
mean : bool, default = True
mean VaR of portfolio
Returns
-------
Calculates the VaR given portfolio weights
See Also
--------
cVaR
VaR_portfolio
VaR
Examples
--------
>>> w = [0.2,0.3,0.5]
>>> VaR_portfolio(w,R,p = 0.01)
add_constraint(portfolio, kind, enabled=True, **kwargs)
Add a constraint in portfolio_spec object
Main function to add or update constraint in portfolio_spec object
Parameters
----------
portfolio : portfolio_spec,
an object of class portfolio_spec. see portfolio_spec
kind : str,
currently supported constraint: ’weight_sum’ (also ’leverage’ or ’weight’), ’box’, ’group’,
’turnover’,’diversification’, ’position_limit’, ’return’, ’factor_exposure’,
or ’leverage_exposure’.
enabled : bool, default = True
bool to enable or disable constraints.
kwargs : additional key word arguments, optional
any additional constraint argument to be passed.
Returns
-------
Adds constraints to object portfolio_spec of the specified input.
See Also
--------
add_constraints
box_constraints
group_constraints
weight_sum_constraint
turnover_constraint
diversification_constraint
position_limit_constraint
return_constraint
factor_exposure_constraint
transaction_cost_constraint
leverage_exposure_constraint
Notes
-----
•weight_sum, weight, leverage Specify constraint on the sum of the weights, see weight_sum_constraint
•full_investment Special case to set min_sum=1 and max_sum=1 of weight sum constraints
•dollar_neutral, active Special case to set min_sum=0 and max_sum=0 of weight_sum constraints
•box box constraint for the individual asset weights, see box_constraint
•long_only Special case to set min=0 and max=1 of box constraint
•group specify the sum of weights within groups and the number of assets with non-zero weights in groups,
see group_constraint
•turnover Specify a constraint for target turnover. Turnover is calculated from a set of initial weights,
see turnover_constraint
•diversification target diversification of asset of weights, see diversification_constraint
•position_limit Specify the number of non-zero,long, and/orshortpositions, see position_limit_constraint
•return Specify the target mean return, see return_constraint
•factor_exposure Specify risk factor exposures, see factor_exposure_constraint
•leverage_exposure Specify a maximum leverage exposure, see leverage_exposure_constraint
Examples
--------
>>> portfolio = portfolio_spec(assets = 4)
>>> # adding weight_sum cinstraint
>>> add_constraint(portfolio, kind = 'weight_sum', min_sum = 0.9, max_sum = .95)
>>> # long_only is a special kind of box constraint where minimum and maximum is positive
>>> # minimum and maximum can be list or scalars
>>> add_constraint(portfolio, kind = 'box', minimum = [0.9, -0.5,-0.5, 0.1], maximum = 1)
>>> add_constraint(portfolio, kind = 'long_only')
>>> # group constraint is used to specify min and max weights of certain asset_groups
>>> # groups must be a dict and group_min and group_max can be scalar or list
>>> add_constraint(portfolio, kind = 'group', group_min = [0.9, -0.5,-0.5, 0.1], group_max = 1,
groups = {'eqity':[0,3], 'debt':[1,2]})
>>> # adding weight_sum constraint
>>> add_constraint(portfolio, kind = 'weight_sum', min_sum = 0.9, max_sum = .95)
>>> # special case of weight_sum is dollar_neutral/active or full_investment
>>> add_constraint(portfolio, kind = 'dollar_neutral')
>>> add_constraint(portfolio, kind = 'full_investment')
>>> #turnover constraint
>>> add_constraint(portfolio, kind = 'turnover', turnover_target = 0.1)
>>> #diversification constraint for diversification target in a portfolio
>>> add_constraint(portfolio, kind = 'diversification', div_target = 0.1)
>>> #position_limit is a constraint to restrict max position and also max long/short positions
>>> add_constraint(portfolio, kind = 'position_limit', max_pos = 3, max_pos_long = 2, max_pos_short = 2)
>>> #return constraint to add a target mean historical return to the portfolio
>>> add_constraint(portfolio, kind = 'return', return_target = 0.0018)
>>> #adds a tranaction cost constraint on portfolio
>>> add_constraint(portfolio, kind = 'transaction_cost', ptc = 0.1)
>>> #constraint on the leverage of portfolio
>>> add_constraint(portfolio, kind = 'leverage_exposure', leverage = 0.8)
>>> #Factor_exposure constraint is used to test portfolio with their impact on certaint factors
>>> # factors can be single or multiple with lower and upper limit.
>>> # B can be a N*K matrix for N assets and K factors.
>>> # lower and upper arguments can be float for single factor and list for multiple factors
>>> add_constraint(portfolio, kind = 'factor_exposure',
B = np.matrix([[1.2,1.3],
[2.3,1.4],
[1.4,0.9],
[3.4,1.2]]),
lower = [0.8,1.4], upper = [2,2.4])
add_objective(portfolio, kind, name, arguments=None, constraints=None, enabled=True, message=True, **kwargs)
This function is the primary function of adding and updating business goals in a portfolio.spec type object.
General interface, including risk, return, and risk budget, to add optimization goals.
Parameters
----------
portfolio : portfolio_spec,
an object of class portfolio_spec.
kind : str,
the character form of the goal to be added or changed, currently 'return',' risk',
‘risk_budget',' quadratic_utility’, or ‘weight_concentration’.
name : str,
The target name should correspond to a feature, although we will attempt to make allowances
arguments : Default arguments to be transferred when executed on an objective function.
enabled : bool, default = True
bool to enable or disable constraints.
message : bool, default = True
bool to enable or disable messages.
kwargs : additional key word arguments, optional
any additional constraint argument to be passed.
Returns
-------
Adds objective to object portfolio_spec of the specified input.
See Also
--------
add_objectives
portfolio_risk_objectives
risk_budget_objective
turnover_objective
minmax_objective
weight_constraint_objective
Notes
-----
In general, you will define your objective as one of the following types:
’return’, ’risk’, ’risk_budget’, or ’weight_concentration’.
These have special handling and intelligent defaults for dealing with the function
most likely to be used as objectives, including mean, median, VaR, ES, etc.
Objectives of type ’turnover’ and ’minmax’ are also supported.
Examples
--------
>>> port = portfolio_spec(assets = 5)
>>> import pandas_datareader as pdr
>>> aapl = pdr.get_data_yahoo('AAPL')
>>> msft = pdr.get_data_yahoo('MSFT')
>>> tsla = pdr.get_data_yahoo('TSLA')
>>> uber = pdr.get_data_yahoo('UBER')
>>> amzn = pdr.get_data_yahoo('AMZN')
>>> port = pd.DataFrame({'aapl': pd.DataFrame.reset_index(aapl).iloc[:,6], 'msft':pd.DataFrame.reset_index(msft).iloc[:,6],
'tsla': pd.DataFrame.reset_index(tsla).iloc[:,6], 'uber':pd.DataFrame.reset_index(uber).iloc[:,6],
'amzn': pd.DataFrame.reset_index(amzn).iloc[:,6]})
>>> port_ret = port.pct_change().dropna()
>>> R = port_ret
>>> add_constraint('long_only')
>>> add_constraint('full_investment')
>>> #adding objectives
>>> add_objective(kind = 'return', name = 'mean', target = 0.0018)
>>> add_objective(kind = 'portfolio_risk', name = 'std', target = 0.015)
>>> add_objective(kind = 'risk_budget', name = 'risk_budget')
>>> add_objective(kind = 'weight_conc', name = 'HHI', target = 0.11)
>>> add_objective(kind = 'performance_metrics', name = 'sharpe', target = 0.13)
>>> # add a custom objective by first defining it.
>>> def sortino_ratio(w,R):
#SOME CODE
>>> add_objective(kind = 'performance_metrics', name = {'sortino':sortino_ratio}, target = 0.35)
NOTE: The output of sortino_ratio or other custom function in objective must be a float.
NOTE: you can also add other custom function in other kind of objective in similar methd.
box_constraint(assets, minimum, maximum, kind='box', enabled=True, message=True, **kwargs)
The box constraint defines the upper and lower limits of asset weights.
add_constraint calls this function when type=”box” is defined.
Parameters
----------
assets : int, or array-like,
number of assets, or optionally a named list of assets specifying initial weights.
minimum : float, or array-like,
numeric or named list defining the minimum constraints of the weight box.
maximum : float, or array-like,
numeric or named list defining the maximum constraints of the weight box.
kind : str,
string of kind of constraint.
enabled : bool, default = True
bool to enable or disable constraints.
message : bool, default = True
bool to enable or disable messages.
kwargs : additional key word arguments, optional
any additional constraint argument to be passed.
Returns
-------
Add box constraints to object portfolio_spec of the specified input.
See Also
--------
add_constraints
box_constraints
group_constraints
weight_sum_constraint
turnover_constraint
diversification_constraint
position_limit_constraint
return_constraint
factor_exposure_constraint
transaction_cost_constraint
leverage_exposure_constraint
Examples
--------
>>> add_constraint(portfolio, kind = 'box', minimum = [0.9, -0.5,-0.5, 0.1], maximum = 1)
cVaR_portfolio(w, R, p=0.05, mean=True)
Calculate the conditional value at risk (cVaR) of a portfolio
This function calculates the conditional value at risk (cVaR) assuming gaussian distribution
Parameters
----------
w : array-like,
list of weights of portfolio
R : pd.DataFrame object,
returns dataframe
p : float, optional
quantile estimate
mean : bool, default = True
mean VaR of portfolio
Returns
-------
Calculates the VaR given portfolio weights
See Also
--------
cVaR
VaR_portfolio
VaR
Examples
--------
>>> w = [0.2,0.3,0.5]
>>> cVaR_portfolio(w,R,p = 0.01)
chart_efficient_frontier(portfolio, R, metric='Sharpe Ratio', arguments={'rf': 0.0}, cml=False, rand_pf=300, optimize_method='DEoptim', alpha=0.4, figsize=(10, 6), **kwargs)
Function to plot efficient frontier of portfolio.
Parameters
----------
portfolio : portfolio_spec,
an object of class portfolio_spec.
R : pandas dataframe,
dataframe of the returns series
metric: str, default = 'Sharpe Ratio'
metric should be either of 'Sharpe Ratio' or 'Treynor Ratio'
arguments : dict, optional
additional arguments such as risk-free rate in the form of a dictionary.
cml : bool, default = False
bool to enable or disable capital market line
rand_pf : int, optional
random portfolio to plot to show the efficient frontier
optimize_method : str, optional
optimize_method should be similar to those in optimize_portfolio. see optimize_portfolio
alpha : float, optional
transparency
figsize : tuple, optional
figure size in the form of a tuple
kwargs : additional key word arguments, optional
any additional constraint argument to be passed.
Returns
-------
matplotlib.scatter
See Also
--------
chart_group_weights
chart_weights
chart_efficient_frontier
Examples
--------
>>> # Rb is S&P500 benchmark for capital market line and beta for treynor ratio
>>> chart_efficient_froniter(portfolio, R, metric = 'Treynor Ratio',
arguments = {'rf': 0.0008, 'Rb':Rb}, cml = True, alpha = 0.1, rand_pf = 1000, optimize_method = 'pso')
chart_group_weights(portfolio)
Function to plot individual group weights of optimal weights.
Parameters
----------
portfolio : portfolio_spec,
an object of class portfolio_spec.
Returns
-------
matplotlib.lines.Line2D
See Also
--------
chart_group_weights
chart_efficient_frontier
Examples
--------
>>> chart_group_weights(portfolio)
NOTE: chart_group_weights will only work after call optimize_portfolio on portfolio_spec
chart_weights(portfolio)
Function to plot weights of optimal weights.
Parameters
----------
portfolio : portfolio_spec,
an object of class portfolio_spec.
Returns
-------
matplotlib.lines.Line2D
See Also
--------
chart_group_weights
chart_efficient_frontier
Examples
--------
>>> chart_weights(portfolio)
NOTE: chart_group_weights will only work after call optimize_portfolio on portfolio_spec
constrained_objective(w, R, portfolio, trace=False, normalize=False, storage=False, verbose=False, penalty=10000, *kwargs, **args)
Add a constraint in portfolio_spec object
Main function to add or update constraint in portfolio_spec object
Parameters
----------
w : array-like,
weights to test
R : pd.DataFrame,
dataframe of returns of assets in portfolio
trace : bool, default = False
bool to enable or disable constraints.
normalize : bool, default = False
bool to specify if weights should be normalized first. see normalize_weights.
verbose : bool, default = False
bool to enable or disable verbose argument.
penalty : int, optional
int value specifying he penalty if constraint or objective is breached.
kwargs : additional key word arguments, optional
any additional constraint argument to be passed.
kwargs : additional arguments, optional
any additional argument to be passed.
Returns
-------
returns a float of total penalty given a weight. if trace = True, additional objective measure will be returned
in the form of dictionary.
See Also
--------
rp_transform
optimize_portfolio
Notes
-----
constrained_objective is the main function that is called by
optimize_weights to optimze the constraint and objectives provided by the portfolio.
Loosely speaking, constrained_objective is very similar to an information criteria.
diversification(weights)
Diversification is stated as 1 minus the total of the squared weights
Diversification function to compute as a constraint
Parameters
----------
weights : array-like,
list of weights of assets.
Returns
-------
returns diversification given the weights
See Also
--------
turnover
Examples
--------
>>> w = [0.2,0.3,0.5]
>>> turnover(w)
diversification_constraint(assets, div_target, kind='diversification', enabled=True, message=True)
Target diversification value is specified under the diversification constraint.
This function is called by add.constraint when type=”diversification” is mentioned.
Parameters
----------
assets : Int, or array-like,
Number of assets or, as an alternative, a named asset list specifying initial weights.
div_target : float,
diversification target value
kind : str,
string of the kind of constraint.
enabled : bool, default = True
bool to enable or disable constraints.
message : bool, default = True
bool to enable or disable messages.
Returns
-------
Adds diversification constraints to object portfolio_spec of the specified input.
See Also
--------
add_constraints
box_constraints
group_constraints
weight_sum_constraint
turnover_constraint
diversification_constraint
position_limit_constraint
return_constraint
factor_exposure_constraint
transaction_cost_constraint
leverage_exposure_constraint
Examples
--------
>>> #diversification constraint for diversification target in a portfolio
>>> add_constraint(portfolio, kind = 'diversification', div_target = 0.1)
equal_weight(R, portfoio, **kwargs)
Function to extract objective measures of equal weight portfolio.
Parameters
----------
R : pd.DataFrame,
dataframe of returns of assets in portfolio
portfolio : portfolio_spec,
an object of class portfolio_spec.
kwargs : additional arguments, optional
any additional argument to be passed.
Returns
-------
dictionary of objective measures of equal weighted portfolio
See Also
--------
inverse_volatility_weights
Examples
--------
>>> equal_weight(R, portfolio)
extract_groups(portfolio)
Function to extract groups from portfolio_spec object.
Parameters
----------
portfolio : portfolio_spec,
an object of class portfolio_spec.
Returns
-------
dictionary of groups if group_constraint is specified.
See Also
--------
extract_weights
extract_objective_measure
extract_groups
Examples
--------
>>> extract_groups(portfolio)
NOTE: extract_groups will only work after calling optimize_portfolio on portfolio_spec
extract_objective_measure(R, portfolio, **kwargs)
Function to extract objective measures of optimal weights.
Parameters
----------
R : pd.DataFrame,
dataframe of returns of assets in portfolio
portfolio : portfolio_spec,
an object of class portfolio_spec.
kwargs : additional arguments, optional
any additional argument to be passed.
Returns
-------
dictionary of objective measures as specified in the portfolio_spec object
See Also
--------
extract_weights
extract_objective_measure
extract_groups
Examples
--------
>>> extract_objective_measure(R, portfolio)
NOTE: extract_objective_measure will only work after calling optimize_portfolio on portfolio_spec
extract_weights(portfolio)
Function to extract optimal weights.
Parameters
----------
portfolio : portfolio_spec,
an object of class portfolio_spec.
Returns
-------
array of optimal weights
See Also
--------
extract_objective_measure
extract_groups
Examples
--------
>>> extract_weights(portfolio)
NOTE: extract_weights will only work after calling optimize_portfolio on portfolio_spec
factor_exposure_constraint(assets, B, lower, upper, kind='factor_exposure', enabled=True, message=False)
Add a factor exposure constraint for "K" different factos in a portdolio and also their exposure to
particular asset.
Parameters
----------
assets : int, or array-like,
named list of assets specifying initial weights.
B : matrix-like,
matrix or list of risk factor exposures
lower : int, or array-like
list of lower limits of risk factor exposure constraints.
upper : int, or array-like
list of upper limits of risk factor exposure constraints.
kind : str,
string of kind of constraints.
enabled : bool, default = True
bool to enable or disable constraints.
message : bool, default = False
bool to enable or disable messages.
Returns
-------
Adds factor_exposure constraints to object portfolio_spec of the specified input.
See Also
--------
add_constraints
box_constraints
group_constraints
weight_sum_constraint
turnover_constraint
diversification_constraint
position_limit_constraint
return_constraint
factor_exposure_constraint
transaction_cost_constraint
leverage_exposure_constraint
Examples
--------
>>> #Factor_exposure constraint is used to test portfolio with their impact on certaint factors
>>> # factors can be single or multiple with lower and upper limit.
>>> # B can be a N*K matrix for N assets and K factors.
>>> # lower and upper arguments can be float for single factor and list for multiple factors
>>> add_constraint(portfolio, kind = 'factor_exposure',
B = np.matrix([[1.2,1.3],
[2.3,1.4],
[1.4,0.9],
[3.4,1.2]]),
lower = [0.8,1.4], upper = [2,2.4])
fn_map(weights, portfolio, relax=False, verbose=False)
This function transforms list of weights that does not meet the portfolio constraints to an array that meets
the constraints. relax argument (default = False) if True gives the function permission to transform weights
if needed
Parameters
----------