def test_get_reports(mocker):
    id_1 = 'RX1'
    id_2 = 'RX2'

    mock_response = {'results': (
        Report.from_dict({'id': id_1, 'positionSourceType': 'Portfolio', 'positionSourceId': 'MP1',
                          'type': 'Portfolio Performance Analytics', 'parameters': {'transactionCostModel': 'FIXED'}}),
        Report.from_dict({'id': id_2, 'positionSourceType': 'Portfolio', 'positionSourceId': 'MP2',
                          'type': 'Portfolio Performance Analytics', 'parameters': {'transactionCostModel': 'FIXED'}})
    ), 'totalResults': 2}

    expected_response = (
        Report(id=id_1, positionSourceType='Portfolio', positionSourceId='MP1', type='Portfolio Performance Analytics',
               parameters=ReportParameters(transactionCostModel='FIXED')),
        Report(id=id_2, positionSourceType='Portfolio', positionSourceId='MP2', type='Portfolio Performance Analytics',
               parameters=ReportParameters(transactionCostModel='FIXED'))
    )

    # mock GsSession
    mocker.patch.object(
        GsSession.__class__,
        'default_value',
        return_value=GsSession.get(
            Environment.QA,
            'client_id',
            'secret'))
    mocker.patch.object(GsSession.current, '_get', return_value=mock_response)

    # run test
    response = GsReportApi.get_reports()
    GsSession.current._get.assert_called_with('/reports?limit=100', cls=Report)
    assert response == expected_response
Exemple #2
0
def test_update_report(mocker):
    id_1 = 'RX1'

    report = Report.from_dict({
        'id': id_1,
        'positionSourceType': 'Portfolio',
        'positionSourceId': 'MP25',
        'type': 'Portfolio Performance Analytics',
        'parameters': {
            'transactionCostModel': 'FIXED'
        }
    })

    # mock GsSession
    mocker.patch.object(GsSession.__class__,
                        'default_value',
                        return_value=GsSession.get(Environment.QA, 'client_id',
                                                   'secret'))
    mocker.patch.object(GsSession.current, '_put', return_value=report)

    # run test
    response = GsReportApi.update_report(report)
    GsSession.current._put.assert_called_with('/reports/{id}'.format(id=id_1),
                                              report,
                                              cls=Report)
    assert response == report
def test_financial_conditions_index():
    data = {
        'pnl': [
            101,
            102,
            103
        ],
        'date': [
            '2020-01-01',
            '2020-01-02',
            '2020-01-03'
        ]
    }
    idx = pd.date_range('2020-01-01', freq='D', periods=3)
    df = MarketDataResponseFrame(data=data, index=idx)
    df.dataset_ids = ('PNL',)
    replace = Replacer()

    # mock PerformanceReport.get_pnl()
    mock = replace('gs_quant.markets.report.PerformanceReport.get_pnl', Mock())
    mock.return_value = df

    # mock GsPortfolioApi.get_reports()
    mock = replace('gs_quant.api.gs.portfolios.GsPortfolioApi.get_reports', Mock())
    mock.return_value = [Report.from_dict({'id': 'RP1', 'positionSourceType': 'Portfolio', 'positionSourceId': 'MP1',
                                          'type': 'Portfolio Performance Analytics',
                                           'parameters': {'transactionCostModel': 'FIXED'}})]

    with DataContext(datetime.date(2020, 1, 1), datetime.date(2019, 1, 3)):
        actual = mp.pnl('MP1')
        assert actual.index.equals(idx)
        assert all(actual.values == data['pnl'])
    replace.restore()
