forked from scrtlabs/catalyst
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_perf_tracking.py
2170 lines (1848 loc) · 75.5 KB
/
test_perf_tracking.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
#
# Copyright 2016 Quantopian, 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.
from __future__ import division
import copy
from datetime import (
datetime,
timedelta,
)
import logging
import nose.tools as nt
import pytz
import pandas as pd
import numpy as np
from six.moves import range, zip
from catalyst.assets import Asset
from catalyst.assets.synthetic import make_simple_equity_info
from catalyst.data.us_equity_pricing import (
SQLiteAdjustmentWriter,
SQLiteAdjustmentReader,
)
import catalyst.utils.factory as factory
import catalyst.finance.performance as perf
from catalyst.finance.transaction import create_transaction
import catalyst.utils.math_utils as zp_math
from catalyst.finance.blotter import Order
from catalyst.finance.performance.position import Position
from catalyst.utils.factory import create_simulation_parameters
from catalyst.utils.serialization_utils import (
loads_with_persistent_ids, dumps_with_persistent_ids
)
from catalyst.testing import (
MockDailyBarReader,
create_data_portal_from_trade_history,
create_empty_splits_mergers_frame,
tmp_trading_env,
)
from catalyst.testing.fixtures import (
WithInstanceTmpDir,
WithSimParams,
WithTmpDir,
WithTradingEnvironment,
ZiplineTestCase,
)
from catalyst.utils.calendars import get_calendar
logger = logging.getLogger('Test Perf Tracking')
oneday = timedelta(days=1)
tradingday = timedelta(hours=6, minutes=30)
# nose.tools changed name in python 3
if not hasattr(nt, 'assert_count_equal'):
nt.assert_count_equal = nt.assert_items_equal
def check_perf_period(pp,
gross_leverage,
net_leverage,
long_exposure,
longs_count,
short_exposure,
shorts_count):
perf_data = pp.to_dict()
np.testing.assert_allclose(
gross_leverage, perf_data['gross_leverage'], rtol=1e-3)
np.testing.assert_allclose(
net_leverage, perf_data['net_leverage'], rtol=1e-3)
np.testing.assert_allclose(
long_exposure, perf_data['long_exposure'], rtol=1e-3)
np.testing.assert_allclose(
longs_count, perf_data['longs_count'], rtol=1e-3)
np.testing.assert_allclose(
short_exposure, perf_data['short_exposure'], rtol=1e-3)
np.testing.assert_allclose(
shorts_count, perf_data['shorts_count'], rtol=1e-3)
def check_account(account,
settled_cash,
equity_with_loan,
total_positions_value,
total_positions_exposure,
regt_equity,
available_funds,
excess_liquidity,
cushion,
leverage,
net_leverage,
net_liquidation):
# this is a long only portfolio that is only partially invested
# so net and gross leverage are equal.
np.testing.assert_allclose(settled_cash,
account.settled_cash, rtol=1e-3)
np.testing.assert_allclose(equity_with_loan,
account.equity_with_loan, rtol=1e-3)
np.testing.assert_allclose(total_positions_value,
account.total_positions_value, rtol=1e-3)
np.testing.assert_allclose(total_positions_exposure,
account.total_positions_exposure, rtol=1e-3)
np.testing.assert_allclose(regt_equity,
account.regt_equity, rtol=1e-3)
np.testing.assert_allclose(available_funds,
account.available_funds, rtol=1e-3)
np.testing.assert_allclose(excess_liquidity,
account.excess_liquidity, rtol=1e-3)
np.testing.assert_allclose(cushion,
account.cushion, rtol=1e-3)
np.testing.assert_allclose(leverage, account.leverage, rtol=1e-3)
np.testing.assert_allclose(net_leverage,
account.net_leverage, rtol=1e-3)
np.testing.assert_allclose(net_liquidation,
account.net_liquidation, rtol=1e-3)
def create_txn(asset, dt, price, amount):
"""
Create a fake transaction to be filled and processed prior to the execution
of a given trade event.
"""
if not isinstance(asset, Asset):
raise ValueError("pass an asset to create_txn")
mock_order = Order(dt, asset, amount, id=None)
return create_transaction(mock_order, dt, price, amount)
def calculate_results(sim_params,
env,
data_portal,
splits=None,
txns=None,
commissions=None):
"""
Run the given events through a stripped down version of the loop in
AlgorithmSimulator.transform.
IMPORTANT NOTE FOR TEST WRITERS/READERS:
This loop has some wonky logic for the order of event processing for
datasource types. This exists mostly to accommodate legacy tests that were
making assumptions about how events would be sorted.
In particular:
- Dividends passed for a given date are processed PRIOR to any events
for that date.
- Splits passed for a given date are process AFTER any events for that
date.
Tests that use this helper should not be considered useful guarantees of
the behavior of AlgorithmSimulator on a stream containing the same events
unless the subgroups have been explicitly re-sorted in this way.
"""
txns = txns or []
splits = splits or {}
commissions = commissions or {}
perf_tracker = perf.PerformanceTracker(
sim_params, get_calendar("NYSE"), env
)
results = []
for date in sim_params.sessions:
for txn in filter(lambda txn: txn.dt == date, txns):
# Process txns for this date.
perf_tracker.process_transaction(txn)
try:
commissions_for_date = commissions[date]
for comm in commissions_for_date:
perf_tracker.process_commission(comm)
except KeyError:
pass
try:
splits_for_date = splits[date]
perf_tracker.handle_splits(splits_for_date)
except KeyError:
pass
msg = perf_tracker.handle_market_close(date, data_portal)
perf_tracker.position_tracker.sync_last_sale_prices(
date, False, data_portal,
)
msg['account'] = perf_tracker.get_account(True)
results.append(copy.deepcopy(msg))
return results
def check_perf_tracker_serialization(perf_tracker):
scalar_keys = [
'emission_rate',
'txn_count',
'market_open',
'last_close',
'start_session',
'day_count',
'capital_base',
'market_close',
'saved_dt',
'period_end',
'total_days',
]
p_string = dumps_with_persistent_ids(perf_tracker)
test = loads_with_persistent_ids(p_string, env=perf_tracker.env)
for k in scalar_keys:
nt.assert_equal(getattr(test, k), getattr(perf_tracker, k), k)
perf_periods = (
test.cumulative_performance,
test.todays_performance
)
for period in perf_periods:
nt.assert_true(hasattr(period, '_position_tracker'))
def setup_env_data(env, sim_params, sids, futures_sids=[]):
data = {}
for sid in sids:
data[sid] = {
"start_date": sim_params.sessions[0],
"end_date": get_calendar("NYSE").next_session_label(
sim_params.sessions[-1]
)
}
env.write_data(equities_data=data)
futures_data = {}
for future_sid in futures_sids:
futures_data[future_sid] = {
"start_date": sim_params.sessions[0],
# (obviously) FIXME once we have a future calendar
"end_date": get_calendar("NYSE").next_session_label(
sim_params.sessions[-1]
),
"multiplier": 100
}
env.write_data(futures_data=futures_data)
class TestSplitPerformance(WithSimParams, WithTmpDir, ZiplineTestCase):
START_DATE = pd.Timestamp('2006-01-03', tz='utc')
END_DATE = pd.Timestamp('2006-01-04', tz='utc')
SIM_PARAMS_CAPITAL_BASE = 10e3
ASSET_FINDER_EQUITY_SIDS = 1, 2
@classmethod
def init_class_fixtures(cls):
super(TestSplitPerformance, cls).init_class_fixtures()
cls.asset1 = cls.env.asset_finder.retrieve_asset(1)
cls.asset2 = cls.env.asset_finder.retrieve_asset(2)
def test_multiple_splits(self):
# if multiple positions all have splits at the same time, verify that
# the total leftover cash is correct
perf_tracker = perf.PerformanceTracker(self.sim_params,
self.trading_calendar,
self.env)
perf_tracker.position_tracker.positions[1] = \
Position(self.asset1, amount=10, cost_basis=10, last_sale_price=11)
perf_tracker.position_tracker.positions[2] = \
Position(self.asset2, amount=10, cost_basis=10, last_sale_price=11)
leftover_cash = perf_tracker.position_tracker.handle_splits(
[(self.asset1, 0.333), (self.asset2, 0.333)]
)
# we used to have 10 shares that each cost us $10, total $100
# now we have 33 shares that each cost us $3.33, total $99.9
# each position returns $0.10 as leftover cash
self.assertEqual(0.2, leftover_cash)
def test_split_long_position(self):
events = factory.create_trade_history(
self.asset1,
# TODO: Should we provide adjusted prices in the tests, or provide
# raw prices and adjust via DataPortal?
[20, 60],
[100, 100],
oneday,
self.sim_params,
trading_calendar=self.trading_calendar,
)
# set up a long position in sid 1
# 100 shares at $20 apiece = $2000 position
data_portal = create_data_portal_from_trade_history(
self.env.asset_finder,
self.trading_calendar,
self.tmpdir,
self.sim_params,
{1: events},
)
txns = [create_txn(self.asset1, events[0].dt, 20, 100)]
# set up a split with ratio 3 occurring at the start of the second
# day.
splits = {
events[1].dt: [(self.asset1, 3)]
}
results = calculate_results(self.sim_params,
self.env,
data_portal,
txns=txns,
splits=splits)
# should have 33 shares (at $60 apiece) and $20 in cash
self.assertEqual(2, len(results))
latest_positions = results[1]['daily_perf']['positions']
self.assertEqual(1, len(latest_positions))
# check the last position to make sure it's been updated
position = latest_positions[0]
self.assertEqual(self.asset1, position['sid'])
self.assertEqual(33, position['amount'])
self.assertEqual(60, position['cost_basis'])
self.assertEqual(60, position['last_sale_price'])
# since we started with $10000, and we spent $2000 on the
# position, but then got $20 back, we should have $8020
# (or close to it) in cash.
# we won't get exactly 8020 because sometimes a split is
# denoted as a ratio like 0.3333, and we lose some digits
# of precision. thus, make sure we're pretty close.
daily_perf = results[1]['daily_perf']
self.assertTrue(
zp_math.tolerant_equals(8020,
daily_perf['ending_cash'], 1),
"ending_cash was {0}".format(daily_perf['ending_cash']))
# Validate that the account attributes were updated.
account = results[1]['account']
self.assertEqual(float('inf'), account.day_trades_remaining)
# this is a long only portfolio that is only partially invested
# so net and gross leverage are equal.
np.testing.assert_allclose(0.198, account.leverage, rtol=1e-3)
np.testing.assert_allclose(0.198, account.net_leverage, rtol=1e-3)
np.testing.assert_allclose(8020, account.regt_equity, rtol=1e-3)
self.assertEqual(float('inf'), account.regt_margin)
np.testing.assert_allclose(8020, account.available_funds, rtol=1e-3)
self.assertEqual(0, account.maintenance_margin_requirement)
np.testing.assert_allclose(10000,
account.equity_with_loan, rtol=1e-3)
self.assertEqual(float('inf'), account.buying_power)
self.assertEqual(0, account.initial_margin_requirement)
np.testing.assert_allclose(8020, account.excess_liquidity,
rtol=1e-3)
np.testing.assert_allclose(8020, account.settled_cash, rtol=1e-3)
np.testing.assert_allclose(10000, account.net_liquidation,
rtol=1e-3)
np.testing.assert_allclose(0.802, account.cushion, rtol=1e-3)
np.testing.assert_allclose(1980, account.total_positions_value,
rtol=1e-3)
self.assertEqual(0, account.accrued_interest)
for i, result in enumerate(results):
for perf_kind in ('daily_perf', 'cumulative_perf'):
perf_result = result[perf_kind]
# prices aren't changing, so pnl and returns should be 0.0
self.assertEqual(0.0, perf_result['pnl'],
"day %s %s pnl %s instead of 0.0" %
(i, perf_kind, perf_result['pnl']))
self.assertEqual(0.0, perf_result['returns'],
"day %s %s returns %s instead of 0.0" %
(i, perf_kind, perf_result['returns']))
class TestDividendPerformance(WithSimParams,
WithInstanceTmpDir,
ZiplineTestCase):
START_DATE = pd.Timestamp('2006-01-03', tz='utc')
END_DATE = pd.Timestamp('2006-01-10', tz='utc')
ASSET_FINDER_EQUITY_SIDS = 1, 2
SIM_PARAMS_CAPITAL_BASE = 10e3
@classmethod
def init_class_fixtures(cls):
super(TestDividendPerformance, cls).init_class_fixtures()
cls.asset1 = cls.asset_finder.retrieve_asset(1)
cls.asset2 = cls.asset_finder.retrieve_asset(2)
def test_market_hours_calculations(self):
# DST in US/Eastern began on Sunday March 14, 2010
before = datetime(2010, 3, 12, 14, 31, tzinfo=pytz.utc)
after = factory.get_next_trading_dt(
before,
timedelta(days=1),
self.trading_calendar,
)
self.assertEqual(after.hour, 13)
def test_long_position_receives_dividend(self):
# post some trades in the market
events = factory.create_trade_history(
self.asset1,
[10, 10, 10, 10, 10, 10],
[100, 100, 100, 100, 100, 100],
oneday,
self.sim_params,
trading_calendar=self.trading_calendar,
)
dbpath = self.instance_tmpdir.getpath('adjustments.sqlite')
writer = SQLiteAdjustmentWriter(
dbpath,
MockDailyBarReader(),
self.trading_calendar.all_sessions,
)
splits = mergers = create_empty_splits_mergers_frame()
dividends = pd.DataFrame({
'sid': np.array([1], dtype=np.uint32),
'amount': np.array([10.00], dtype=np.float64),
'declared_date': np.array([events[0].dt], dtype='datetime64[ns]'),
'ex_date': np.array([events[1].dt], dtype='datetime64[ns]'),
'record_date': np.array([events[1].dt], dtype='datetime64[ns]'),
'pay_date': np.array([events[2].dt], dtype='datetime64[ns]'),
})
writer.write(splits, mergers, dividends)
adjustment_reader = SQLiteAdjustmentReader(dbpath)
data_portal = create_data_portal_from_trade_history(
self.env.asset_finder,
self.trading_calendar,
self.instance_tmpdir,
self.sim_params,
{1: events},
)
data_portal._adjustment_reader = adjustment_reader
# Simulate a transaction being filled prior to the ex_date.
txns = [create_txn(self.asset1, events[0].dt, 10.0, 100)]
results = calculate_results(
self.sim_params,
self.env,
data_portal,
txns=txns,
)
self.assertEqual(len(results), 6)
cumulative_returns = \
[event['cumulative_perf']['returns'] for event in results]
self.assertEqual(cumulative_returns, [0.0, 0.0, 0.1, 0.1, 0.1, 0.1])
daily_returns = [event['daily_perf']['returns']
for event in results]
self.assertEqual(daily_returns, [0.0, 0.0, 0.10, 0.0, 0.0, 0.0])
cash_flows = [event['daily_perf']['capital_used']
for event in results]
self.assertEqual(cash_flows, [-1000, 0, 1000, 0, 0, 0])
cumulative_cash_flows = \
[event['cumulative_perf']['capital_used'] for event in results]
self.assertEqual(cumulative_cash_flows, [-1000, -1000, 0, 0, 0, 0])
cash_pos = \
[event['cumulative_perf']['ending_cash'] for event in results]
self.assertEqual(cash_pos, [9000, 9000, 10000, 10000, 10000, 10000])
def test_long_position_receives_stock_dividend(self):
# post some trades in the market
events = {}
for asset in [self.asset1, self.asset2]:
events[asset.sid] = factory.create_trade_history(
asset,
[10, 10, 10, 10, 10, 10],
[100, 100, 100, 100, 100, 100],
oneday,
self.sim_params,
trading_calendar=self.trading_calendar,
)
dbpath = self.instance_tmpdir.getpath('adjustments.sqlite')
writer = SQLiteAdjustmentWriter(
dbpath,
MockDailyBarReader(),
self.trading_calendar.all_sessions
)
splits = mergers = create_empty_splits_mergers_frame()
dividends = pd.DataFrame({
'sid': np.array([], dtype=np.uint32),
'amount': np.array([], dtype=np.float64),
'declared_date': np.array([], dtype='datetime64[ns]'),
'ex_date': np.array([], dtype='datetime64[ns]'),
'pay_date': np.array([], dtype='datetime64[ns]'),
'record_date': np.array([], dtype='datetime64[ns]'),
})
sid_1 = events[1]
stock_dividends = pd.DataFrame({
'sid': np.array([1], dtype=np.uint32),
'payment_sid': np.array([2], dtype=np.uint32),
'ratio': np.array([2], dtype=np.float64),
'declared_date': np.array([sid_1[0].dt], dtype='datetime64[ns]'),
'ex_date': np.array([sid_1[1].dt], dtype='datetime64[ns]'),
'record_date': np.array([sid_1[1].dt], dtype='datetime64[ns]'),
'pay_date': np.array([sid_1[2].dt], dtype='datetime64[ns]'),
})
writer.write(splits, mergers, dividends, stock_dividends)
adjustment_reader = SQLiteAdjustmentReader(dbpath)
data_portal = create_data_portal_from_trade_history(
self.env.asset_finder,
self.trading_calendar,
self.instance_tmpdir,
self.sim_params,
events,
)
data_portal._adjustment_reader = adjustment_reader
txns = [create_txn(self.asset1, events[1][0].dt, 10.0, 100)]
results = calculate_results(
self.sim_params,
self.env,
data_portal,
txns=txns,
)
self.assertEqual(len(results), 6)
cumulative_returns = \
[event['cumulative_perf']['returns'] for event in results]
self.assertEqual(cumulative_returns, [0.0, 0.0, 0.2, 0.2, 0.2, 0.2])
daily_returns = [event['daily_perf']['returns']
for event in results]
self.assertEqual(daily_returns, [0.0, 0.0, 0.2, 0.0, 0.0, 0.0])
cash_flows = [event['daily_perf']['capital_used']
for event in results]
self.assertEqual(cash_flows, [-1000, 0, 0, 0, 0, 0])
cumulative_cash_flows = \
[event['cumulative_perf']['capital_used'] for event in results]
self.assertEqual(cumulative_cash_flows, [-1000] * 6)
cash_pos = \
[event['cumulative_perf']['ending_cash'] for event in results]
self.assertEqual(cash_pos, [9000] * 6)
def test_long_position_purchased_on_ex_date_receives_no_dividend(self):
# post some trades in the market
events = factory.create_trade_history(
self.asset1,
[10, 10, 10, 10, 10, 10],
[100, 100, 100, 100, 100, 100],
oneday,
self.sim_params,
trading_calendar=self.trading_calendar
)
dbpath = self.instance_tmpdir.getpath('adjustments.sqlite')
writer = SQLiteAdjustmentWriter(
dbpath,
MockDailyBarReader(),
self.trading_calendar.all_sessions
)
splits = mergers = create_empty_splits_mergers_frame()
dividends = pd.DataFrame({
'sid': np.array([1], dtype=np.uint32),
'amount': np.array([10.00], dtype=np.float64),
'declared_date': np.array([events[0].dt], dtype='datetime64[ns]'),
'ex_date': np.array([events[1].dt], dtype='datetime64[ns]'),
'record_date': np.array([events[1].dt], dtype='datetime64[ns]'),
'pay_date': np.array([events[2].dt], dtype='datetime64[ns]'),
})
writer.write(splits, mergers, dividends)
adjustment_reader = SQLiteAdjustmentReader(dbpath)
data_portal = create_data_portal_from_trade_history(
self.env.asset_finder,
self.trading_calendar,
self.instance_tmpdir,
self.sim_params,
{1: events},
)
data_portal._adjustment_reader = adjustment_reader
# Simulate a transaction being filled on the ex_date.
txns = [create_txn(self.asset1, events[1].dt, 10.0, 100)]
results = calculate_results(
self.sim_params,
self.env,
data_portal,
txns=txns,
)
self.assertEqual(len(results), 6)
cumulative_returns = \
[event['cumulative_perf']['returns'] for event in results]
self.assertEqual(cumulative_returns, [0, 0, 0, 0, 0, 0])
daily_returns = [event['daily_perf']['returns'] for event in results]
self.assertEqual(daily_returns, [0, 0, 0, 0, 0, 0])
cash_flows = [event['daily_perf']['capital_used'] for event in results]
self.assertEqual(cash_flows, [0, -1000, 0, 0, 0, 0])
cumulative_cash_flows = \
[event['cumulative_perf']['capital_used'] for event in results]
self.assertEqual(cumulative_cash_flows,
[0, -1000, -1000, -1000, -1000, -1000])
def test_selling_before_dividend_payment_still_gets_paid(self):
# post some trades in the market
events = factory.create_trade_history(
self.asset1,
[10, 10, 10, 10, 10, 10],
[100, 100, 100, 100, 100, 100],
oneday,
self.sim_params,
trading_calendar=self.trading_calendar,
)
dbpath = self.instance_tmpdir.getpath('adjustments.sqlite')
writer = SQLiteAdjustmentWriter(
dbpath,
MockDailyBarReader(),
self.trading_calendar.all_sessions,
)
splits = mergers = create_empty_splits_mergers_frame()
dividends = pd.DataFrame({
'sid': np.array([1], dtype=np.uint32),
'amount': np.array([10.00], dtype=np.float64),
'declared_date': np.array([events[0].dt], dtype='datetime64[ns]'),
'ex_date': np.array([events[1].dt], dtype='datetime64[ns]'),
'record_date': np.array([events[1].dt], dtype='datetime64[ns]'),
'pay_date': np.array([events[3].dt], dtype='datetime64[ns]'),
})
writer.write(splits, mergers, dividends)
adjustment_reader = SQLiteAdjustmentReader(dbpath)
data_portal = create_data_portal_from_trade_history(
self.env.asset_finder,
self.trading_calendar,
self.instance_tmpdir,
self.sim_params,
{1: events},
)
data_portal._adjustment_reader = adjustment_reader
buy_txn = create_txn(self.asset1, events[0].dt, 10.0, 100)
sell_txn = create_txn(self.asset1, events[2].dt, 10.0, -100)
txns = [buy_txn, sell_txn]
results = calculate_results(
self.sim_params,
self.env,
data_portal,
txns=txns,
)
self.assertEqual(len(results), 6)
cumulative_returns = \
[event['cumulative_perf']['returns'] for event in results]
self.assertEqual(cumulative_returns, [0, 0, 0, 0.1, 0.1, 0.1])
daily_returns = [event['daily_perf']['returns'] for event in results]
self.assertEqual(daily_returns, [0, 0, 0, 0.1, 0, 0])
cash_flows = [event['daily_perf']['capital_used'] for event in results]
self.assertEqual(cash_flows, [-1000, 0, 1000, 1000, 0, 0])
cumulative_cash_flows = \
[event['cumulative_perf']['capital_used'] for event in results]
self.assertEqual(cumulative_cash_flows,
[-1000, -1000, 0, 1000, 1000, 1000])
def test_buy_and_sell_before_ex(self):
# need a six-day simparam
# post some trades in the market
events = factory.create_trade_history(
self.asset1,
[10, 10, 10, 10, 10, 10],
[100, 100, 100, 100, 100, 100],
oneday,
self.sim_params,
trading_calendar=self.trading_calendar,
)
dbpath = self.instance_tmpdir.getpath('adjustments.sqlite')
writer = SQLiteAdjustmentWriter(
dbpath,
MockDailyBarReader(),
self.trading_calendar.all_sessions,
)
splits = mergers = create_empty_splits_mergers_frame()
dividends = pd.DataFrame({
'sid': np.array([1], dtype=np.uint32),
'amount': np.array([10.0], dtype=np.float64),
'declared_date': np.array([events[3].dt], dtype='datetime64[ns]'),
'ex_date': np.array([events[4].dt], dtype='datetime64[ns]'),
'pay_date': np.array([events[5].dt], dtype='datetime64[ns]'),
'record_date': np.array([events[4].dt], dtype='datetime64[ns]'),
})
writer.write(splits, mergers, dividends)
adjustment_reader = SQLiteAdjustmentReader(dbpath)
data_portal = create_data_portal_from_trade_history(
self.env.asset_finder,
self.trading_calendar,
self.instance_tmpdir,
self.sim_params,
{1: events},
)
data_portal._adjustment_reader = adjustment_reader
buy_txn = create_txn(self.asset1, events[1].dt, 10.0, 100)
sell_txn = create_txn(self.asset1, events[2].dt, 10.0, -100)
txns = [buy_txn, sell_txn]
results = calculate_results(
self.sim_params,
self.env,
data_portal,
txns=txns,
)
self.assertEqual(len(results), 6)
cumulative_returns = \
[event['cumulative_perf']['returns'] for event in results]
self.assertEqual(cumulative_returns, [0, 0, 0, 0, 0, 0])
daily_returns = [event['daily_perf']['returns'] for event in results]
self.assertEqual(daily_returns, [0, 0, 0, 0, 0, 0])
cash_flows = [event['daily_perf']['capital_used'] for event in results]
self.assertEqual(cash_flows, [0, -1000, 1000, 0, 0, 0])
cumulative_cash_flows = \
[event['cumulative_perf']['capital_used'] for event in results]
self.assertEqual(cumulative_cash_flows, [0, -1000, 0, 0, 0, 0])
def test_ending_before_pay_date(self):
# post some trades in the market
events = factory.create_trade_history(
self.asset1,
[10, 10, 10, 10, 10, 10],
[100, 100, 100, 100, 100, 100],
oneday,
self.sim_params,
trading_calendar=self.trading_calendar,
)
pay_date = self.sim_params.first_open
# find pay date that is much later.
for i in range(30):
pay_date = factory.get_next_trading_dt(pay_date, oneday,
self.trading_calendar)
dbpath = self.instance_tmpdir.getpath('adjustments.sqlite')
writer = SQLiteAdjustmentWriter(
dbpath,
MockDailyBarReader(),
self.trading_calendar.all_sessions,
)
splits = mergers = create_empty_splits_mergers_frame()
dividends = pd.DataFrame({
'sid': np.array([1], dtype=np.uint32),
'amount': np.array([10.00], dtype=np.float64),
'declared_date': np.array([events[0].dt], dtype='datetime64[ns]'),
'ex_date': np.array([events[0].dt], dtype='datetime64[ns]'),
'record_date': np.array([events[0].dt], dtype='datetime64[ns]'),
'pay_date': np.array([pay_date], dtype='datetime64[ns]'),
})
writer.write(splits, mergers, dividends)
adjustment_reader = SQLiteAdjustmentReader(dbpath)
data_portal = create_data_portal_from_trade_history(
self.env.asset_finder,
self.trading_calendar,
self.instance_tmpdir,
self.sim_params,
{1: events},
)
data_portal._adjustment_reader = adjustment_reader
txns = [create_txn(self.asset1, events[1].dt, 10.0, 100)]
results = calculate_results(
self.sim_params,
self.env,
data_portal,
txns=txns,
)
self.assertEqual(len(results), 6)
cumulative_returns = \
[event['cumulative_perf']['returns'] for event in results]
self.assertEqual(cumulative_returns, [0, 0, 0, 0.0, 0.0, 0.0])
daily_returns = [event['daily_perf']['returns'] for event in results]
self.assertEqual(daily_returns, [0, 0, 0, 0, 0, 0])
cash_flows = [event['daily_perf']['capital_used'] for event in results]
self.assertEqual(cash_flows, [0, -1000, 0, 0, 0, 0])
cumulative_cash_flows = \
[event['cumulative_perf']['capital_used'] for event in results]
self.assertEqual(
cumulative_cash_flows,
[0, -1000, -1000, -1000, -1000, -1000]
)
def test_short_position_pays_dividend(self):
# post some trades in the market
events = factory.create_trade_history(
self.asset1,
[10, 10, 10, 10, 10, 10],
[100, 100, 100, 100, 100, 100],
oneday,
self.sim_params,
trading_calendar=self.trading_calendar,
)
dbpath = self.instance_tmpdir.getpath('adjustments.sqlite')
writer = SQLiteAdjustmentWriter(
dbpath,
MockDailyBarReader(),
self.trading_calendar.all_sessions,
)
splits = mergers = create_empty_splits_mergers_frame()
dividends = pd.DataFrame({
'sid': np.array([1], dtype=np.uint32),
'amount': np.array([10.00], dtype=np.float64),
'declared_date': np.array([events[0].dt], dtype='datetime64[ns]'),
'ex_date': np.array([events[2].dt], dtype='datetime64[ns]'),
'record_date': np.array([events[2].dt], dtype='datetime64[ns]'),
'pay_date': np.array([events[3].dt], dtype='datetime64[ns]'),
})
writer.write(splits, mergers, dividends)
adjustment_reader = SQLiteAdjustmentReader(dbpath)
data_portal = create_data_portal_from_trade_history(
self.env.asset_finder,
self.trading_calendar,
self.instance_tmpdir,
self.sim_params,
{1: events},
)
data_portal._adjustment_reader = adjustment_reader
txns = [create_txn(self.asset1, events[1].dt, 10.0, -100)]
results = calculate_results(
self.sim_params,
self.env,
data_portal,
txns=txns,
)
self.assertEqual(len(results), 6)
cumulative_returns = \
[event['cumulative_perf']['returns'] for event in results]
self.assertEqual(cumulative_returns, [0.0, 0.0, 0.0, -0.1, -0.1, -0.1])
daily_returns = [event['daily_perf']['returns'] for event in results]
self.assertEqual(daily_returns, [0.0, 0.0, 0.0, -0.1, 0.0, 0.0])
cash_flows = [event['daily_perf']['capital_used'] for event in results]
self.assertEqual(cash_flows, [0, 1000, 0, -1000, 0, 0])
cumulative_cash_flows = \
[event['cumulative_perf']['capital_used'] for event in results]
self.assertEqual(cumulative_cash_flows, [0, 1000, 1000, 0, 0, 0])
def test_no_position_receives_no_dividend(self):
# post some trades in the market
events = factory.create_trade_history(
self.asset1,
[10, 10, 10, 10, 10, 10],
[100, 100, 100, 100, 100, 100],
oneday,
self.sim_params,
trading_calendar=self.trading_calendar,
)
dbpath = self.instance_tmpdir.getpath('adjustments.sqlite')
writer = SQLiteAdjustmentWriter(
dbpath,
MockDailyBarReader(),
self.trading_calendar.all_sessions,
)
splits = mergers = create_empty_splits_mergers_frame()
dividends = pd.DataFrame({
'sid': np.array([1], dtype=np.uint32),
'amount': np.array([10.00], dtype=np.float64),
'declared_date': np.array([events[0].dt], dtype='datetime64[ns]'),
'ex_date': np.array([events[1].dt], dtype='datetime64[ns]'),
'pay_date': np.array([events[2].dt], dtype='datetime64[ns]'),
'record_date': np.array([events[2].dt], dtype='datetime64[ns]'),
})
writer.write(splits, mergers, dividends)
adjustment_reader = SQLiteAdjustmentReader(dbpath)
data_portal = create_data_portal_from_trade_history(
self.env.asset_finder,
self.trading_calendar,
self.instance_tmpdir,
self.sim_params,
{1: events},
)
data_portal._adjustment_reader = adjustment_reader
results = calculate_results(
self.sim_params,
self.env,
data_portal,
)
self.assertEqual(len(results), 6)
cumulative_returns = \
[event['cumulative_perf']['returns'] for event in results]
self.assertEqual(cumulative_returns, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
daily_returns = [event['daily_perf']['returns'] for event in results]
self.assertEqual(daily_returns, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
cash_flows = [event['daily_perf']['capital_used'] for event in results]
self.assertEqual(cash_flows, [0, 0, 0, 0, 0, 0])
cumulative_cash_flows = \
[event['cumulative_perf']['capital_used'] for event in results]
self.assertEqual(cumulative_cash_flows, [0, 0, 0, 0, 0, 0])
def test_no_dividend_at_simulation_end(self):
# post some trades in the market
events = factory.create_trade_history(
self.asset1,
[10, 10, 10, 10, 10, 10],
[100, 100, 100, 100, 100, 100],
oneday,
self.sim_params,
trading_calendar=self.trading_calendar,
)
dbpath = self.instance_tmpdir.getpath('adjustments.sqlite')
writer = SQLiteAdjustmentWriter(
dbpath,
MockDailyBarReader(),
self.trading_calendar.all_sessions,
)
splits = mergers = create_empty_splits_mergers_frame()
dividends = pd.DataFrame({
'sid': np.array([1], dtype=np.uint32),
'amount': np.array([10.00], dtype=np.float64),
'declared_date': np.array([events[-3].dt], dtype='datetime64[ns]'),
'ex_date': np.array([events[-2].dt], dtype='datetime64[ns]'),
'record_date': np.array([events[0].dt], dtype='datetime64[ns]'),
'pay_date': np.array(
[self.trading_calendar.next_session_label(
self.trading_calendar.minute_to_session_label(
events[-1].dt
)
)],
dtype='datetime64[ns]'),
})
writer.write(splits, mergers, dividends)
adjustment_reader = SQLiteAdjustmentReader(dbpath)
# Set the last day to be the last event
sim_params = create_simulation_parameters(
num_days=6,
capital_base=10e3,
start=self.sim_params.start_session,
end=self.sim_params.end_session
)
sim_params = sim_params.create_new(
sim_params.start_session,
events[-1].dt
)
data_portal = create_data_portal_from_trade_history(
self.env.asset_finder,
self.trading_calendar,
self.instance_tmpdir,
sim_params,
{1: events},
)
data_portal._adjustment_reader = adjustment_reader
# Simulate a transaction being filled prior to the ex_date.
txns = [create_txn(self.asset1, events[0].dt, 10.0, 100)]
results = calculate_results(
sim_params,