How to use the catalyst.testing.fixtures.ZiplineTestCase function in catalyst

To help you get started, we’ve selected a few catalyst examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github enigmampc / catalyst / tests / data / test_resample.py View on Github external
columns=OHLCV,
                    index=pd.to_datetime(['2016-03-16'], utc=True)),
    1003: DataFrame(EXPECTED_AGGREGATION[1003].iloc[[2, 5]].values,
                    columns=OHLCV,
                    index=pd.to_datetime(['2016-03-16', '2016-03-17'],
                                         utc=True)),
    1004: DataFrame(EXPECTED_AGGREGATION[1004].iloc[[2, 5]].values,
                    columns=OHLCV,
                    index=pd.to_datetime(['2016-03-16', '2016-03-17'],
                                         utc=True)),
}


class MinuteToDailyAggregationTestCase(WithBcolzEquityMinuteBarReader,
                                       WithBcolzFutureMinuteBarReader,
                                       ZiplineTestCase):

    #    March 2016
    # Su Mo Tu We Th Fr Sa
    #        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

    TRADING_ENV_MIN_DATE = START_DATE = pd.Timestamp(
        '2016-03-01', tz='UTC',
    )
    TRADING_ENV_MAX_DATE = END_DATE = pd.Timestamp(
        '2016-03-31', tz='UTC',
    )
github enigmampc / catalyst / tests / pipeline / test_engine.py View on Github external
expected_raw_data = self.raw_expected_values(
            col,
            start_date,
            end_date,
        )
        expected_labels = LabelArray(expected_raw_data, col.missing_value)
        expected_final_result = expected_labels.as_categorical_frame(
            index=run_dates,
            columns=self.asset_finder.retrieve_all(self.asset_finder.sids),
        )
        assert_frame_equal(result.c.unstack(), expected_final_result)


