Пример #1
0
    def __init__(self,
                 main_price,
                 init_capital,
                 orders,
                 cash,
                 shares,
                 freq=None,
                 year_freq=None,
                 levy_alpha=None,
                 risk_free=None,
                 required_return=None,
                 cutoff=None,
                 factor_returns=None,
                 incl_unrealized_stats=False):
        # Perform checks
        checks.assert_type(main_price, (pd.Series, pd.DataFrame))
        if checks.is_frame(main_price):
            checks.assert_type(init_capital, pd.Series)
            checks.assert_same(main_price.columns, init_capital.index)
        else:
            checks.assert_ndim(init_capital, 0)
        checks.assert_same_meta(main_price, cash)
        checks.assert_same_meta(main_price, shares)

        # Store passed arguments
        self._main_price = main_price
        self._init_capital = init_capital
        self._orders = orders
        self._cash = cash
        self._shares = shares
        self._incl_unrealized_stats = incl_unrealized_stats

        freq = main_price.vbt(freq=freq).freq
        if freq is None:
            raise ValueError(
                "Couldn't parse the frequency of index. You must set `freq`.")
        self._freq = freq

        year_freq = main_price.vbt.returns(year_freq=year_freq).year_freq
        if freq is None:
            raise ValueError("You must set `year_freq`.")
        self._year_freq = year_freq

        # Parameters
        self._levy_alpha = defaults.portfolio[
            'levy_alpha'] if levy_alpha is None else levy_alpha
        self._risk_free = defaults.portfolio[
            'risk_free'] if risk_free is None else risk_free
        self._required_return = defaults.portfolio[
            'required_return'] if required_return is None else required_return
        self._cutoff = defaults.portfolio[
            'cutoff'] if cutoff is None else cutoff
        self._factor_returns = defaults.portfolio[
            'factor_returns'] if factor_returns is None else factor_returns

        # Supercharge
        PandasIndexer.__init__(self, _indexing_func)
        self.wrapper = ArrayWrapper.from_obj(main_price, freq=freq)
Пример #2
0
    def __add__(self, other):
        checks.assert_type(other, self.__class__)
        checks.assert_same(self.price, other.price)

        return self.__class__(self.price, self.cash + other.cash,
                              self.shares + other.shares,
                              self.init_capital + other.init_capital,
                              self.paid_fees + other.paid_fees,
                              self.paid_slippage + other.paid_slippage)
Пример #3
0
def make_symmetric(arg):
    """Make `arg` symmetric.

    The index and columns of the resulting DataFrame will be identical.

    Requires the index and columns to have the same number of levels.

    Example:
        ```python-repl
        >>> import pandas as pd
        >>> from vectorbt.base.reshape_fns import make_symmetric

        >>> df = pd.DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['c', 'd'])

        >>> print(make_symmetric(df))
             a    b    c    d
        a  NaN  NaN  1.0  2.0
        b  NaN  NaN  3.0  4.0
        c  1.0  3.0  NaN  NaN
        d  2.0  4.0  NaN  NaN
        ```"""
    checks.assert_type(arg, (pd.Series, pd.DataFrame))
    arg = to_2d(arg)
    if isinstance(arg.index, pd.MultiIndex) or isinstance(
            arg.columns, pd.MultiIndex):
        checks.assert_type(arg.index, pd.MultiIndex)
        checks.assert_type(arg.columns, pd.MultiIndex)
        checks.assert_same(arg.index.nlevels, arg.columns.nlevels)
        names1, names2 = tuple(arg.index.names), tuple(arg.columns.names)
    else:
        names1, names2 = arg.index.name, arg.columns.name

    if names1 == names2:
        new_name = names1
    else:
        if isinstance(arg.index, pd.MultiIndex):
            new_name = tuple(zip(*[names1, names2]))
        else:
            new_name = (names1, names2)
    idx_vals = list(dict.fromkeys(np.concatenate((arg.index, arg.columns))))
    arg = arg.copy()
    if isinstance(arg.index, pd.MultiIndex):
        unique_index = pd.MultiIndex.from_tuples(idx_vals, names=new_name)
        arg.index.names = new_name
        arg.columns.names = new_name
    else:
        unique_index = pd.Index(idx_vals, name=new_name)
        arg.index.name = new_name
        arg.columns.name = new_name
    df_out = pd.DataFrame(index=unique_index, columns=unique_index)
    df_out.loc[:, :] = arg
    df_out[df_out.isnull()] = arg.transpose()
    return df_out
Пример #4
0
 def test_assert_same(self):
     index = ['x', 'y', 'z']
     columns = ['a', 'b', 'c']
     checks.assert_same(np.array([1, 2, 3]), np.array([1, 2, 3]))
     checks.assert_same(pd.Series([1, 2, 3], index=index), pd.Series([1, 2, 3], index=index))
     checks.assert_same(pd.DataFrame([[1, 2, 3]], columns=columns), pd.DataFrame([[1, 2, 3]], columns=columns))
     with pytest.raises(Exception) as e_info:
         checks.assert_same(np.array([1, 2]), np.array([1, 2, 3]))
Пример #5
0
 def test_assert_same(self):
     index = ['x', 'y', 'z']
     columns = ['a', 'b', 'c']
     checks.assert_same(np.array([1, 2, 3]), np.array([1, 2, 3]))
     checks.assert_same(pd.Series([1, 2, 3], index=index), pd.Series([1, 2, 3], index=index))
     checks.assert_same(pd.DataFrame([[1, 2, 3]], columns=columns), pd.DataFrame([[1, 2, 3]], columns=columns))
     try:
         checks.assert_same(np.array([1, 2]), np.array([1, 2, 3]))
         raise Exception
     except:
         pass
Пример #6
0
    def __add__(self, other):
        checks.assert_type(other, self.__class__)
        checks.assert_same(self.ts, other.ts)
        checks.assert_same(self.slippage, other.slippage)
        checks.assert_same(self.commission, other.commission)

        return self.__class__(self.ts, self.cash + other.cash,
                              self.shares + other.shares,
                              self.investment + other.investment,
                              self.slippage, self.commission)
Пример #7
0
    def __add__(self, other):
        checks.assert_type(other, self.__class__)
        checks.assert_same(self.price, other.price)
        checks.assert_same(self.data_freq, other.data_freq)
        checks.assert_same(self.year_freq, other.year_freq)
        checks.assert_same(self.risk_free, other.risk_free)
        checks.assert_same(self.required_return, other.required_return)
        checks.assert_same(self.cutoff, other.cutoff)
        checks.assert_same(self.factor_returns, other.factor_returns)

        return self.__class__(self.price,
                              self.cash + other.cash,
                              self.shares + other.shares,
                              self.init_capital + other.init_capital,
                              self.fees_paid + other.fees_paid,
                              self.slippage_paid + other.slippage_paid,
                              data_freq=self.data_freq,
                              year_freq=self.year_freq,
                              risk_free=self.risk_free,
                              required_return=self.required_return,
                              cutoff=self.cutoff,
                              factor_returns=self.factor_returns)
Пример #8
0
    def __init__(self, wrapper, records, layout=EventRecord):
        checks.assert_same(EventRecord._fields, layout._fields[:len(EventRecord)])  # subtype of EventRecord

        super().__init__(wrapper, records, layout, EventRecord.Column, EventRecord.CloseAt)