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
|
|
|
import random |
16
|
|
|
|
17
|
|
|
import pandas as pd |
18
|
|
|
import numpy as np |
19
|
|
|
from numpy.testing import assert_almost_equal |
20
|
|
|
from unittest import TestCase |
21
|
|
|
from zipline.utils.munge import bfill, ffill |
22
|
|
|
|
23
|
|
|
|
24
|
|
|
class MungeTests(TestCase): |
25
|
|
|
def test_bfill(self): |
|
|
|
|
26
|
|
|
# test ndim=1 |
27
|
|
|
N = 100 |
28
|
|
|
s = pd.Series(np.random.randn(N)) |
29
|
|
|
mask = random.sample(range(N), 10) |
30
|
|
|
s.iloc[mask] = np.nan |
31
|
|
|
|
32
|
|
|
correct = s.bfill().values |
33
|
|
|
test = bfill(s.values) |
34
|
|
|
assert_almost_equal(correct, test) |
35
|
|
|
|
36
|
|
|
# test ndim=2 |
37
|
|
|
df = pd.DataFrame(np.random.randn(N, N)) |
38
|
|
|
df.iloc[mask] = np.nan |
39
|
|
|
correct = df.bfill().values |
40
|
|
|
test = bfill(df.values) |
41
|
|
|
assert_almost_equal(correct, test) |
42
|
|
|
|
43
|
|
|
def test_ffill(self): |
|
|
|
|
44
|
|
|
# test ndim=1 |
45
|
|
|
N = 100 |
46
|
|
|
s = pd.Series(np.random.randn(N)) |
47
|
|
|
mask = random.sample(range(N), 10) |
48
|
|
|
s.iloc[mask] = np.nan |
49
|
|
|
|
50
|
|
|
correct = s.ffill().values |
51
|
|
|
test = ffill(s.values) |
52
|
|
|
assert_almost_equal(correct, test) |
53
|
|
|
|
54
|
|
|
# test ndim=2 |
55
|
|
|
df = pd.DataFrame(np.random.randn(N, N)) |
56
|
|
|
df.iloc[mask] = np.nan |
57
|
|
|
correct = df.ffill().values |
58
|
|
|
test = ffill(df.values) |
59
|
|
|
assert_almost_equal(correct, test) |
60
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.