def test_normalized_performance_short():
    idx = pd.date_range('2020-01-02', freq='D', periods=3)
    replace = Replacer()
    expected = {"Short": pd.Series(data=[1, 1 / 2, 1 / 3], index=idx,
                                   name='normalizedPerformance', dtype='float64'),
                "Long": pd.Series(data=[1, 2, 3], index=idx,
                                  name='normalizedPerformance', dtype='float64'),
                None: pd.Series(data=[1, (2 + 1 / 2) / 2, (3 + 1 / 3) / 2], index=idx,
                                name='normalizedPerformance', dtype='float64')}

    mock = replace('gs_quant.api.gs.portfolios.GsPortfolioApi.get_reports', Mock())
    mock.return_value = [
        Report.from_dict({'id': 'RP1', 'positionSourceType': 'Portfolio', 'positionSourceId': 'MP1',
                          'type': 'Portfolio Performance Analytics',
                          'parameters': {'transactionCostModel': 'FIXED'}})]
    # mock PerformanceReport.get_portfolio_constituents()
    mock = replace('gs_quant.markets.report.PerformanceReport.get_portfolio_constituents', Mock())
    mock.return_value = MarketDataResponseFrame(data=constituents_data_l_s, dtype="float64")

    # mock PerformanceReport.get()
    mock = replace('gs_quant.markets.report.PerformanceReport.get', Mock())
    mock.return_value = PerformanceReport(report_id='RP1',
                                          position_source_type='Portfolio',
                                          position_source_id='MP1',
                                          report_type='Portfolio Performance Analytics',
                                          parameters=ReportParameters(transaction_cost_model='FIXED'))

    for k, v in expected.items():
        with DataContext(datetime.date(2020, 1, 1), datetime.date(2019, 1, 3)):
            actual = mr.normalized_performance('MP1', k)
            assert all((actual.values - v.values) < 0.01)
    replace.restore()
def test_get_reports(mocker):
    mock_portfolio = TargetPortfolio(id='MP',
                                     currency='USD',
                                     name='Example Port')
    mock_reports = (Report.from_dict({
        'id': 'PPAID',
        'positionSourceType': 'Portfolio',
        'positionSourceId': 'MP',
        'type': 'Portfolio Performance Analytics',
        'parameters': {
            'transactionCostModel': 'FIXED'
        },
        'percentageComplete': 0,
        'status': 'new'
    }),
                    Report.from_dict({
                        'id': 'PFRID',
                        'positionSourceType': 'Portfolio',
                        'positionSourceId': 'MP',
                        'type': 'Portfolio Factor Risk',
                        'parameters': {
                            'riskModel': 'AXUS4M',
                            'transactionCostModel': 'FIXED'
                        },
                        'percentageComplete': 0,
                        'status': 'new'
                    }))

    mocker.patch.object(GsPortfolioApi,
                        'get_portfolio',
                        return_value=mock_portfolio)
    mocker.patch.object(GsPortfolioApi,
                        'get_position_dates',
                        return_value=[dt.date(2020, 1, 1)])
    mocker.patch.object(GsPortfolioApi,
                        'get_positions_for_date',
                        return_value=None)
    mocker.patch.object(GsPortfolioApi,
                        'get_reports',
                        return_value=mock_reports)

    # run test
    pm = PortfolioManager('MP')
    reports = pm.get_reports()
    assert len(reports) == 2
    assert isinstance(reports[0], PerformanceReport)
    assert isinstance(reports[1], FactorRiskReport)
