-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
test_metrics.py
2362 lines (2059 loc) · 73.5 KB
/
test_metrics.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
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
import unittest
import warnings
import numpy as np
import pandas as pd
from zipline import api
from zipline.assets import Equity, Future
from zipline.assets.synthetic import make_commodity_future_info
from zipline.data.data_portal import DataPortal
from zipline.data.resample import MinuteResampleSessionBarReader
from zipline.testing import (
parameter_space,
prices_generating_returns,
simulate_minutes_for_day,
)
from zipline.testing.fixtures import (
WithMakeAlgo,
WithConstantEquityMinuteBarData,
WithConstantFutureMinuteBarData,
WithWerror,
ZiplineTestCase,
)
from zipline.testing.predicates import assert_equal, wildcard
def T(cs):
return pd.Timestamp(cs, tz='utc')
def portfolio_snapshot(p):
"""Extract all of the fields from the portfolio as a new dictionary.
"""
fields = (
'cash_flow',
'starting_cash',
'portfolio_value',
'pnl',
'returns',
'cash',
'positions',
'positions_value',
'positions_exposure',
)
return {field: getattr(p, field) for field in fields}
class TestConstantPrice(WithConstantEquityMinuteBarData,
WithConstantFutureMinuteBarData,
WithMakeAlgo,
WithWerror,
ZiplineTestCase):
EQUITY_DAILY_BAR_SOURCE_FROM_MINUTE = True
FUTURE_DAILY_BAR_SOURCE_FROM_MINUTE = True
ASSET_FINDER_EQUITY_SIDS = [ord('A')]
EQUITY_MINUTE_CONSTANT_LOW = 1.0
EQUITY_MINUTE_CONSTANT_OPEN = 1.0
EQUITY_MINUTE_CONSTANT_CLOSE = 1.0
EQUITY_MINUTE_CONSTANT_HIGH = 1.0
EQUITY_MINUTE_CONSTANT_VOLUME = 100.0
FUTURE_MINUTE_CONSTANT_LOW = 1.0
FUTURE_MINUTE_CONSTANT_OPEN = 1.0
FUTURE_MINUTE_CONSTANT_CLOSE = 1.0
FUTURE_MINUTE_CONSTANT_HIGH = 1.0
FUTURE_MINUTE_CONSTANT_VOLUME = 100.0
START_DATE = T('2014-01-06')
END_DATE = T('2014-01-10')
# note: class attributes after this do not configure fixtures, they are
# just used in this test suite
# we use a contract multiplier to make sure we are correctly calculating
# exposure as price * multiplier
future_contract_multiplier = 2
# this is the expected exposure for a position of one contract
future_constant_exposure = (
FUTURE_MINUTE_CONSTANT_CLOSE * future_contract_multiplier
)
@classmethod
def make_futures_info(cls):
return make_commodity_future_info(
first_sid=ord('Z'),
root_symbols=['Z'],
years=[cls.START_DATE.year],
multiplier=cls.future_contract_multiplier,
)
@classmethod
def init_class_fixtures(cls):
super(TestConstantPrice, cls).init_class_fixtures()
cls.equity = cls.asset_finder.retrieve_asset(
cls.asset_finder.equities_sids[0],
)
cls.future = cls.asset_finder.retrieve_asset(
cls.asset_finder.futures_sids[0],
)
cls.trading_minutes = pd.Index(
cls.trading_calendar.minutes_for_sessions_in_range(
cls.START_DATE,
cls.END_DATE,
),
)
cls.closes = pd.Index(
cls.trading_calendar.session_closes_in_range(
cls.START_DATE,
cls.END_DATE,
),
)
cls.closes.name = None
def test_nop(self):
# Filter out pandas `ix` DeprecationWarning causing tests to fail
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
perf = self.run_algorithm()
zeros = pd.Series(0.0, index=self.closes)
all_zero_fields = [
'algorithm_period_return',
'benchmark_period_return',
'capital_used',
'excess_return',
'long_exposure',
'long_value',
'longs_count',
'max_drawdown',
'max_leverage',
'short_exposure',
'short_value',
'shorts_count',
'treasury_period_return',
]
for field in all_zero_fields:
assert_equal(
perf[field],
zeros,
check_names=False,
check_dtype=False,
msg=field,
)
nan_then_zero = pd.Series(0.0, index=self.closes)
nan_then_zero[0] = float('nan')
nan_then_zero_fields = (
'algo_volatility',
'benchmark_volatility',
)
for field in nan_then_zero_fields:
assert_equal(
perf[field],
nan_then_zero,
check_names=False,
msg=field,
)
empty_lists = pd.Series([[]] * len(self.closes), self.closes)
empty_list_fields = (
'orders',
'positions',
'transactions',
)
for field in empty_list_fields:
assert_equal(
perf[field],
empty_lists,
check_names=False,
msg=field,
)
@parameter_space(
direction=['long', 'short'],
# checking the portfolio forces a sync; we want to ensure that the
# perf packets are correct even without explicitly requesting the
# portfolio every day. we also want to test that ``context.portfolio``
# produces the expected values when queried mid-simulation
check_portfolio_during_simulation=[True, False],
)
def test_equity_slippage(self,
direction,
check_portfolio_during_simulation):
if direction not in ('long', 'short'):
raise ValueError(
'direction must be either long or short, got: %r' % direction,
)
# the number of shares to order, this will be filled one share at a
# time
shares = 100
# random values in the range [0, 5) rounded to 3 decimal points
st = np.random.RandomState(1868655980)
per_fill_slippage = st.uniform(0, 5, shares).round(3)
if direction == 'short':
per_fill_slippage = -per_fill_slippage
shares = -shares
slippage_iter = iter(per_fill_slippage)
class TestingSlippage(api.slippage.SlippageModel):
@staticmethod
def process_order(data, order):
return (
self.EQUITY_MINUTE_CONSTANT_CLOSE + next(slippage_iter),
1 if direction == 'long' else -1,
)
if check_portfolio_during_simulation:
portfolio_snapshots = {}
def check_portfolio(context):
# force the portfolio even on the first bar
portfolio = context.portfolio
portfolio_snapshots[api.get_datetime()] = portfolio_snapshot(
portfolio,
)
if context.bar_count < 1:
assert_equal(portfolio.positions, {})
return
expected_amount = min(context.bar_count, 100)
if direction == 'short':
expected_amount = -expected_amount
expected_position = {
'asset': self.equity,
'last_sale_date': api.get_datetime(),
'last_sale_price': self.EQUITY_MINUTE_CONSTANT_CLOSE,
'amount': expected_amount,
'cost_basis': (
self.EQUITY_MINUTE_CONSTANT_CLOSE +
per_fill_slippage[:context.bar_count].mean()
),
}
expected_positions = {self.equity: [expected_position]}
positions = {
asset: [{k: getattr(p, k) for k in expected_position}]
for asset, p in portfolio.positions.items()
}
assert_equal(positions, expected_positions)
else:
def check_portfolio(context):
pass
def initialize(context):
api.set_slippage(TestingSlippage())
api.set_commission(api.commission.NoCommission())
context.bar_count = 0
def handle_data(context, data):
if context.bar_count == 0:
api.order(self.equity, shares)
check_portfolio(context)
context.bar_count += 1
perf = self.run_algorithm(
initialize=initialize,
handle_data=handle_data,
)
first_day_returns = -(
abs(per_fill_slippage.sum()) / self.SIM_PARAMS_CAPITAL_BASE
)
expected_returns = pd.Series(0.0, index=self.closes)
expected_returns.iloc[0] = first_day_returns
assert_equal(
perf['returns'],
expected_returns,
check_names=False,
)
expected_cumulative_returns = pd.Series(
first_day_returns,
index=self.closes,
)
assert_equal(
perf['algorithm_period_return'],
expected_cumulative_returns,
check_names=False,
)
first_day_capital_used = -(
shares * self.EQUITY_MINUTE_CONSTANT_CLOSE +
abs(per_fill_slippage.sum())
)
expected_capital_used = pd.Series(0.0, index=self.closes)
expected_capital_used.iloc[0] = first_day_capital_used
assert_equal(
perf['capital_used'],
expected_capital_used,
check_names=False,
)
if not check_portfolio_during_simulation:
return
portfolio_snapshots = pd.DataFrame.from_dict(
portfolio_snapshots,
orient='index',
)
# each minute our cash flow is the share filled (if any) plus the
# slippage for that minute
minutely_cash_flow = pd.Series(0.0, index=self.trading_minutes)
minutely_cash_flow[1:abs(shares) + 1] = (
-(per_fill_slippage + self.EQUITY_MINUTE_CONSTANT_CLOSE)
if direction == 'long' else
(per_fill_slippage + self.EQUITY_MINUTE_CONSTANT_CLOSE)
)
expected_cash_flow = minutely_cash_flow.cumsum()
assert_equal(
portfolio_snapshots['cash_flow'],
expected_cash_flow,
check_names=False,
)
# Our pnl should just be the cost of the slippage incurred. This is
# because we trade from cash into a position which holds 100% of its
# value, but we lose the slippage on the way into that position.
minutely_pnl = pd.Series(0.0, index=self.trading_minutes)
minutely_pnl[1:abs(shares) + 1] = -np.abs(per_fill_slippage)
expected_pnl = minutely_pnl.cumsum()
assert_equal(
portfolio_snapshots['pnl'],
expected_pnl,
check_names=False,
)
# the divisor is capital base because this is cumulative returns
expected_returns = expected_pnl / self.SIM_PARAMS_CAPITAL_BASE
assert_equal(
portfolio_snapshots['returns'],
expected_returns,
check_names=False,
)
@parameter_space(
direction=['long', 'short'],
# checking the portfolio forces a sync; we want to ensure that the
# perf packets are correct even without explicitly requesting the
# portfolio every day. we also want to test that ``context.portfolio``
# produces the expected values when queried mid-simulation
check_portfolio_during_simulation=[True, False],
)
def test_equity_commissions(self,
direction,
check_portfolio_during_simulation):
if direction not in ('long', 'short'):
raise ValueError(
'direction must be either long or short, got: %r' % direction,
)
shares = 100
# random values in the range [0, 5) rounded to 3 decimal points
st = np.random.RandomState(1868655980)
per_fill_commission = st.uniform(0, 5, shares).round(3)
commission_iter = iter(per_fill_commission)
if direction == 'short':
shares = -shares
class SplitOrderButIncurNoSlippage(api.slippage.SlippageModel):
"""This model fills 1 share at a time, but otherwise fills with no
penalty.
"""
@staticmethod
def process_order(data, order):
return (
self.EQUITY_MINUTE_CONSTANT_CLOSE,
1 if direction == 'long' else -1,
)
class TestingCommission(api.commission.CommissionModel):
@staticmethod
def calculate(order, transaction):
return next(commission_iter)
if check_portfolio_during_simulation:
portfolio_snapshots = {}
def check_portfolio(context):
# force the portfolio even on the first bar
portfolio = context.portfolio
portfolio_snapshots[api.get_datetime()] = portfolio_snapshot(
portfolio,
)
if context.bar_count < 1:
assert_equal(portfolio.positions, {})
return
expected_amount = min(context.bar_count, 100)
if direction == 'short':
expected_amount = -expected_amount
expected_position = {
'asset': self.equity,
'last_sale_date': api.get_datetime(),
'last_sale_price': self.EQUITY_MINUTE_CONSTANT_CLOSE,
'amount': expected_amount,
'cost_basis': (
self.EQUITY_MINUTE_CONSTANT_CLOSE +
np.copysign(
per_fill_commission[:context.bar_count].mean(),
expected_amount,
)
),
}
expected_positions = {self.equity: [expected_position]}
positions = {
asset: [{k: getattr(p, k) for k in expected_position}]
for asset, p in portfolio.positions.items()
}
assert_equal(positions, expected_positions)
else:
def check_portfolio(context):
pass
def initialize(context):
api.set_slippage(SplitOrderButIncurNoSlippage())
api.set_commission(TestingCommission())
context.bar_count = 0
def handle_data(context, data):
if context.bar_count == 0:
api.order(self.equity, shares)
check_portfolio(context)
context.bar_count += 1
# Filter out pandas `ix` DeprecationWarning causing tests to fail
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
perf = self.run_algorithm(
initialize=initialize,
handle_data=handle_data,
)
first_day_returns = -(
abs(per_fill_commission.sum()) / self.SIM_PARAMS_CAPITAL_BASE
)
expected_returns = pd.Series(0.0, index=self.closes)
expected_returns.iloc[0] = first_day_returns
assert_equal(
perf['returns'],
expected_returns,
check_names=False,
)
expected_cumulative_returns = pd.Series(
first_day_returns,
index=self.closes,
)
assert_equal(
perf['algorithm_period_return'],
expected_cumulative_returns,
check_names=False,
)
first_day_capital_used = -(
shares * self.EQUITY_MINUTE_CONSTANT_CLOSE +
per_fill_commission.sum()
)
expected_capital_used = pd.Series(0.0, index=self.closes)
expected_capital_used.iloc[0] = first_day_capital_used
assert_equal(
perf['capital_used'],
expected_capital_used,
check_names=False,
)
if not check_portfolio_during_simulation:
return
portfolio_snapshots = pd.DataFrame.from_dict(
portfolio_snapshots,
orient='index',
)
# each minute our cash flow is the share filled (if any) plus the
# commission for that minute
minutely_cash_flow = pd.Series(0.0, index=self.trading_minutes)
minutely_cash_flow[1:abs(shares) + 1] = (
-(self.EQUITY_MINUTE_CONSTANT_CLOSE + per_fill_commission)
if direction == 'long' else
(self.EQUITY_MINUTE_CONSTANT_CLOSE - per_fill_commission)
)
expected_cash_flow = minutely_cash_flow.cumsum()
assert_equal(
portfolio_snapshots['cash_flow'],
expected_cash_flow,
check_names=False,
)
# Our pnl should just be the cost of the commission incurred. This is
# because we trade from cash into a position which holds 100% of its
# value, but we lose the commission on the way into that position.
minutely_pnl = pd.Series(0.0, index=self.trading_minutes)
minutely_pnl[1:abs(shares) + 1] = -per_fill_commission
expected_pnl = minutely_pnl.cumsum()
assert_equal(
portfolio_snapshots['pnl'],
expected_pnl,
check_names=False,
)
# the divisor is capital base because this is cumulative returns
expected_returns = expected_pnl / self.SIM_PARAMS_CAPITAL_BASE
assert_equal(
portfolio_snapshots['returns'],
expected_returns,
check_names=False,
)
@parameter_space(
direction=['long', 'short'],
# checking the portfolio forces a sync; we want to ensure that the
# perf packets are correct even without explicitly requesting the
# portfolio every day. we also want to test that ``context.portfolio``
# produces the expected values when queried mid-simulation
check_portfolio_during_simulation=[True, False],
)
def test_equity_single_position(self,
direction,
check_portfolio_during_simulation):
if direction not in ('long', 'short'):
raise ValueError(
'direction must be either long or short, got: %r' % direction,
)
shares = 1 if direction == 'long' else -1
def initialize(context):
api.set_benchmark(self.equity)
api.set_slippage(api.slippage.NoSlippage())
api.set_commission(api.commission.NoCommission())
context.first_bar = True
if check_portfolio_during_simulation:
portfolio_snapshots = {}
def check_portfolio(context, first_bar):
portfolio = context.portfolio
portfolio_snapshots[api.get_datetime()] = portfolio_snapshot(
portfolio,
)
positions = portfolio.positions
if first_bar:
assert_equal(positions, {})
return
assert_equal(list(positions), [self.equity])
position = positions[self.equity]
assert_equal(position.last_sale_date, api.get_datetime())
assert_equal(position.amount, shares)
assert_equal(
position.last_sale_price,
self.EQUITY_MINUTE_CONSTANT_CLOSE,
)
assert_equal(position.asset, self.equity)
assert_equal(
position.cost_basis,
self.EQUITY_MINUTE_CONSTANT_CLOSE,
)
else:
def check_portfolio(context, first_bar):
pass
def handle_data(context, data):
first_bar = context.first_bar
if first_bar:
api.order(self.equity, shares)
context.first_bar = False
# take the snapshot after the order; ordering does not affect
# the portfolio on the bar of the order, only the following bars
check_portfolio(context, first_bar)
# Filter out pandas `ix` DeprecationWarning causing tests to fail
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
perf = self.run_algorithm(
initialize=initialize,
handle_data=handle_data,
)
zeros = pd.Series(0.0, index=self.closes)
all_zero_fields = [
'algorithm_period_return',
'benchmark_period_return',
'excess_return',
'max_drawdown',
'treasury_period_return',
]
if direction == 'long':
all_zero_fields.extend((
'short_value',
'shorts_count',
))
else:
all_zero_fields.extend((
'long_value',
'longs_count',
))
for field in all_zero_fields:
assert_equal(
perf[field],
zeros,
check_names=False,
check_dtype=False,
msg=field,
)
ones = pd.Series(1, index=self.closes)
if direction == 'long':
count_field = 'longs_count'
else:
count_field = 'shorts_count'
assert_equal(
perf[count_field],
ones,
check_names=False,
msg=field,
)
if direction == 'long':
expected_exposure = pd.Series(
self.EQUITY_MINUTE_CONSTANT_CLOSE,
index=self.closes,
)
for field in 'long_value', 'long_exposure':
assert_equal(
perf[field],
expected_exposure,
check_names=False,
)
else:
expected_exposure = pd.Series(
-self.EQUITY_MINUTE_CONSTANT_CLOSE,
index=self.closes,
)
for field in 'short_value', 'short_exposure':
assert_equal(
perf[field],
expected_exposure,
check_names=False,
)
nan_then_zero = pd.Series(0.0, index=self.closes)
nan_then_zero[0] = float('nan')
nan_then_zero_fields = (
'algo_volatility',
'benchmark_volatility',
)
for field in nan_then_zero_fields:
assert_equal(
perf[field],
nan_then_zero,
check_names=False,
check_dtype=False,
msg=field,
)
capital_base_series = pd.Series(
self.SIM_PARAMS_CAPITAL_BASE,
index=self.closes,
)
# with no commissions, slippage, or returns our portfolio value stays
# constant (at the capital base)
assert_equal(
perf['portfolio_value'],
capital_base_series,
check_names=False,
)
# leverage is gross market exposure / current notional capital
# gross market exposure is
# sum(long_exposure) + sum(abs(short_exposure))
# current notional capital is the current portfolio value
expected_max_leverage = (
# we are exposed to only one share, the portfolio value is the
# capital_base because we have no commissions, slippage, or
# returns
self.EQUITY_MINUTE_CONSTANT_CLOSE / capital_base_series
)
assert_equal(
perf['max_leverage'],
expected_max_leverage,
check_names=False,
)
expected_cash = capital_base_series.copy()
if direction == 'long':
# we purchased one share on the first day
cash_modifier = -self.EQUITY_MINUTE_CONSTANT_CLOSE
else:
# we sold one share on the first day
cash_modifier = +self.EQUITY_MINUTE_CONSTANT_CLOSE
expected_cash[1:] += cash_modifier
assert_equal(
perf['starting_cash'],
expected_cash,
check_names=False,
)
expected_cash[0] += cash_modifier
assert_equal(
perf['ending_cash'],
expected_cash,
check_names=False,
)
# we purchased one share on the first day
expected_capital_used = pd.Series(0.0, index=self.closes)
expected_capital_used[0] += cash_modifier
assert_equal(
perf['capital_used'],
expected_capital_used,
check_names=False,
)
# we hold one share so our positions exposure is that one share's price
expected_position_exposure = pd.Series(
-cash_modifier,
index=self.closes,
)
for field in 'ending_value', 'ending_exposure':
# for equities, position value and position exposure are the same
assert_equal(
perf[field],
expected_position_exposure,
check_names=False,
msg=field,
)
# we don't start with any positions; the first day has no starting
# exposure
expected_position_exposure[0] = 0
for field in 'starting_value', 'starting_exposure':
# for equities, position value and position exposure are the same
assert_equal(
perf[field],
expected_position_exposure,
check_names=False,
msg=field,
)
assert_equal(
perf['trading_days'],
pd.Series(
np.arange(len(self.closes)) + 1,
index=self.closes,
dtype=np.int64,
),
check_names=False,
)
all_none = pd.Series(
[None] * len(self.closes),
index=self.closes, dtype=object,
)
all_none_fields = (
'alpha',
'beta',
'sortino',
)
for field in all_none_fields:
assert_equal(
perf[field],
all_none,
check_names=False,
msg=field,
)
orders = perf['orders']
expected_single_order = {
'amount': shares,
'commission': 0.0,
'created': T('2014-01-06 14:31'),
'dt': T('2014-01-06 14:32'),
'filled': shares,
'id': wildcard,
'limit': None,
'limit_reached': False,
'reason': None,
'sid': self.equity,
'status': 1,
'stop': None,
'stop_reached': False
}
# we only order on the first day
expected_orders = (
[[expected_single_order]] +
[[]] * (len(self.closes) - 1)
)
assert_equal(
orders.tolist(),
expected_orders,
check_names=False,
)
assert_equal(
orders.index,
self.closes,
check_names=False,
)
transactions = perf['transactions']
expected_single_transaction = {
'amount': shares,
'commission': None,
'dt': T('2014-01-06 14:32'),
'order_id': wildcard,
'price': 1.0,
'sid': self.equity,
}
# since we only order on the first day, we should only transact on the
# first day
expected_transactions = (
[[expected_single_transaction]] +
[[]] * (len(self.closes) - 1)
)
assert_equal(
transactions.tolist(),
expected_transactions,
)
assert_equal(
transactions.index,
self.closes,
check_names=False,
)
if not check_portfolio_during_simulation:
return
portfolio_snapshots = pd.DataFrame.from_dict(
portfolio_snapshots,
orient='index',
)
expected_cash = pd.Series(
self.SIM_PARAMS_CAPITAL_BASE,
index=self.trading_minutes,
)
if direction == 'long':
expected_cash.iloc[1:] -= self.EQUITY_MINUTE_CONSTANT_CLOSE
else:
expected_cash.iloc[1:] += self.EQUITY_MINUTE_CONSTANT_CLOSE
assert_equal(
portfolio_snapshots['cash'],
expected_cash,
check_names=False,
)
expected_portfolio_capital_used = pd.Series(
cash_modifier,
index=self.trading_minutes,
)
expected_portfolio_capital_used[0] = 0.0
expected_capital_used[0] = 0
assert_equal(
portfolio_snapshots['cash_flow'],
expected_portfolio_capital_used,
check_names=False,
)
zero_minutes = pd.Series(0.0, index=self.trading_minutes)
for field in 'pnl', 'returns':
assert_equal(
portfolio_snapshots[field],
zero_minutes,
check_names=False,
msg=field,
)
reindex_columns = sorted(
set(portfolio_snapshots.columns) - {
'starting_cash',
'cash_flow',
'pnl',
'returns',
'positions',
},
)
minute_reindex = perf.rename(
columns={
'capital_used': 'cash_flow',
'ending_cash': 'cash',
'ending_exposure': 'positions_exposure',
'ending_value': 'positions_value',
},
)[reindex_columns].reindex(
self.trading_minutes,
method='bfill',
)
first_minute = self.trading_minutes[0]
# the first minute should have the default values because we haven't
# done anything yet
minute_reindex.loc[first_minute, 'cash'] = (
self.SIM_PARAMS_CAPITAL_BASE
)
minute_reindex.loc[
first_minute,
['positions_exposure', 'positions_value'],
] = 0
assert_equal(
portfolio_snapshots[reindex_columns],
minute_reindex,
check_names=False,
)
@unittest.skip("Needs fix to calendar mismatch.")
@parameter_space(
direction=['long', 'short'],
# checking the portfolio forces a sync; we want to ensure that the
# perf packets are correct even without explicitly requesting the
# portfolio every day. we also want to test that ``context.portfolio``
# produces the expected values when queried mid-simulation
check_portfolio_during_simulation=[True, False],
)
def test_future_single_position(self,
direction,
check_portfolio_during_simulation):
if direction not in ('long', 'short'):
raise ValueError(
'direction must be either long or short, got: %r' % direction,
)
if direction == 'long':
contracts = 1
expected_exposure = self.future_constant_exposure
else:
contracts = -1
expected_exposure = -self.future_constant_exposure
def initialize(context):
api.set_benchmark(self.equity)
api.set_slippage(us_futures=api.slippage.NoSlippage())
api.set_commission(us_futures=api.commission.NoCommission())
context.first_bar = True
if check_portfolio_during_simulation:
portfolio_snapshots = {}
def check_portfolio(context, first_bar):
portfolio = context.portfolio
portfolio_snapshots[api.get_datetime()] = portfolio_snapshot(
portfolio,
)
positions = portfolio.positions
if first_bar:
assert_equal(positions, {})
return