Completed
Pull Request — master (#867)
by Joe
02:09
created

scripts.CachedObjectTestCase   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 14
Duplicated Lines 0 %
Metric Value
dl 0
loc 14
rs 10
wmc 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A test_cached_object() 0 12 2
1
#
2
# Copyright 2015 Quantopian, Inc.
3
#
4
# Licensed under the Apache License, Version 2.0 (the "License");
5
# you may not use this file except in compliance with the License.
6
# You may obtain a copy of the License at
7
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
import datetime
17
import logbook
18
import os
19
import pickle
20
import pytz
21
22
import sys
23
sys.path.insert(0, '.')  # noqa
24
25
from zipline.finance.blotter import Blotter, Order
26
from zipline.finance.commission import PerShare, PerTrade, PerDollar
27
from zipline.finance.performance.period import PerformancePeriod
28
from zipline.finance.performance.position import Position
29
from zipline.finance.performance.position_tracker import PositionTracker
30
from zipline.finance.performance.tracker import PerformanceTracker
31
from zipline.finance.risk.cumulative import RiskMetricsCumulative
32
from zipline.finance.risk.period import RiskMetricsPeriod
33
from zipline.finance.risk.report import RiskReport
34
from zipline.finance.slippage import (
35
    FixedSlippage,
36
    Transaction,
37
    VolumeShareSlippage
38
)
39
from zipline.protocol import Account
40
from zipline.protocol import Portfolio
41
from zipline.protocol import Position as ProtocolPosition
42
43
44
from zipline.finance.trading import SimulationParameters
45
46
from zipline.utils import factory
47
from zipline.utils.serialization_utils import VERSION_LABEL
48
49
base_state_dir = 'tests/resources/saved_state_archive'
50
if not os.path.exists(base_state_dir):
51
    os.makedirs(base_state_dir)
52
53
54
sim_params_daily = SimulationParameters(
55
    datetime.datetime(2013, 6, 19, tzinfo=pytz.UTC),
56
    datetime.datetime(2013, 6, 19, tzinfo=pytz.UTC),
57
    10000,
58
    emission_rate='daily')
59
60
61
sim_params_minute = SimulationParameters(
62
    datetime.datetime(2013, 6, 19, tzinfo=pytz.UTC),
63
    datetime.datetime(2013, 6, 19, tzinfo=pytz.UTC),
64
    10000,
65
    emission_rate='minute')
66
67
68
returns = factory.create_returns_from_list(
69
    [1.0], sim_params_daily)
70
71
72
argument_list = [
73
    (Blotter, ()),
74
    (Order, (datetime.datetime(2013, 6, 19), 8554, 100)),
75
    (PerShare, ()),
76
    (PerTrade, ()),
77
    (PerDollar, ()),
78
    (PerformancePeriod, (10000,)),
79
    (Position, (8554,)),
80
    (PositionTracker, ()),
81
    (PerformanceTracker, (sim_params_minute,)),
82
    (RiskMetricsCumulative, (sim_params_minute,)),
83
    (RiskMetricsPeriod, (returns.index[0], returns.index[0], returns)),
84
    (RiskReport, (returns, sim_params_minute)),
85
    (FixedSlippage, ()),
86
    (Transaction, (8554, 10, datetime.datetime(2013, 6, 19), 100, "0000")),
87
    (VolumeShareSlippage, ()),
88
    (Account, ()),
89
    (Portfolio, ()),
90
    (ProtocolPosition, (8554,))
91
]
92
93
94
def write_state_to_disk(cls, state, emission_rate=None):
95
    state_dir = cls.__module__ + '.' + cls.__name__
96
97
    full_dir = base_state_dir + '/' + state_dir
98
99
    if not os.path.exists(full_dir):
100
        os.makedirs(full_dir)
101
102
    if emission_rate is not None:
103
        name = 'State_Version_' + emission_rate + \
104
            str(state['obj_state'][VERSION_LABEL])
105
    else:
106
        name = 'State_Version_' + str(state['obj_state'][VERSION_LABEL])
107
108
    full_path = full_dir + '/' + name
109
110
    f = open(full_path, 'w')
111
112
    pickle.dump(state, f)
113
114
    f.close()
115
116
117
def generate_object_state(cls, initargs):
118
119
    obj = cls(*initargs)
120
    state = obj.__getstate__()
121
    if hasattr(obj, '__getinitargs__'):
122
        initargs = obj.__getinitargs__()
123
    else:
124
        initargs = None
125
    if hasattr(obj, '__getnewargs__'):
126
        newargs = obj.__getnewargs__()
127
    else:
128
        newargs = None
129
130
    on_disk_state = {
131
        'obj_state': state,
132
        'initargs': initargs,
133
        'newargs': newargs
134
    }
135
136
    write_state_to_disk(cls, on_disk_state)
137
138
139
if __name__ == "__main__":
140
    logbook.StderrHandler().push_application()
141
142
    for args in argument_list:
143
        generate_object_state(*args)
144