def test_portfolio_without_value():
    port = Portfolio(date='2018-03-19',
                     cash=1000.21,
                     positions=dict(GAZP=682, VSMO=145, TTLK=123))
    date = pd.to_datetime('2018-03-19').date()
    assert port.date == date
    assert f'Дата - {date}' in port.__str__()
    assert port.value[PORTFOLIO] == 3_699_111.41
    assert port.weight['VSMO'] == pytest.approx(0.691071)
Example #2
0
def case_optimizer():
    pos = dict(
        AKRN=679,
        BANEP=392,
        CHMF=173,
        GMKN=139,
        LKOH=123,
        LSNGP=59,
        LSRG=1341,
        MSRS=38,
        MSTT=2181,
        MTSS=1264,
        MVID=141,
        PMSBP=2715,
        RTKMP=1674,
        SNGSP=263,
        TTLK=234,
        UPRO=1272,
        VSMO=101,
    )
    port = Portfolio(date="2018-07-24", cash=102_262, positions=pos)
    save_max_trade = optimizer.MAX_TRADE
    save_cut_off = portfolio.VOLUME_CUT_OFF
    save_dividends_metrics = metrics.DividendsMetrics
    save_returns_metrics = metrics.ReturnsMetrics
    optimizer.MAX_TRADE = 0.006
    portfolio.VOLUME_CUT_OFF = 2.9 * optimizer.MAX_TRADE
    metrics.DividendsMetrics = BaseDividendsMetrics
    metrics.ReturnsMetrics = BaseReturnsMetrics
    opt = Optimizer(port)
    yield opt
    optimizer.MAX_TRADE = save_max_trade
    portfolio.VOLUME_CUT_OFF = save_cut_off
    optimizer.DividendsMetrics = save_dividends_metrics
    optimizer.ReturnsMetrics = save_returns_metrics
def make_test_portfolio():
    save_class = metrics.ReturnsMetrics
    metrics.ReturnsMetrics = BaseReturnsMetrics
    port = Portfolio(date='2018-03-19',
                     cash=1000.21,
                     positions=dict(GAZP=682, VSMO=145, TTLK=123))
    yield port
    metrics.ReturnsMetrics = save_class
def trading():
    """Распечатка всей аналитики, необходимой для управления портфелем"""
    port = Portfolio(date=DATE, cash=CASH, positions=POSITIONS)
    optimizer = Optimizer(port)
    print(optimizer.portfolio)
    print(optimizer.dividends_metrics)
    print(optimizer.returns_metrics)
    print(optimizer)
def test_yields_vs_dividends_metrics_predicted_false():
    positions = dict(GMKN=128,
                     MSRS=0,
                     SNGSP=0)
    port = Portfolio(date='2018-08-30',
                     cash=7_764,
                     positions=positions)
    metrics_yields = BaseDividendsMetrics(port).yields
    tickers = tuple(key for key in sorted(positions))
    itr = DividendsCasesIterator(tickers, pd.Timestamp('2018-08-30'), Freq.yearly)
    df = itr._real_dividends_yields(pd.Timestamp('2018-08-30'), labels=False)
    assert np.allclose(metrics_yields, df.iloc[:, 1:].T)
def test_yields_vs_dividends_metrics():
    positions = dict(MSRS=128,
                     PRTK=0,
                     MVID=0)
    port = Portfolio(date='2017-07-31',
                     cash=7_764,
                     positions=positions)
    metrics_yields = BaseDividendsMetrics(port).yields
    tickers = tuple(key for key in sorted(positions))
    itr = DividendsCasesIterator(tickers, pd.Timestamp('2018-07-31'), Freq.yearly)
    df = itr._real_dividends_yields(pd.Timestamp('2018-07-31'))
    assert np.allclose(metrics_yields, df.iloc[:, 1:-1].T)
