Example #1
0
    def test_frame_tz_localize(self):
        rng = date_range('1/1/2011', periods=100, freq='H')

        df = DataFrame({'a': 1}, index=rng)
        result = df.tz_localize('utc')
        expected = DataFrame({'a': 1}, rng.tz_localize('UTC'))
        assert result.index.tz.zone == 'UTC'
        tm.assert_frame_equal(result, expected)

        df = df.T
        result = df.tz_localize('utc', axis=1)
        assert result.columns.tz.zone == 'UTC'
        tm.assert_frame_equal(result, expected.T)
Example #2
0
    def test_series_frame_tz_localize(self):

        rng = date_range('1/1/2011', periods=100, freq='H')
        ts = Series(1, index=rng)

        result = ts.tz_localize('utc')
        self.assert_(result.index.tz.zone == 'UTC')

        df = DataFrame({'a': 1}, index=rng)
        result = df.tz_localize('utc')
        expected = DataFrame({'a': 1}, rng.tz_localize('UTC'))
        self.assert_(result.index.tz.zone == 'UTC')
        assert_frame_equal(result, expected)

        df = df.T
        result = df.tz_localize('utc', axis=1)
        self.assert_(result.columns.tz.zone == 'UTC')
        assert_frame_equal(result, expected.T)

        # Can't localize if already tz-aware
        rng = date_range('1/1/2011', periods=100, freq='H', tz='utc')
        ts = Series(1, index=rng)
        self.assertRaises(Exception, ts.tz_localize, 'US/Eastern')
    def test_series_frame_tz_localize(self):

        rng = date_range("1/1/2011", periods=100, freq="H")
        ts = Series(1, index=rng)

        result = ts.tz_localize("utc")
        self.assertEqual(result.index.tz.zone, "UTC")

        df = DataFrame({"a": 1}, index=rng)
        result = df.tz_localize("utc")
        expected = DataFrame({"a": 1}, rng.tz_localize("UTC"))
        self.assertEqual(result.index.tz.zone, "UTC")
        assert_frame_equal(result, expected)

        df = df.T
        result = df.tz_localize("utc", axis=1)
        self.assertEqual(result.columns.tz.zone, "UTC")
        assert_frame_equal(result, expected.T)

        # Can't localize if already tz-aware
        rng = date_range("1/1/2011", periods=100, freq="H", tz="utc")
        ts = Series(1, index=rng)
        tm.assertRaisesRegexp(TypeError, "Already tz-aware", ts.tz_localize, "US/Eastern")
Example #4
0
    def _standardize_index(
            self, df_in: pd.DataFrame, symbol: str=None, datatype: str=None,
            barsize: str=None, tz: str=None):
        """Normalize input DataFrame index to MarketDataBlock standard.
        """
        # Add or starndardize index names in the input.
        if isinstance(df_in.index, pd.MultiIndex):
            df_in.reset_index(inplace=True)

        # Rename ambiguous column names.
        df_in.columns = [
            col_rename.get(col.strip().lower(), col.strip().lower())
            for col in df_in.columns]

        # Insert Symbol, DataType, Barsize columns from arguments if not
        # found in the input dataframe.
        for col in MarketDataBlock.data_index:
            if col not in df_in.columns:
                if locals().get(col.lower(), None) is None:
                    raise KeyError(
                        'No {0} argument and no {0} column in the DataFrame.'
                        .format(col))
                df_in.insert(0, col, locals()[col.lower()])

        # Convert datetime strings to pandas DatetimeIndex
        df_in['TickerTime'] = pd.DatetimeIndex(
            df_in['TickerTime'].apply(pd.Timestamp))

        # Standardize BarSize strings
        df_in['BarSize'] = df_in['BarSize'].map(timedur_standardize)

        # Set index to class-defined MultiIndex
        df_in.set_index(MarketDataBlock.data_index, inplace=True)

        # Set time zone so all DatetimeIndex are tz-aware
        df_in_tz = df_in.index.levels[self.__class__.dtlevel].tz
        if df_in_tz is None or isinstance(df_in_tz, timezone) or \
           isinstance(df_in_tz, pytz._FixedOffset):
            # Input df has naive time index, or tzinfo is not pytz.timezone()
            if tz is None:
                raise ValueError(
                    'Argument tz=None, and TickerTime.tzinfo is None(naive),'
                    'datetime.timezone, or pytz._FixedOffset.')
            if df_in_tz is None:
                df_in = df_in.tz_localize(tz, level=self.__class__.dtlevel)
            else:
                df_in = df_in.tz_convert(tz, level=self.__class__.dtlevel)

        return df_in
Example #5
0
month = lambda x: np.random.choice([abc for abc in x],
                                   np.random.choice([1]))

contracts = np.ravel([[(''.join(month(string.letters[:26])) +
                        str(np.random.choice([14, 15, 16])))] * len(cols)
                      for x in xrange(len(source.columns) / len(cols) / 2)])

level_1 = len(source.columns) / len(contracts) * list(contracts)

numsyms = len(source.columns) / (len(set(level_1)) * len(cols))
underlyings = [''.join(sym(string.letters[:26])) for x in xrange(numsyms)]
level_0 = np.ravel([[sym] * len(set(level_1)) * len(cols) for sym in underlyings])

source.columns = pd.MultiIndex.from_tuples(zip(level_0, level_1, source.columns))
source.index = pd.date_range(start=dt.datetime.utcnow() - dt.timedelta(days=len(source.index) - 1),
                             end=dt.datetime.utcnow(), freq='D')

futdata = FuturesDataFrameSource(source.tz_localize('UTC'))


class FrontTrader(TradingAlgorithm):
    @roll(lambda x: x[x['open_interest'] == x['open_interest'].max()])
    def handle_data(self, data):
        for sym in data.keys():
            self.order((sym, data[sym]['contract']), 2)
        return data


bot = FrontTrader()
stats = bot.run(futdata)