-
Notifications
You must be signed in to change notification settings - Fork 225
/
policies.py
948 lines (784 loc) · 38 KB
/
policies.py
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
# Copyright 2016 Enzo Busseti, Stephen Boyd, Steven Diamond, BlackRock Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module contains trading policies that can be back-tested."""
import copy
import logging
import warnings
import cvxpy as cp
import numpy as np
import pandas as pd
from .errors import (ConvexityError, ConvexSpecificationError, DataError,
MissingTimesError, PortfolioOptimizationError)
from .estimator import DataEstimator, Estimator
from .forecast import HistoricalMeanVolume
from .returns import CashReturn
from .utils import flatten_heterogeneous_list
__all__ = [
"AllCash",
"Hold",
"SellAll",
"FixedTrades",
"PeriodicRebalance",
"ProportionalRebalance",
"AdaptiveRebalance",
"SinglePeriodOptimization",
"MultiPeriodOptimization",
"MarketBenchmark",
"ProportionalTradeToTargets",
"RankAndLongShort",
"FixedWeights",
"Uniform",
"SinglePeriodOpt",
"MultiPeriodOpt",
]
logger = logging.getLogger(__name__)
class Policy(Estimator):
"""Base trading policy class, defines execute method."""
def execute(self, h, market_data, t=None):
"""Execute trading policy at current or user-specified time.
Return the (*e.g.*, dollar) trade vector :math:`u`, the timestamp
of execution (for double check in case you don't pass it), and a Pandas
Series of the number of shares to trade, if you pass a Market
Data server which provides open prices (or None).
:param h: Holdings vector, in dollars, including the cash account
(the last element).
:type h: pandas.Series
:param market_data: :class:`MarketData` instance used to provide
data to the policy
:type market_data: cvxportfolio.MarketData instance
:param t: Time at which we execute. If None (the default), the
last timestamp in the trading calendar provided by the
:class:`MarketData` instance is used. Note: if you use a default
market data server, you probably want to set their ``online_usage``
argument to ``True``.
:type t: pandas.Timestamp or None
:raises cvxportfolio.errors.DataError: Holdings vector sum to a
negative value or don't match the market data server's universe.
:returns: u, t, shares_traded
:rtype: pandas.Series, pandas.Timestamp, pandas.Series
"""
trading_calendar = market_data.trading_calendar()
if t is None:
t = trading_calendar[-1]
if not t in trading_calendar:
raise ValueError(f'Provided time {t} must be in the '
+ 'trading calendar implied by the market data server.')
v = np.sum(h)
if v < 0.:
raise DataError(
f"Holdings provided to {self.__class__.__name__}.execute "
+ " have negative sum.")
past_returns, _, past_volumes, _, current_prices = market_data.serve(t)
if sorted(h.index) != sorted(past_returns.columns):
raise DataError(
"Holdings provided don't match the universe"
" implied by the market data server.")
h = h[past_returns.columns]
w = h / v
# consider adding caching logic here
self.initialize_estimator_recursive(
universe=past_returns.columns,
trading_calendar=trading_calendar[trading_calendar >= t])
w_plus = self.values_in_time_recursive(
t=t, past_returns=past_returns, past_volumes=past_volumes,
current_weights=w, current_portfolio_value=v,
current_prices=current_prices)
# this could be optional, currently unused)
self.finalize_estimator_recursive()
z = w_plus - w
u = z * v
if current_prices is not None:
shares_traded = pd.Series(np.round(u.iloc[:-1] / current_prices),
dtype=int)
else:
shares_traded = None
return u, t, shares_traded
class Hold(Policy):
"""Hold initial portfolio, don't trade."""
def values_in_time( # pylint: disable=arguments-differ
self, current_weights, **kwargs):
"""Return current_weights.
:param current_weights: Current weights.
:type current_weights: pandas.Series
:param kwargs: Unused arguments to :meth:`values_in_time`.
:type kwargs: dict
:returns: Same current weights.
:rtype: pandas.Series
"""
return current_weights
class AllCash(Policy):
"""Allocate all weight to cash.
This is the default benchmark used in :class:`SinglePeriodOptimization` and
:class:`MultiPeriodOptimization` policies.
"""
def values_in_time( # pylint: disable=arguments-differ
self, past_returns, **kwargs):
"""Return all cash weights.
:param past_returns: Past market returns (used to infer universe).
:type past_returns: pandas.DataFrame
:param kwargs: Unused arguments to :meth:`values_in_time`.
:type kwargs: dict
:returns: All cash weights.
:rtype: pandas.Series
"""
result = pd.Series(0., past_returns.columns)
result.iloc[-1] = 1.
return result
class MarketBenchmark(Policy):
"""Allocation weighted by average market traded volumes.
This policy provides an approximation of a market capitalization-weighted
allocation, by using the average of traded volumes in units of value (e.g.,
USDOLLAR) over the previous year (by default, can be changed) as proxy.
.. versionadded:: 1.2.0
We added the ``mean_volume_forecast`` parameter.
:param mean_volume_forecast: Forecaster class that computes the average
of historical volumes. You can also pass a DataFrame containing
your own forecasts computed externally. Default is
:class:`cvxportfolio.forecast.HistoricalMeanVolume` which is
instantiated with parameter ``rolling=pd.Timedelta('365.24d')``
(that's one solar year in number of days). If you
want to provide a different forecaster, or change the parameters (like
adding exponential smoothing) you should instantiate the forecaster
class and pass the instance.
:type mean_volume_forecast: pandas.DataFrame, cvx.forecast.BaseForecast
class or instance
"""
def __init__(self, mean_volume_forecast=HistoricalMeanVolume):
if isinstance(mean_volume_forecast, type):
mean_volume_forecast = mean_volume_forecast(
rolling=pd.Timedelta('365.24d'))
self.mean_volume_forecast = DataEstimator(
mean_volume_forecast, data_includes_cash=False)
def values_in_time( # pylint: disable=arguments-differ
self, past_returns, **kwargs):
"""Return market benchmark weights.
:param past_returns: Past market returns (used to infer universe with
cash).
:type past_returns: pandas.DataFrame
:param kwargs: Unused arguments to :meth:`values_in_time`.
:type kwargs: dict
:raises cvxportfolio.errors.DataError: Market data does not include
market volumes.
:returns: Market benchmark weights.
:rtype: pandas.Series
"""
meanvolumes = self.mean_volume_forecast.current_value
result = np.zeros(len(meanvolumes) + 1)
result[:-1] = meanvolumes / sum(meanvolumes)
return pd.Series(result, index=past_returns.columns)
class RankAndLongShort(Policy):
"""Rank assets by signal; long highest and short lowest.
:param signal: time-indexed DataFrame of signal for all symbols
excluding cash. At each point in time the num_long assets with
highest signal will have equal positive weight, and the
num_short assets with lower signal will have equal negative
weight. If two or more assets have the same signal value and
they are on the boundary of either the top or bottom set,
alphanumerical ranking will prevail.
:type signal: pd.DataFrame
:param num_long: number of assets to long, default 1; if specified
as Series it must be indexed by time.
:type num_long: int or pd.Series
:param num_short: Number of assets to short, default 1; if specified
as Series it must be indexed by time.
:type num_short: int or pd.Series)
:param target_leverage: leverage of the resulting portfolio, default
1; if specified as Series it must be indexed by time.
:type target_leverage: float or pd.Series
"""
def __init__(self, signal, num_long=1, num_short=1, target_leverage=1.):
"""Define sub-estimators at class attribute level."""
self.num_long = DataEstimator(num_long)
self.num_short = DataEstimator(num_short)
self.signal = DataEstimator(signal)
self.target_leverage = DataEstimator(target_leverage)
def values_in_time( # pylint: disable=arguments-differ
self, current_weights, **kwargs):
"""Get allocation weights.
:param current_weights: Current allocation weights.
:type current_weights: pandas.Series
:param kwargs: Unused arguments to :meth:`values_in_time`.
:type kwargs: dict
:returns: Rank and long-short weights.
:rtype: pandas.Series
"""
sorted_ret = pd.Series(
self.signal.current_value, current_weights.index[:-1]
).sort_values()
short_positions = sorted_ret.index[: self.num_short.current_value]
long_positions = sorted_ret.index[-self.num_long.current_value:]
target_weights = pd.Series(0., index=current_weights.index)
target_weights[short_positions] = -1.
target_weights[long_positions] = 1.
target_weights /= sum(abs(target_weights))
target_weights *= self.target_leverage.current_value
# cash is always 1.
target_weights[current_weights.index[-1]] = 1.
return target_weights
class ProportionalTradeToTargets(Policy):
"""Trade in equal proportion to match target weights in time.
Initially, it loads the list of trading days and so at each day it
knows how many are missing before the next target's day, and trades
in equal proportions to reach those targets. If there are no targets
remaining it defaults to not trading.
:param targets: time-indexed DataFrame of target weight vectors at
given points in time (e.g., start of each month).
:type targets: pandas.DataFrame
"""
def __init__(self, targets):
assert isinstance(targets, pd.DataFrame)
assert isinstance(targets.index, pd.DatetimeIndex)
self.targets = targets
self.trading_days = None
def initialize_estimator( # pylint: disable=arguments-differ
self, trading_calendar, **kwargs):
"""Initialize policy instance with updated trading_calendar.
:param trading_calendar: Future (including current) trading calendar.
:type trading_calendar: pandas.DatetimeIndex
:param kwargs: Other unused arguments to :meth:`initialize_estimator`.
:type kwargs: dict
"""
self.trading_days = trading_calendar
def values_in_time( # pylint: disable=arguments-differ
self, t, current_weights, **kwargs):
"""Get current allocation weights.
:param t: Current time.
:type t: pandas.Timestamp
:param current_weights: Current allocation weights.
:type current_weights: pandas.Series
:param kwargs: Unused arguments to :meth:`values_in_time`.
:type kwargs: dict
:raises ValueError: Some target weights provided do not sum to 1.
:returns: Allocation weights.
:rtype: pandas.Series
"""
next_targets = self.targets.loc[self.targets.index >= t]
if not np.allclose(next_targets.sum(1), 1.):
raise ValueError(
f"The target weights provided to {self.__class__.__name__} at"
+ f" time {t} do not sum to 1.")
if len(next_targets) == 0:
return current_weights
next_target = next_targets.iloc[0]
next_target_day = next_targets.index[0]
trading_days_to_target = len(self.trading_days[(
self.trading_days >= t) & (self.trading_days < next_target_day)])
if trading_days_to_target == 0:
return current_weights
return current_weights + (
next_target - current_weights) / trading_days_to_target
class SellAll(AllCash):
"""Sell all assets to cash.
Alias of :class:`AllCash`.
"""
class FixedTrades(Policy):
"""Each day trade the provided *trade weights* vector.
If there are no weights defined for the given day, default to no
trades.
:param trades_weights: target trade weights :math:`z_t` to trade at each
period. If constant in time use a pandas Series indexed by the assets'
names, including the cash account name (``cash_key`` option to
:class:`MarketSimulator`). If varying in time, use a pandas DataFrame
with datetime index and as columns the assets names including cash.
If a certain time in the backtest is not present in the data provided
the policy defaults to not trading in that period.
:type trades_weights: pd.Series or pd.DataFrame
"""
def __init__(self, trades_weights):
"""Trade fixed trade weigths in time."""
self.trades_weights = DataEstimator(
trades_weights, data_includes_cash=True)
def values_in_time_recursive( # pylint: disable=arguments-differ
self, t, current_weights, **kwargs):
"""Get current allocation weights.
We redefine the recursive version of :meth:`values_in_time` because
we catch an exception thrown by a sub-estimator.
:param t: Current time.
:type t: pandas.Timestamp
:param current_weights: Current allocation weights.
:type current_weights: pandas.Series
:param kwargs: Unused arguments to :meth:`values_in_time`.
:type kwargs: dict
:returns: Allocation weights.
:rtype: pandas.Series
"""
try:
super().values_in_time_recursive(
t=t, current_weights=current_weights, **kwargs)
result = current_weights + pd.Series(
self.trades_weights.current_value, current_weights.index)
except MissingTimesError:
logger.info("%s didn't trade at time %s because it couldn't find"
+ " trade weights among the provided ones.",
self.__class__.__name__, t)
result = current_weights
self._current_value = result
return result
class FixedWeights(Policy):
"""Each day trade to the provided *weights* vector.
If there are no weights defined for the given day, default to no
trades.
:param target_weights: target weights :math:`w_t^+` to trade to at each
period. If constant in time use a pandas Series indexed by the assets'
names, including the cash account name (``cash_key`` option
to the simulator). If varying in time, use a pandas DataFrame
with datetime index and as columns the assets names including cash.
If a certain time in the backtest is not present in the data provided
the policy defaults to not trading in that period.
:type target_weights: pd.Series or pd.DataFrame
"""
def __init__(self, target_weights):
"""Trade the tradevec vector (dollars) or tradeweight weights."""
self.target_weights = DataEstimator(
target_weights, data_includes_cash=True)
def values_in_time_recursive( # pylint: disable=arguments-differ
self, t, current_weights, **kwargs):
"""Get current allocation weights.
We redefine the recursive version of :meth:`values_in_time` because
we catch an exception thrown by a sub-estimator.
:param t: Current time.
:type t: pandas.Timestamp
:param current_weights: Current allocation weights.
:type current_weights: pandas.Series
:param kwargs: Unused arguments to :meth:`values_in_time_recursive`.
:type kwargs: dict
:returns: Allocation weights.
:rtype: pandas.Series
"""
try:
super().values_in_time_recursive(
t=t, current_weights=current_weights, **kwargs)
result = current_weights + pd.Series(
self.target_weights.current_value, current_weights.index
) - current_weights
except MissingTimesError:
logger.info("%s didn't trade at time %s because it couldn't find"
+ " target weights among the provided ones.",
self.__class__.__name__, t)
result = current_weights
self._current_value = result
return result
class Uniform(FixedWeights):
"""Uniform allocation on non-cash assets.
:param leverage: Leverage of the allocation. Default is 1, corresponding to
the classic :math:`1/n` allocation.
:type leverage: float
"""
# pylint: disable=super-init-not-called
def __init__(self, leverage=1.):
self.leverage = leverage
# then we re-define the target weights for each universe in the method
# below, so we provide the same interface to the parent class'
# values_in_time_recursive
self.target_weights = None
def initialize_estimator( # pylint: disable=arguments-differ
self, universe, **kwargs):
"""Initialize this estimator.
:param universe: Trading universe, including cash.
:type universe: pandas.Index
:param kwargs: Other unused arguments to :meth:`initialize_estimator`.
:type kwargs: dict
"""
target_weights = pd.Series(1., universe)
target_weights.iloc[-1] = 0
target_weights /= sum(target_weights)
target_weights *= self.leverage
target_weights.iloc[-1] = 1. - target_weights.sum()
self.target_weights = DataEstimator(target_weights)
class PeriodicRebalance(FixedWeights):
"""Track a target weight vector rebalancing at given times.
This calls `FixedWeights`. If you want to change the target in time
use that policy directly.
:param target: Allocation weights to rebalance to.
:type target: pandas.Series
:param rebalancing_times: Times at which we rebalance.
:type rebalancing_times: pandas.DateTimeIndex):
"""
def __init__(self, target, rebalancing_times):
target_weights = pd.DataFrame(
{el: target for el in rebalancing_times}).T
super().__init__(target_weights)
class ProportionalRebalance(ProportionalTradeToTargets):
"""Trade proportionally in time to track fixed target weights at times.
This calls `ProportionalTradeToTargets`. If you want to change
the target in time use that policy directly.
:param target: Allocation weights to rebalance to.
:type target: pandas.Series
:param rebalancing_times: Times at which we rebalance.
:type rebalancing_times: pandas.DateTimeIndex):
"""
def __init__(self, target, target_matching_times):
targets = pd.DataFrame({el: target for el in target_matching_times}).T
super().__init__(targets)
class AdaptiveRebalance(Policy):
"""Rebalance portfolio when deviates too far from target.
We use the 2-norm as trigger for rebalance. You may want to
calibrate ``tracking_error`` for your application
by backtesting this policy, *e.g.*, to get your desired turnover.
:param target: target weights to rebalance to.
It is assumed a constant if it is a Series. If it varies in
time (you must specify it for every trading day) pass a
DataFrame indexed by time. You can also pass a policy object instance
and its resulting weights will be used as targets, at each point in
time.
:type target: pd.Series or pd.DataFrame or cvx.policy.Policy instance
:param tracking_error: we trade to match the target
weights whenever the 2-norm of our weights minus the
target is larger than this. Pass a Series if you want to vary it in
time.
:type tracking_error: pd.Series or pd.DataFrame
"""
def __init__(self, target, tracking_error):
self.target = DataEstimator(target)
self.tracking_error = DataEstimator(tracking_error)
def values_in_time( # pylint: disable=arguments-differ
self, current_weights, **kwargs):
"""Get target allocation weights.
:param current_weights: Current allocation weights.
:type current_weights: pandas.Series
:param kwargs: Unused arguments to :meth:`values_in_time`.
:type kwargs: dict
:returns: Allocation weights.
:rtype: pandas.Series
"""
if np.linalg.norm(current_weights - self.target.current_value) >\
self.tracking_error.current_value:
return self.target.current_value
return current_weights
# pylint: disable=too-many-instance-attributes
class MultiPeriodOptimization(Policy):
r"""Multi Period Optimization policy.
Implements the model developed in :paper:`chapter 5, page 49 <section.5.2>`
of the paper.
You specify the objective terms
using classes such as ReturnsForecast and TcostModel, each
multiplied by its multiplier. You also specify lists
of constraints. There are two ways to do it. You either
define the same objective terms and costraints for each
step of the multi-period problem, or you define a different
objective term and different list of constraints for each step.
In addition we offer a `terminal_constraint` argument to
simply impose that at the last step in the optimization the
post-trade weights match the given weights (see page 51).
When it computes the trajectory of weights for the future
it only returns the first step (to the Simulator, typically).
The future steps (planning horizon) are by default not returned.
:param objective: These will be maximized;
if you pass a single expression of Cost it is understood as the
same for all steps; if it's a list you must also pass a list of lists
for `constraints`, each term represents the cost for each step of the
optimization (starting from the first, i.e., today) and the length of
the list is used as planning_horizon (the value you pass there will be
ignored)
:type objective: algebra of Cost or list of
:param constraints: These will be
imposed on the optimization. Default []. Pass this as a list of
lists of the same length as `objective` to specify different
constraints at different time steps.
:type constraints: list of Constraints or list of those
:param planning_horizon: How many steps in the future we
plan for. Ignored if passing `objective` and `constraints` as lists.
Default is None.
:type planning_horizon: int or None
:param terminal_constraint: If you pass a Series to this
(default is None) it will impose that at the last step of the multi
period optimization the post-trade weights are equal to this.
:type terminal_constraint: pd.Series or None
:param include_cash_return: Whether to automatically include the
``CashReturn`` term in the objective, with default parameters.
Default is ``True``.
:type include_cash_return: bool
:param benchmark: Benchmark weights to use in the risk model and
other terms that need it. You can use any policy here. Suggested ones
ones are ``AllCash``, the default, ``Uniform``
(uniform allocation on non-cash assets),
and ``MarketBenchmark``, which approximates the market-weighted
portfolio.
:type benchmark: :class:`Policy` class or instance
:param kwargs: Any extra argument will be passed to cvxpy.Problem.solve,
so you can choose a solver and pass parameters to it.
:type kwargs: dict
:raises SyntaxError: If the format of provided objective and constraints
is not right.
"""
# pylint: disable=too-many-arguments
def __init__(
self, objective, constraints=(), include_cash_return=True,
planning_horizon=None, terminal_constraint=None,
benchmark=AllCash, **kwargs):
if hasattr(objective, '__iter__'):
if not (hasattr(constraints, '__iter__') and len(constraints
) and (hasattr(constraints[0], '__iter__') and len(
objective) == len(constraints))):
raise SyntaxError(
'If you pass the objective as a list, constraints should'
+ ' be a list of lists of the same length.')
self._planning_horizon = len(objective)
self.objective = objective
self.constraints = constraints
else:
if not np.isscalar(planning_horizon):
raise SyntaxError(
'If `objective` and `constraints` are the same for '
+ 'all steps you must specify `planning_horizon`.')
self._planning_horizon = planning_horizon
self.objective = [objective.copy_keeping_multipliers()
if hasattr(objective, 'copy_keeping_multipliers')
else copy.deepcopy(objective) for i in range(
planning_horizon)] if planning_horizon > 1 else [objective]
self.constraints = [copy.deepcopy(constraints) for i in range(
planning_horizon)] if planning_horizon > 1 else [constraints]
self._include_cash_return = include_cash_return
if self._include_cash_return:
self.objective = [el + CashReturn() for el in self.objective]
self.terminal_constraint = terminal_constraint
if isinstance(benchmark, (pd.DataFrame, pd.Series)):
self.benchmark = DataEstimator(benchmark, data_includes_cash=True)
else:
self.benchmark = benchmark() if isinstance(benchmark, type
) else benchmark
self.cvxpy_kwargs = kwargs
self._set_internal_vars_to_none()
# for recursive evaluation
self.__subestimators__ = tuple(
[self.benchmark] + self.objective + sum(
[list(con_at_lag) for con_at_lag in self.constraints], []))
def _set_internal_vars_to_none(self):
"""Set internal variables to None, includes CVXPY objects."""
self._cvxpy_objective = 0
self._cvxpy_constraints = []
self._problem = None
self._w_bm = None
self._w_current = None
self._z_at_lags = None
self._w_plus_at_lags = None
self._w_plus_minus_w_bm_at_lags = None
self._cache = {}
def _compile_to_cvxpy(self):
"""Compile all cvxpy expressions and the problem."""
self._cvxpy_objective = [
el.compile_to_cvxpy(
w_plus=self._w_plus_at_lags[i], z=self._z_at_lags[i],
w_plus_minus_w_bm=self._w_plus_minus_w_bm_at_lags[i])
for i, el in enumerate(self.objective)]
for el, term in zip(self.objective, self._cvxpy_objective):
if not term.is_dcp():
raise ConvexSpecificationError(el)
if not term.is_concave():
raise ConvexityError(el)
self._cvxpy_objective = sum(self._cvxpy_objective)
def _compile_and_check_constraint(constr, i):
result = constr.compile_to_cvxpy(
w_plus=self._w_plus_at_lags[i], z=self._z_at_lags[i],
w_plus_minus_w_bm=self._w_plus_minus_w_bm_at_lags[i])
for el in (result if hasattr(result, '__iter__') else [result]):
if not el.is_dcp():
raise ConvexSpecificationError(constr)
return result
self._cvxpy_constraints = [
flatten_heterogeneous_list([
_compile_and_check_constraint(constr, i) for constr in el])
for i, el in enumerate(self.constraints)]
self._cvxpy_constraints = sum(self._cvxpy_constraints, [])
self._cvxpy_constraints += [cp.sum(z) == 0 for z in self._z_at_lags]
w = self._w_current
for i in range(self._planning_horizon):
self._cvxpy_constraints.append(
self._w_plus_at_lags[i] == self._z_at_lags[i] + w)
self._cvxpy_constraints.append(
self._w_plus_at_lags[i] - self._w_bm == \
self._w_plus_minus_w_bm_at_lags[i])
w = self._w_plus_at_lags[i]
if not self.terminal_constraint is None:
self._cvxpy_constraints.append(w == self.terminal_constraint)
self._problem = cp.Problem(cp.Maximize(
self._cvxpy_objective), self._cvxpy_constraints)
if not self._problem.is_dcp(): # this one can't be triggered, I think
raise SyntaxError( # pragma: no cover
f"The optimization problem compiled by {self.__class__.__name__}"
+ " does not follow the convex optimization rules."
+ " This should not happen if you're using the default "
+ " cvxportfolio terms and is probably due to a"
+ " mis-specified custom term.")
def initialize_estimator( # pylint: disable=arguments-differ
self, universe, **kwargs):
"""Initialize the policy object by defining all CVXPY terms.
:param universe: Trading universe, including cash.
:type universe: pandas.Index
:param kwargs: Arguments to :meth:`initialize_estimator`.
:type kwargs: dict
"""
self._w_bm = cp.Parameter(len(universe))
self._w_current = cp.Parameter(len(universe))
self._z_at_lags = [cp.Variable(len(universe))
for i in range(self._planning_horizon)]
self._w_plus_at_lags = [cp.Variable(
len(universe)) for i in range(self._planning_horizon)]
self._w_plus_minus_w_bm_at_lags = [cp.Variable(
len(universe)) for i in range(self._planning_horizon)]
# simulator will overwrite this with cache loaded from disk
self._cache = {}
self._compile_to_cvxpy()
def finalize_estimator(self, **kwargs):
"""Finalize the policy, delete CVXPY objects.
:param kwargs: Unused arguments to :meth:`finalize_estimator`.
:type kwargs: dict
"""
self._set_internal_vars_to_none()
def values_in_time_recursive( # pylint: disable=arguments-differ
self, t, current_weights, current_portfolio_value, **kwargs):
"""Update all cvxpy parameters, solve, and return allocation weights.
We redefine the recursive version of :meth:`values_in_time`
because we change the variables that are passed down the tree:
we add ``cache`` and ``mpo_step``, and the latter is changed for the
different MPO steps.
:param t: Current time.
:type t: pandas.Timestamp
:param current_weights: Current allocation weights.
:type current_weights: pandas.Series
:param current_portfolio_value: Current total value of the portfolio.
:type current_portfolio_value: float
:param kwargs: Other arguments to :meth:`values_in_time_recursive`.
:type kwargs: dict
:raises cvxportfolio.errors.DataError: Current portfolio value is
negative.
:raises cvxportfolio.errors.PortfolioOptimizationError: The portfolio
optimization failed: either the problem was infeasible on
unbounded, or a numerical error occurred. In the latter case the
original Cvxpy exception is re-raised.
:returns: Allocation weights.
:rtype: pandas.Series
"""
if not current_portfolio_value > 0:
raise DataError(
f"Policy {self.__class__.__name__} was evaluated at "
+ f"{t} with negative portfolio value.")
assert np.isclose(sum(current_weights), 1)
for i, obj in enumerate(self.objective):
obj.values_in_time_recursive(
t=t, current_weights=current_weights,
current_portfolio_value=current_portfolio_value,
mpo_step=i, cache=self._cache,
**kwargs)
for i, constr_at_lag in enumerate(self.constraints):
for constr in constr_at_lag:
constr.values_in_time_recursive(
t=t, current_weights=current_weights,
current_portfolio_value=current_portfolio_value,
mpo_step=i, cache=self._cache, **kwargs)
self.benchmark.values_in_time_recursive(
t=t, current_weights=current_weights,
current_portfolio_value=current_portfolio_value,
**kwargs)
self._w_bm.value = np.array(self.benchmark.current_value.values)\
if hasattr(self.benchmark.current_value, 'values'
) else np.array(self.benchmark.current_value)
self._w_current.value = current_weights.values
with warnings.catch_warnings():
# these warnings are thrown on numerical inaccuracies reported by
# the solver and accounted for by cvxpy; we expect expert users
# to set the solver options explicitely and/or setting verbose=True
# in the cvxpy_kwargs
warnings.filterwarnings(
"ignore", category=UserWarning,
message='Solution may be inaccurate')
# cvxpy 1.4 and 1.5 FutureWarnings about ECOS deprecation
if cp.__version__[:3] in ['1.4', '1.5']:
warnings.filterwarnings("ignore", category=FutureWarning)
try:
self._problem.solve(**self.cvxpy_kwargs)
except cp.SolverError as exc:
# try to solve with SCS; it's the most robust
logger.error(
'CVXPY with settings %s reported numerical solver failure'
' at time %s;'
' re-trying by using SCS with basic options.',
self.cvxpy_kwargs, t)
# we could refactor code to handle solve errors also here
try:
self._problem.solve(ignore_dpp=True, solver='SCS')
# old cvxpy had no ignore_dpp
except TypeError: # pragma: no cover
self._problem.solve(solver='SCS') # pragma: no cover
if self._problem.status in ['optimal', 'optimal_inaccurate']:
logger.warning('Fallback solution with SCS worked!')
else: # pragma: no cover
raise PortfolioOptimizationError( # pragma: no cover
f"Numerical solver for policy {self.__class__.__name__}"
+ f" at time {t} failed; try changing it, relaxing some"
+ " constraints, or removing costs.") from exc
if self._problem.status in ["unbounded", "unbounded_inaccurate"]:
raise PortfolioOptimizationError(
f"Policy {self.__class__.__name__} at time "
+ f"{t} resulted in an unbounded problem.")
if self._problem.status in ["infeasible", 'infeasible_inaccurate']:
raise PortfolioOptimizationError(
f"Policy {self.__class__.__name__} at time "
+ f"{t} resulted in an infeasible problem.")
result = current_weights + pd.Series(
self._z_at_lags[0].value, current_weights.index)
self._current_value = result
return result
class SinglePeriodOptimization(MultiPeriodOptimization):
r"""Single Period Optimization policy.
Implements the model developed in :paper:`chapter 4, page 43 <section.4.8>`
of the paper.
You specify the objective terms
using classes such as ReturnsForecast and TcostModel, each
multiplied by its multiplier. You also specify lists
of constraints.
:param objective: This algebraic combination of cvxportfolio cost objects
will be maximized
:type objective: CombinedCost
:param constraints: These will be imposed on the optimization. Default [].
:type constraints: list of Constraints
:param include_cash_return: Whether to automatically include the
``CashReturn`` term in the objective, with default parameters.
Default is ``True``.
:type include_cash_return: bool
:param benchmark: Benchmark weights to use in the risk model and
other terms that need it. You can use any policy here. Suggested ones
ones are ``AllCash``, the default, ``Uniform``
(uniform allocation on non-cash assets),
and ``MarketBenchmark``, which approximates the market-weighted
portfolio.
:type benchmark: :class:`Policy` class or instance
:param kwargs: Any extra argument will be passed to cvxpy.Problem.solve,
so you can choose a solver and pass parameters to it.
:type kwargs: dict
"""
def __init__(self, objective, constraints=(),
include_cash_return=True, benchmark=AllCash, **kwargs):
super().__init__(
[objective], [constraints],
include_cash_return=include_cash_return,
benchmark=benchmark, **kwargs)
def __repr__(self):
return self.__class__.__name__ + '(' \
+ 'objective=' + str(self.objective[0]) \
+ ', constraints=' + str(self.constraints[0])\
+ ', benchmark=' + str(self.benchmark)\
+ ', cvxpy_kwargs=' + str(self.cvxpy_kwargs)\
+ ')'
# Aliases
class SinglePeriodOpt(SinglePeriodOptimization):
"""Alias of :class:`SinglePeriodOptimization`.
As it was defined originally in :paper:`section 6.1 <section.6.1>` of the
paper.
"""
class MultiPeriodOpt(MultiPeriodOptimization):
"""Alias of :class:`MultiPeriodOptimization`.
As it was defined originally in :paper:`section 6.1 <section.6.1>` of the
paper.
"""