Exemple #6
0
def test_normalized_performance_default_aum():
    idx = pd.date_range('2020-01-02', freq='D', periods=3)
    expected = pd.Series(data=[1, 1 / 0.8, 1 / 0.6],
                         index=idx,
                         name='normalizedPerformance',
                         dtype='float64')

    with DataContext(datetime.date(2020, 1, 1), datetime.date(2019, 1, 3)):

        df = MarketDataResponseFrame(data=ppa_data, dtype="float64")
        replace = Replacer()

        # mock GsPortfolioApi.get_reports()
        mock = replace('gs_quant.api.gs.portfolios.GsPortfolioApi.get_reports',
                       Mock())
        mock.return_value = [
            Report.from_dict({
                'id': 'RP1',
                'positionSourceType': 'Portfolio',
                'positionSourceId': 'MP1',
                'type': 'Portfolio Performance Analytics',
                'parameters': {
                    'transactionCostModel': 'FIXED'
                }
            })
        ]

        # mock PerformanceReport.get_many_measures()
        mock = replace(
            'gs_quant.markets.report.PerformanceReport.get_many_measures',
            Mock())
        mock.return_value = df

        # mock PerformanceReport.get_custom_aum()
        mock = replace(
            'gs_quant.api.gs.portfolios.GsPortfolioApi.get_custom_aum', Mock())
        mock.return_value = aum

        # mock PerformanceReport.get()
        mock = replace('gs_quant.markets.report.PerformanceReport.get', Mock())
        mock.return_value = PerformanceReport(
            report_id='RP1',
            position_source_type='Portfolio',
            position_source_id='MP1',
            report_type='Portfolio Performance Analytics',
            parameters=ReportParameters(transaction_cost_model='FIXED'))

        mock = replace(
            'gs_quant.api.gs.portfolios.GsPortfolioApi.get_portfolio', Mock())
        mock.return_value = Portfolio('USD', 'P1', id_='MP1')

        actual = mr.normalized_performance('MP1', None)
        assert all(actual.values == expected.values)
        replace.restore()
Exemple #7
0
def test_normalized_performance_no_custom_aum():
    with DataContext(datetime.date(2020, 1, 1), datetime.date(2019, 1, 3)):
        df = MarketDataResponseFrame(data=ppa_data, dtype="float64")
        replace = Replacer()

        # mock GsPortfolioApi.get_reports()
        mock = replace('gs_quant.api.gs.portfolios.GsPortfolioApi.get_reports',
                       Mock())
        mock.return_value = [
            Report.from_dict({
                'id': 'RP1',
                'positionSourceType': 'Portfolio',
                'positionSourceId': 'MP1',
                'type': 'Portfolio Performance Analytics',
                'parameters': {
                    'transactionCostModel': 'FIXED'
                }
            })
        ]

        # mock PerformanceReport.get_many_measures()
        mock = replace(
            'gs_quant.markets.report.PerformanceReport.get_many_measures',
            Mock())
        mock.return_value = df

        # mock PerformanceReport.get_portfolio_constituents()
        mock = replace(
            'gs_quant.markets.report.PerformanceReport.get_portfolio_constituents',
            Mock())
        mock.return_value = MarketDataResponseFrame(data=constituents_data,
                                                    dtype="float64")

        # mock PerformanceReport.get_custom_aum()
        mock = replace(
            'gs_quant.api.gs.portfolios.GsPortfolioApi.get_custom_aum', Mock())
        mock.return_value = pd.DataFrame({})

        # mock PerformanceReport.get()
        mock = replace('gs_quant.markets.report.PerformanceReport.get', Mock())
        mock.return_value = PerformanceReport(
            report_id='RP1',
            position_source_type='Portfolio',
            position_source_id='MP1',
            report_type='Portfolio Performance Analytics',
            parameters=ReportParameters(transaction_cost_model='FIXED'))

        with pytest.raises(MqError):
            mr.normalized_performance('MP1', 'Custom AUM')
        replace.restore()