def test_iter():
    iterator = DividendsCasesIterator(tuple(['AKRN', 'MTSS', 'PMSBP']), pd.Timestamp('2016-01-05'), Freq.yearly)
    df = next(iter(iterator))
    assert len(df) == 3
    assert df.iat[0, 0] == 'AKRN'
    assert df.iat[1, 0] == 'MTSS'
    assert df.iat[2, 0] == 'PMSBP'
    positions = dict(AKRN=128,
                     PMSBP=0,
                     MTSS=0)
    port = Portfolio(date='2015-01-05',
                     cash=7_764,
                     positions=positions)
    metrics_yields = BaseDividendsMetrics(port).yields
    assert np.allclose(metrics_yields.T, df.iloc[:, 1:-1])
def test_cases_vs_dividends_metrics():
    positions = dict(MSTT=128,
                     MVID=0,
                     ALRS=0)
    port = Portfolio(date='2017-06-28',
                     cash=7_764,
                     positions=positions)
    metrics_yields = BaseDividendsMetrics(port).yields
    tickers = tuple(key for key in sorted(positions))
    df = DividendsCasesIterator(tickers, pd.Timestamp('2018-07-31'), Freq.yearly).cases(pd.Timestamp('2018-06-28'))
    assert len(df) == 3
    assert df.iat[0, 0] == 'ALRS'
    assert df.iat[1, 0] == 'MSTT'
    assert df.iat[2, 0] == 'MVID'
    assert np.allclose(metrics_yields.T, df.iloc[:, 1:-1])
    assert not df['y'].isnull().any()
def test_cases_vs_dividends_metrics_predicted_false():
    positions = dict(PRTK=128,
                     AKRN=0,
                     LKOH=0)
    port = Portfolio(date='2018-07-31',
                     cash=7_764,
                     positions=positions)
    metrics_yields = BaseDividendsMetrics(port).yields
    tickers = tuple(key for key in sorted(positions))
    df = DividendsCasesIterator(tickers, pd.Timestamp('2018-07-31'), Freq.yearly).cases(pd.Timestamp('2018-07-31'),
                                                                                        False)
    assert len(df) == 3
    assert df.iat[0, 0] == 'AKRN'
    assert df.iat[1, 0] == 'LKOH'
    assert df.iat[2, 0] == 'PRTK'
    assert np.allclose(metrics_yields.T, df.iloc[:, 1:-1])
    assert df['y'].isnull().all()
    """Реализует основные метрики дивидендного потока для портфеля с помощью ML-модели

    ML-модели строится с помощью Gradient Boosting по данным с лагом о предыдущей дивидендной доходности и
    категориальной переменной на основе тикеров. СКО прогноза вычисляется с помощью кросс-валидации
    """
    @property
    def _tickers_real_after_tax_mean(self):
        portfolio = self._portfolio
        manager = ml.dividends.manager.DividendsMLDataManager(
            portfolio.positions[:-2], pd.Timestamp(portfolio.date))
        return manager.value.prediction_mean

    @property
    def _tickers_real_after_tax_std(self):
        portfolio = self._portfolio
        manager = ml.dividends.manager.DividendsMLDataManager(
            portfolio.positions[:-2], pd.Timestamp(portfolio.date))
        return manager.value.prediction_std


if __name__ == '__main__':
    from trading import POSITIONS, DATE, CASH

    port = Portfolio(date=DATE, cash=CASH, positions=POSITIONS)
    metrics = MLDividendsMetrics(port)
    dsr = (metrics.mean -
           metrics.beta * metrics.mean.iloc[-1]) / metrics.std.iloc[-1]
    print(dsr.sort_values(ascending=False))

    print(metrics.mean.iloc[-1] / metrics.std.iloc[-1])
Example #11
0
def case_metrics():
    positions = dict(AKRN=679, GMKN=139, LSRG=172, MSTT=2436, TTLK=234)
    port = Portfolio(date='2018-05-11', cash=311_587, positions=positions)
    return BaseDividendsMetrics(port)
