예제 #1
0
def test_set_position_target():
    factor_report = FactorRiskReport(
        report_id='PFRID',
        position_source_type=PositionSourceType.Portfolio,
        position_source_id='PORTFOLIOID',
        report_type=ReportType.Portfolio_Factor_Risk,
        parameters=ReportParameters(fx_hedged=True, risk_model='AXUS4M'),
        status=ReportStatus.done)
    factor_report.set_position_target('MA3FMSN9VNMD')
    assert factor_report.position_source_type == PositionSourceType.Asset
    assert factor_report.type == ReportType.Asset_Factor_Risk
예제 #2
0
def _get_factor_data(report_id: str, factor_name: str,
                     query_type: QueryType) -> pd.Series:
    # Check params
    report = FactorRiskReport.get(report_id)
    if factor_name not in ['Factor', 'Specific', 'Total']:
        if query_type in [QueryType.DAILY_RISK, QueryType.ANNUAL_RISK]:
            raise MqValueError(
                'Please pick a factor name from the following: ["Total", "Factor", "Specific"]'
            )
        model = FactorRiskModel.get(report.get_risk_model_id())
        factor = model.get_factor(factor_name)
        factor_name = factor.name

    # Extract relevant data for each date
    col_name = query_type.value.replace(' ', '')
    col_name = decapitalize(col_name)
    data_type = decapitalize(
        col_name[6:]) if col_name.startswith('factor') else col_name

    factor_data = report.get_results(factors=[factor_name],
                                     start_date=DataContext.current.start_date,
                                     end_date=DataContext.current.end_date,
                                     return_format=ReturnFormat.JSON)
    factor_exposures = [{
        'date': d['date'],
        col_name: d[data_type]
    } for d in factor_data if d.get(data_type)]

    # Create and return timeseries
    df = pd.DataFrame(factor_exposures)
    if not df.empty:
        df.set_index('date', inplace=True)
        df.index = pd.to_datetime(df.index)
    return _extract_series_from_df(df, query_type)
예제 #3
0
 def get_factor_risk_report(self,
                            risk_model_id: str = None,
                            fx_hedged: bool = None) -> FactorRiskReport:
     if self.positioned_entity_type in [
             EntityType.PORTFOLIO, EntityType.ASSET
     ]:
         position_source_type = self.positioned_entity_type.value.capitalize(
         )
         reports = GsReportApi.get_reports(
             limit=100,
             position_source_type=position_source_type,
             position_source_id=self.id,
             report_type=f'{position_source_type} Factor Risk')
         if fx_hedged:
             reports = [
                 report for report in reports
                 if report.parameters.fx_hedged == fx_hedged
             ]
         if risk_model_id:
             reports = [
                 report for report in reports
                 if report.parameters.risk_model == risk_model_id
             ]
         if len(reports) > 1:
             raise MqError(
                 f'This {position_source_type} has more than one factor risk report that matches '
                 'your parameters. Please specify the risk model ID and fxHedged value in the '
                 'function parameters.')
         if len(reports) == 0:
             raise MqError(
                 f'This {position_source_type} has no factor risk reports that match your parameters.'
             )
         return FactorRiskReport.from_target(reports[0])
     raise NotImplementedError
예제 #4
0
파일: entity.py 프로젝트: shlff/gs-quant
 def get_reports(self) -> List[Report]:
     if self.positioned_entity_type == EntityType.PORTFOLIO:
         reports_as_target = GsPortfolioApi.get_reports(portfolio_id=self.id)
         report_objects = []
         for report in reports_as_target:
             if report.type == ReportType.Portfolio_Performance_Analytics:
                 report_objects.append(PerformanceReport.from_target(report))
             elif report.type in [ReportType.Portfolio_Factor_Risk, ReportType.Asset_Factor_Risk]:
                 report_objects.append(FactorRiskReport.from_target(report))
             else:
                 report_objects.append(Report.from_target(report))
         return report_objects
     raise NotImplementedError
예제 #5
0
 def get_factor_risk_reports(self, fx_hedged: bool = None) -> List[FactorRiskReport]:
     if self.positioned_entity_type in [EntityType.PORTFOLIO, EntityType.ASSET]:
         position_source_type = self.positioned_entity_type.value.capitalize()
         reports = GsReportApi.get_reports(limit=100,
                                           position_source_type=position_source_type,
                                           position_source_id=self.id,
                                           report_type=f'{position_source_type} Factor Risk')
         if fx_hedged:
             reports = [report for report in reports if report.parameters.fx_hedged == fx_hedged]
         if len(reports) == 0:
             raise MqError(f'This {position_source_type} has no factor risk reports that match your parameters.')
         return [FactorRiskReport.from_target(report) for report in reports]
     raise NotImplementedError
예제 #6
0
 def get_reports(self) -> List[Report]:
     """
     Get a list of all reports associated with the portfolio
     :return: list of Report objects
     """
     reports = []
     reports_as_targets = GsPortfolioApi.get_reports(self.__portfolio_id)
     for report_target in reports_as_targets:
         if report_target.type in [
                 ReportType.Portfolio_Factor_Risk,
                 ReportType.Asset_Factor_Risk
         ]:
             reports.append(FactorRiskReport.from_target(report_target))
         if report_target.type == ReportType.Portfolio_Performance_Analytics:
             reports.append(PerformanceReport.from_target(report_target))
     return reports
예제 #7
0
def test_get_factor_risk_report(mocker):
    # 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=Report(
                            id='PFRID',
                            position_source_type=PositionSourceType.Portfolio,
                            position_source_id='PORTFOLIOID',
                            parameters=None,
                            type=ReportType.Portfolio_Factor_Risk,
                            status=ReportStatus.done))
    # run test
    response = FactorRiskReport.get('PFRID')
    assert response.type == ReportType.Portfolio_Factor_Risk
예제 #8
0
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
"""

import pytest

from gs_quant.api.gs.data import GsDataApi
from gs_quant.markets.report import FactorRiskReport, PerformanceReport, ThematicReport
from gs_quant.session import *
from gs_quant.target.reports import ReportStatus, PositionSourceType, ReportType, ReportParameters, Report

fake_pfr = FactorRiskReport(risk_model_id='AXUS4M',
                            fx_hedged=True,
                            report_id='PFRID',
                            position_source_type=PositionSourceType.Portfolio,
                            position_source_id='PORTFOLIOID',
                            report_type=ReportType.Portfolio_Factor_Risk,
                            status=ReportStatus.done
                            )

fake_ppa = PerformanceReport(report_id='PPAID',
                             position_source_type=PositionSourceType.Portfolio,
                             position_source_id='PORTFOLIOID',
                             report_type=ReportType.Portfolio_Performance_Analytics,
                             parameters=None,
                             status=ReportStatus.done
                             )
fake_pta = ThematicReport(report_id='PTAID',
                          position_source_type=PositionSourceType.Portfolio,
                          position_source_id='PORTFOLIOID',
                          report_type=ReportType.Portfolio_Thematic_Analytics,