def test_get_short_pnl():
    idx = pd.date_range('2020-01-02', freq='D', periods=3)
    replace = Replacer()
    expected = pd.Series(data=[0, -2, -2],
                         index=idx,
                         name='shortPnl',
                         dtype='float64')

    mock = replace('gs_quant.api.gs.portfolios.GsPortfolioApi.get_reports',
                   Mock())
    mock.return_value = [
        Report.from_dict({
            'id': 'RP1',
            'positionSourceType': 'Portfolio',
            'positionSourceId': 'MP1',
            'type': 'Portfolio Performance Analytics',
            'parameters': {
                'transactionCostModel': 'FIXED'
            }
        })
    ]
    # mock PerformanceReport.get_portfolio_constituents()
    mock = replace(
        'gs_quant.markets.report.PerformanceReport.get_portfolio_constituents',
        Mock())
    mock.return_value = MarketDataResponseFrame(data=pnl_data_l_s)

    # mock PerformanceReport.get()
    mock = replace('gs_quant.markets.report.PerformanceReport.get', Mock())
    mock.return_value = PerformanceReport(
        report_id='RP1',
        position_source_type='Portfolio',
        position_source_id='MP1',
        report_type='Portfolio Performance Analytics',
        parameters=ReportParameters(transaction_cost_model='FIXED'))

    with DataContext(datetime.date(2020, 1, 1), datetime.date(2019, 1, 3)):
        actual = mr.short_pnl('MP1')
        assert all(actual.values == expected.values)
    replace.restore()
def test_get_long_pnl_empty():
    replace = Replacer()
    expected = pd.Series(dtype=float)

    mock = replace('gs_quant.api.gs.portfolios.GsPortfolioApi.get_reports',
                   Mock())
    mock.return_value = [
        Report.from_dict({
            'id': 'RP1',
            'positionSourceType': 'Portfolio',
            'positionSourceId': 'MP1',
            'type': 'Portfolio Performance Analytics',
            'parameters': {
                'transactionCostModel': 'FIXED'
            }
        })
    ]
    # mock PerformanceReport.get_portfolio_constituents()
    mock = replace(
        'gs_quant.markets.report.PerformanceReport.get_portfolio_constituents',
        Mock())
    mock.return_value = MarketDataResponseFrame(data=constituents_data_s)

    # mock PerformanceReport.get()
    mock = replace('gs_quant.markets.report.PerformanceReport.get', Mock())
    mock.return_value = PerformanceReport(
        report_id='RP1',
        position_source_type='Portfolio',
        position_source_id='MP1',
        report_type='Portfolio Performance Analytics',
        parameters=ReportParameters(transaction_cost_model='FIXED'))

    with DataContext(datetime.date(2020, 1, 1), datetime.date(2019, 1, 3)):
        actual = mr.long_pnl('MP1')
        assert all(actual.values == expected.values)
    replace.restore()
def test_run_reports(mocker):
    mock_portfolio = TargetPortfolio(id='MP',
                                     currency='USD',
                                     name='Example Port')
    mock_reports = (Report.from_dict({
        'id': 'PPAID',
        'positionSourceType': 'Portfolio',
        'positionSourceId': 'MP',
        'type': 'Portfolio Performance Analytics',
        'parameters': {
            'transactionCostModel': 'FIXED'
        },
        'percentageComplete': 0,
        'status': 'new'
    }), )
    mock_report_jobs = ({
        'startDate': '2020-01-01',
        'endDate': '2020-03-02',
        'id': 'jobId1',
        'createdTime': '2021-05-18T17:08:18.72Z',
        'reportType': 'Portfolio Factor Risk'
    }, {
        'startDate': '2020-05-01',
        'endDate': '2020-07-02',
        'id': 'jobId1',
        'createdTime': '2020-05-18T17:08:18.72Z',
        'reportType': 'Portfolio Factor Risk'
    })
    mock_report_job = {
        'startDate': '2020-01-01',
        'endDate': '2020-03-02',
        'id': 'jobId1',
        'createdTime': '2021-05-18T17:08:18.72Z',
        'reportType': 'Portfolio Factor Risk',
        'status': 'done'
    }
    mock_results = [{
        'date': "2019-08-27",
        'factor': "United States",
        'factorCategory': "Country",
        'pnl': -162.93571064768423,
        'exposure': 19878.043518298073,
        'sensitivity': 52.7507947211687,
        'proportionOfRisk': 0.050898995661382604
    }]

    mocker.patch.object(GsPortfolioApi,
                        'get_portfolio',
                        return_value=mock_portfolio)
    mocker.patch.object(GsPortfolioApi, 'schedule_reports', return_value='')
    mocker.patch.object(GsPortfolioApi,
                        'get_position_dates',
                        return_value=[dt.date(2020, 1, 1)])
    mocker.patch.object(GsPortfolioApi,
                        'get_positions_for_date',
                        return_value=None)
    mocker.patch.object(GsPortfolioApi,
                        'get_reports',
                        return_value=mock_reports)
    mocker.patch.object(GsReportApi,
                        'get_report_jobs',
                        return_value=mock_report_jobs)
    mocker.patch.object(GsReportApi,
                        'get_report_job',
                        return_value=mock_report_job)
    mocker.patch.object(GsReportApi,
                        'get_risk_factor_data_results',
                        return_value=mock_results)

    # run test
    pm = PortfolioManager('MP')
    pm.run_reports(is_async=False)