Example #12
0
def test_end_of_month_shape():
    positions = dict(AKRN=679, GMKN=139, LSRG=172, MSTT=2436, TTLK=234)
    port = Portfolio(date='2018-07-30', cash=311_587, positions=positions)
    return BaseDividendsMetrics(port).real_after_tax.shape == (5, 7)
        t = ((t_score * s) / (2 * m)) ** 2
        """
        return (self.std[PORTFOLIO] * T_SCORE / 2 /
                self.mean[PORTFOLIO])**2 * 12

    @property
    def std_at_draw_down(self):
        """СКО стоимости портфеля в момент оптимизации
        """
        return self.std[PORTFOLIO] * (MONTH_TO_OPTIMIZE / 12)**0.5


if __name__ == '__main__':
    import trading

    port = Portfolio(date=trading.DATE,
                     cash=trading.CASH,
                     positions=trading.POSITIONS)
    metrics = MLReturnsMetrics(port)
    dsr = (metrics.mean -
           metrics.beta * metrics.mean.iloc[-1]) / metrics.std.iloc[-1]
    print(dsr.sort_values(ascending=False))

    print(metrics.mean.iloc[-1] / metrics.std.iloc[-1])
    t = 2 / (12**0.5)
    mean_gradient_ = metrics.mean - metrics.mean.iloc[-1]
    risk_gradient_ = metrics.std.iloc[-1] * (metrics.beta - 1)
    gr = (mean_gradient_ - t * risk_gradient_) / (t * metrics.std.iloc[-1])
    print(t)
    print(gr.sort_values(ascending=False))
def test_ticker_with_empty_history():
    port = Portfolio(date='2018-03-19',
                     cash=1000.21,
                     positions=dict(GAZP=682, VSMO=145, KUNF=123))
    assert port.price['KUNF'] == 0
Example #15
0
    def _tickers_real_after_tax_mean(self):
        return self.yields.mean(axis='index', skipna=False)

    @property
    def _tickers_real_after_tax_std(self):
        return self.yields.std(axis='index', ddof=1, skipna=False)


if __name__ == '__main__':
    pos = dict(AKRN=676,
               BANEP=392,
               CHMF=173,
               GMKN=139,
               LKOH=183,
               LSNGP=596,
               LSRG=2346,
               MSRS=128,
               MSTT=1823,
               MTSS=1348,
               MVID=141,
               PMSBP=2715,
               RTKMP=1674,
               SNGSP=263,
               TTLK=234,
               UPRO=1272,
               VSMO=101)
    port = Portfolio(date='2018-07-27',
                     cash=2_482 + 7_764 + 3_416,
                     positions=pos)
    print(BaseDividendsMetrics(port))
                 AFLT=0,
                 MSRS=699,
                 UPRO=1267,
                 PMSBP=1188 + 322 + 219,
                 CHMF=0,
                 GMKN=166 + 28,
                 VSMO=73,
                 RSTIP=87,
                 PHOR=0,
                 MRSB=0,
                 LKOH=123,
                 ENRU=319 + 148,
                 MVID=264 + 62)
CASH = 596_156 + 470_259 + 481_849
DATE = '2018-04-19'
TEST_PORTFOLIO = Portfolio(date=DATE, cash=CASH, positions=POSITIONS)


def test_drop_small_positions():
    df = drop_small_positions(TEST_PORTFOLIO)
    index = df.index
    assert len(df) == MAX_TABLE_ROWS + 2
    assert index[-1] == PORTFOLIO
    assert df[PORTFOLIO] == pytest.approx(39226178)
    assert index[-2] == OTHER
    assert df[OTHER] == pytest.approx(6523354)
    assert index[0] == 'RTKMP'
    assert df.iloc[0] == pytest.approx(11167816)
    assert index[-3] == 'MVID'
    assert df.iloc[-3] == pytest.approx(1310520)