class WindowSafetyPropagationTestCase(WithSeededRandomPipelineEngine,
                                      ZiplineTestCase):

    SEEDED_RANDOM_PIPELINE_SEED = 5

    def test_window_safety_propagation(self):
        dates = self.trading_days[-30:]
        start_date, end_date = dates[[-10, -1]]

        col = TestingDataSet.float_col
        pipe = Pipeline(
            columns={
                'average_of_rank_plus_one': SimpleMovingAverage(
                    inputs=[col.latest.rank() + 1],
                    window_length=10,
                ),
                'average_of_aliased_rank_plus_one': SimpleMovingAverage(
                    inputs=[col.latest.rank().alias('some_alias') + 1],
github enigmampc / catalyst / tests / test_perf_tracking.py View on Github external
class TestDividendPerformanceHolidayStyle(TestDividendPerformance):

    # The holiday tests begins the simulation on the day
    # before Thanksgiving, so that the next trading day is
    # two days ahead. Any tests that hard code events
    # to be start + oneday will fail, since those events will
    # be skipped by the simulation.
    START_DATE = pd.Timestamp('2003-11-30', tz='utc')
    END_DATE = pd.Timestamp('2003-12-08', tz='utc')


class TestPositionPerformance(WithInstanceTmpDir,
                              WithTradingEnvironment,
                              ZiplineTestCase):

    def create_environment_stuff(self,
                                 num_days=4,
                                 sids=[1, 2],
                                 futures_sids=[3]):
        start = pd.Timestamp('2006-01-01', tz='utc')
        end = start + timedelta(days=num_days * 2)
        equities = make_simple_equity_info(sids, start, end)
        futures = pd.DataFrame.from_dict(
            {
                sid: {
                    'start_date': start,
                    'end_date': end,
                    'multiplier': 100,
                    'exchange': "TEST",
                }
github enigmampc / catalyst / tests / pipeline / test_statistical.py View on Github external
RollingSpearmanOfReturns(
                target=my_asset,
                returns_length=3,
                correlation_length=1,
            )

        with self.assertRaises(ValueError):
            RollingLinearRegressionOfReturns(
                target=my_asset,
                returns_length=3,
                regression_length=1,
            )


class StatisticalMethodsTestCase(WithSeededRandomPipelineEngine,
                                 ZiplineTestCase):
    sids = ASSET_FINDER_EQUITY_SIDS = Int64Index([1, 2, 3])
    START_DATE = Timestamp('2015-01-31', tz='UTC')
    END_DATE = Timestamp('2015-03-01', tz='UTC')

    @classmethod
    def init_class_fixtures(cls):
        super(StatisticalMethodsTestCase, cls).init_class_fixtures()

        # Using these start and end dates because they are a contigous span of
        # 5 days (Monday - Friday) and they allow for plenty of days to look
        # back on when computing correlations and regressions.
        cls.dates = dates = cls.trading_days
        cls.start_date_index = start_date_index = 14
        cls.end_date_index = end_date_index = 18
        cls.pipeline_start_date = cls.trading_days[start_date_index]
        cls.pipeline_end_date = cls.trading_days[end_date_index]
github enigmampc / catalyst / tests / pipeline / test_technical.py View on Github external
# Everything but the last row should be NaN.
        self.assertTrue(signal_ewma.iloc[:-1].isnull().all().all())

        # We're testing a single compute call, which we expect to be equivalent
        # to the last row of the frame we calculated with pandas.
        expected_signal = signal_ewma.values[-1]

        np.testing.assert_almost_equal(
            out,
            expected_signal,
            decimal=8
        )


class AnnualizedVolatilityTestCase(ZiplineTestCase):
    """
    Test Annualized Volatility
    """
    def test_simple_volatility(self):
        """
        Simple test for uniform returns should generate 0 volatility
        """
        nassets = 3
        ann_vol = AnnualizedVolatility()
        today = pd.Timestamp('2016', tz='utc')
        assets = np.arange(nassets, dtype=np.float64)
        returns = np.full((ann_vol.window_length, nassets),
                          0.004,
                          dtype=np.float64)
        out = np.empty(shape=(nassets,), dtype=np.float64)
github enigmampc / catalyst / tests / data / test_resample.py View on Github external
super(TestMinuteToSession, cls).init_class_fixtures()
        cls.equity_frames = {
            sid: frame for sid, frame in cls.make_equity_minute_bar_data()}

    def test_minute_to_session(self):
        for sid in self.ASSET_FINDER_EQUITY_SIDS:
            frame = self.equity_frames[sid]
            expected = EXPECTED_SESSIONS[sid]
            result = minute_frame_to_session_frame(frame, self.nyse_calendar)
            assert_almost_equal(expected.values,
                                result.values,
                                err_msg='sid={0}'.format(sid))


class TestResampleSessionBars(WithBcolzFutureMinuteBarReader,
                              ZiplineTestCase):

    TRADING_CALENDAR_STRS = ('us_futures',)
    TRADING_CALENDAR_PRIMARY_CAL = 'us_futures'

    ASSET_FINDER_FUTURE_SIDS = 1001, 1002, 1003, 1004

    START_DATE = pd.Timestamp('2016-03-16', tz='UTC')
    END_DATE = pd.Timestamp('2016-03-17', tz='UTC')
    NUM_SESSIONS = 2

    @classmethod
    def make_futures_info(cls):
        future_dict = {}

        for future_sid in cls.ASSET_FINDER_FUTURE_SIDS:
            future_dict[future_sid] = {
github enigmampc / catalyst / tests / pipeline / test_engine.py View on Github external
),
                    dates[start],
                    dates[stop],
                )
                self.assertEqual(set(results.columns), {'low', 'high'})
                iloc_bounds = slice(start, stop + 1)  # +1 to include end date

                low_results = results.unstack()['low']
                assert_frame_equal(low_results, low_base.iloc[iloc_bounds])

                high_results = results.unstack()['high']
                assert_frame_equal(high_results, high_base.iloc[iloc_bounds])


class SyntheticBcolzTestCase(WithAdjustmentReader,
                             ZiplineTestCase):
    first_asset_start = Timestamp('2015-04-01', tz='UTC')
    START_DATE = Timestamp('2015-01-01', tz='utc')
    END_DATE = Timestamp('2015-08-01', tz='utc')

    @classmethod
    def make_equity_info(cls):
        cls.equity_info = ret = make_rotating_equity_info(
            num_assets=6,
            first_start=cls.first_asset_start,
            frequency=cls.trading_calendar.day,
            periods_between_starts=4,
            asset_lifetime=8,
        )
        return ret

    @classmethod
github enigmampc / catalyst / tests / pipeline / test_statistical.py View on Github external
make_cascading_boolean_array,
    parameter_space,
)
from catalyst.testing.fixtures import (
    WithSeededRandomPipelineEngine,
    WithTradingEnvironment,
    ZiplineTestCase,
)
from catalyst.utils.numpy_utils import (
    bool_dtype,
    datetime64ns_dtype,
    float64_dtype,
)


class StatisticalBuiltInsTestCase(WithTradingEnvironment, ZiplineTestCase):
    sids = ASSET_FINDER_EQUITY_SIDS = Int64Index([1, 2, 3])
    START_DATE = Timestamp('2015-01-31', tz='UTC')
    END_DATE = Timestamp('2015-03-01', tz='UTC')

    @classmethod
    def init_class_fixtures(cls):
        super(StatisticalBuiltInsTestCase, cls).init_class_fixtures()

        day = cls.trading_calendar.day
        cls.dates = dates = date_range(
            '2015-02-01', '2015-02-28', freq=day, tz='UTC',
        )

        # Using these start and end dates because they are a contigous span of
        # 5 days (Monday - Friday) and they allow for plenty of days to look
        # back on when computing correlations and regressions.
github enigmampc / catalyst / tests / pipeline / test_quarters_estimates.py View on Github external
split_adjusted_at_end_boundary,
                cls.split_adjusted_after_end:
                split_adjusted_after_end_boundary}


class BlazeNextWithAdjustmentBoundaries(NextWithAdjustmentBoundaries):
    @classmethod
    def make_loader(cls, events, columns):
        return partial(BlazeNextSplitAdjustedEstimatesLoader,
                       bz.data(events),
                       columns,
                       split_adjustments_loader=cls.adjustment_reader,
                       split_adjusted_column_names=['estimate'])


class QuarterShiftTestCase(ZiplineTestCase):
    """
    This tests, in isolation, quarter calculation logic for shifting quarters
    backwards/forwards from a starting point.
    """
    def test_quarter_normalization(self):
        input_yrs = pd.Series(range(2011, 2015), dtype=np.int64)
        input_qtrs = pd.Series(range(1, 5), dtype=np.int64)
        result_years, result_quarters = split_normalized_quarters(
            normalize_quarters(input_yrs, input_qtrs)
        )
        # Can't use assert_series_equal here with check_names=False
        # because that still fails due to name differences.
        assert_equal(input_yrs, result_years)
        assert_equal(input_qtrs, result_quarters)
github enigmampc / catalyst / tests / data / bundles / test_core.py View on Github external
assert_is_none,
    assert_raises,
    assert_true,
)
from catalyst.utils.cache import dataframe_cache
from catalyst.utils.functional import apply
from catalyst.utils.calendars import TradingCalendar, get_calendar
import catalyst.utils.paths as pth


_1_ns = pd.Timedelta(1, unit='ns')


class BundleCoreTestCase(WithInstanceTmpDir,
                         WithDefaultDateBounds,
                         ZiplineTestCase):

    START_DATE = pd.Timestamp('2014-01-06', tz='utc')
    END_DATE = pd.Timestamp('2014-01-10', tz='utc')

    def init_instance_fixtures(self):
        super(BundleCoreTestCase, self).init_instance_fixtures()
        (self.bundles,
         self.register,
         self.unregister,
         self.ingest,
         self.load,
         self.clean) = _make_bundle_core()
        self.environ = {'ZIPLINE_ROOT': self.instance_tmpdir.path}

    def test_register_decorator(self):
        @apply