Exemple #11
0
def test_normalized_performance():
    idx = pd.date_range('2020-01-02', freq='D', periods=3)
    expected = {
        RiskAumSource.Net:
        pd.Series(data=[1, 1 + 2 / 4, 1 + 6 / 6],
                  index=idx,
                  name='normalizedPerformance',
                  dtype='float64'),
        RiskAumSource.Gross:
        pd.Series(data=[1, 1 + 2 / 1.2, 1 + 6 / 1.3],
                  index=idx,
                  name='normalizedPerformance',
                  dtype='float64'),
        RiskAumSource.Long:
        pd.Series(data=[1, 1 + 2 / 1.2, 1 + 6 / 1.3],
                  index=idx,
                  name='normalizedPerformance',
                  dtype='float64'),
        RiskAumSource.Short:
        pd.Series(data=[1, 1 + 2 / 1.2, 1 + 6 / 1.3],
                  index=idx,
                  name='normalizedPerformance',
                  dtype='float64'),
        RiskAumSource.Custom_AUM:
        pd.Series(data=[1, 1 + 2 / 2.2, 1 + 6 / 2.4],
                  index=idx,
                  name='normalizedPerformance',
                  dtype='float64')
    }

    with DataContext(datetime.date(2020, 1, 1), datetime.date(2019, 1, 3)):
        for k, v in expected.items():
            df = MarketDataResponseFrame(data=ppa_data, dtype="float64")
            replace = Replacer()

            # mock GsPortfolioApi.get_reports()
            mock = replace(
                'gs_quant.api.gs.portfolios.GsPortfolioApi.get_reports',
                Mock())
            mock.return_value = [
                Report.from_dict({
                    'id': 'RP1',
                    'positionSourceType': 'Portfolio',
                    'positionSourceId': 'MP1',
                    'type': 'Portfolio Performance Analytics',
                    'parameters': {
                        'transactionCostModel': 'FIXED'
                    }
                })
            ]
            # mock PerformanceReport.get_portfolio_constituents()
            mock = replace(
                'gs_quant.markets.report.PerformanceReport.get_portfolio_constituents',
                Mock())
            mock.return_value = MarketDataResponseFrame(data=constituents_data,
                                                        dtype="float64")

            # mock PerformanceReport.get_many_measures()
            mock = replace(
                'gs_quant.markets.report.PerformanceReport.get_many_measures',
                Mock())
            mock.return_value = df

            # mock PerformanceReport.get_custom_aum()
            mock = replace(
                'gs_quant.api.gs.portfolios.GsPortfolioApi.get_custom_aum',
                Mock())
            mock.return_value = aum

            # mock PerformanceReport.get()
            mock = replace('gs_quant.markets.report.PerformanceReport.get',
                           Mock())
            mock.return_value = PerformanceReport(
                report_id='RP1',
                position_source_type='Portfolio',
                position_source_id='MP1',
                report_type='Portfolio Performance Analytics',
                parameters=ReportParameters(transaction_cost_model='FIXED'))

            actual = mr.normalized_performance('MP1', k.value)
            assert all(actual.values == v.values)
            replace.restore()