예제 #1
0
 def get_factor_data(self,
                     start_date: dt.date = None,
                     end_date: dt.date = None,
                     identifiers: List[str] = None,
                     include_performance_curve: bool = None) -> List[Dict]:
     """ Retrieve factor data for existing risk model """
     start_date = dt.datetime.strptime(
         GsRiskModelApi.get_risk_model_dates(self.model.id)[0],
         '%Y-%m-%d') if not start_date else start_date
     id_to_category_for_date_range = GsRiskModelApi.get_risk_model_data(
         model_id=self.model.id,
         start_date=start_date,
         end_date=end_date,
         assets=None,
         measures=[Measure.Factor_Id, Measure.Factor_Category],
         limit_factors=False,
         data_format=None).get('results')
     factor_id_to_category = _build_id_to_category(
         id_to_category_for_date_range)
     factor_data = GsRiskModelApi.get_risk_model_factor_data(
         self.model.id, start_date, end_date, identifiers,
         include_performance_curve)
     for factor in factor_data:
         factor['factorCategory'] = factor_id_to_category.get(
             factor.get('identifier'), factor.get('name'))
     return factor_data
예제 #2
0
 def create(cls,
            coverage: Union[CoverageType, str],
            id_: str,
            name: str,
            term: Union[Term, str],
            universe_identifier: Union[UniverseIdentifier, str],
            vendor: str,
            version: float,
            entitlements: Union[Entitlements, Dict] = None,
            description: str = None):
     """ Creates new factor risk model and uploads factor risk model object to Marquee
         :param coverage: coverage of risk model asset universe
         :param id_: risk model id (cannot be changed)
         :param name: risk model name
         :param term: horizon term
         :param universe_identifier: identifier used in asset universe upload (cannot be changed)
         :param vendor: risk model vendor
         :param version: version of model
         :param entitlements: entitlements associated with risk model
         :param description: risk model description
         :return: Factor Risk Model object  """
     new_model = RiskModelBuilder(coverage,
                                  id_,
                                  name,
                                  term,
                                  universe_identifier,
                                  vendor,
                                  version,
                                  entitlements=entitlements,
                                  description=description)
     GsRiskModelApi.create_risk_model(new_model)
     return FactorRiskModel(id_)
예제 #3
0
 def upload_partial_data(self,
                         data: RiskModelData,
                         target_universe_size: float = None):
     """ Upload partial risk model data to existing risk model, if repeats in partial upload,
         newer posted data will replace existing data on upload day """
     GsRiskModelApi.upload_risk_model_data(
         self.model.id,
         data,
         partial_upload=True,
         target_universe_size=target_universe_size)
예제 #4
0
 def update(self):
     """ Updates factor risk model object on Marquee """
     updated_model = RiskModelBuilder(self.coverage,
                                      self.id,
                                      self.name,
                                      self.term,
                                      self.universe_identifier,
                                      self.vendor,
                                      self.version,
                                      description=self.description,
                                      entitlements=self.entitlements)
     GsRiskModelApi.update_risk_model(updated_model)
예제 #5
0
 def upload(self):
     """ Upload current Factor Risk Model object to Marquee """
     new_model = RiskModelBuilder(self.coverage,
                                  self.id,
                                  self.name,
                                  self.term,
                                  self.universe_identifier,
                                  self.vendor,
                                  self.version,
                                  entitlements=self.entitlements,
                                  description=self.description)
     GsRiskModelApi.create_risk_model(new_model)
예제 #6
0
    def get_many(cls,
                 ids: List[str] = None,
                 terms: List[str] = None,
                 vendors: List[str] = None,
                 names: List[str] = None,
                 coverages: List[str] = None,
                 limit: int = None):
        """ Get a factor risk model from Marquee

        :param ids: list of model identifiers in Marquee
        :param terms: list of model terms
        :param vendors: list of model vendors
        :param names: list of model names
        :param coverages: list of model coverages
        :param limit: limit of number of models in response

        :return: Factor Risk Model object
        """
        models = GsRiskModelApi.get_risk_models(ids=ids,
                                                terms=terms,
                                                vendors=vendors,
                                                names=names,
                                                coverages=coverages,
                                                limit=limit)
        return cls.from_many_targets(models)
예제 #7
0
 def get(cls, model_id: str):
     """ Get a risk model from Marquee
     :param model_id: risk model id corresponding to Marquee Risk Model
     :return: Risk Model object
     """
     model = GsRiskModelApi.get_risk_model(model_id)
     return cls.from_target(model)
예제 #8
0
def test_get_risk_model(mocker):
    model_id = 'WW_TEST_MODEL'
    model = RiskModel.from_dict({
        "coverage": "Global",
        "id": "WW_TEST_MODEL",
        "name": "World Wide Medium Term Test Model",
        "term": "Medium",
        "vendor": "Goldman Sachs",
        "universeIdentifier": "gsid",
        "version": 4
    })

    expected_response = RiskModel(coverage='Global',
                                  id='WW_TEST_MODEL',
                                  name='World Wide Medium Term Test Model',
                                  term='Medium',
                                  vendor='Goldman Sachs',
                                  version=4,
                                  universe_identifier='gsid')

    # 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=model)

    # run test
    response = GsRiskModelApi.get_risk_model(model_id)
    GsSession.current._get.assert_called_with(
        '/risk/models/{id}'.format(id=model_id), cls=RiskModel)
    assert response == expected_response
예제 #9
0
def test_get_risk_model_coverage(mocker):
    results = {
        "results": [
            RiskModelFactor.from_dict({
                "model": "AXUS4S",
                "businessDate": "2020-11-02"
            }),
            RiskModelFactor.from_dict({
                "model": "AXAU4M",
                "businessDate": "2020-11-03"
            })
        ]
    }

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

    # run test
    response = GsRiskModelApi.get_risk_model_coverage()
    GsSession.current._post.assert_called_with('/risk/models/coverage', {})
    assert response == results['results']
예제 #10
0
 def remove_entitlements(self, entitlements: Union[Entitlements, Dict]):
     """ Removes entitlements for existing risk model """
     entitlements = Entitlements.from_dict(entitlements) if type(
         entitlements) == dict else entitlements
     model = GsRiskModelApi.get_risk_model(self.__id)
     edit_ls = list(model.entitlements.edit)
     for edit in entitlements.edit:
         edit_ls.remove(edit)
     admin_ls = list(model.entitlements.admin)
     for admin in entitlements.admin:
         admin_ls.remove(admin)
     query_ls = list(model.entitlements.query)
     for query in entitlements.query:
         query_ls.remove(query)
     upload_ls = list(model.entitlements.upload)
     for upload in entitlements.upload:
         upload_ls.remove(upload)
     view_ls = list(model.entitlements.view)
     for view in entitlements.view:
         view_ls.remove(view)
     execute_ls = list(model.entitlements.execute)
     for execute in entitlements.execute:
         execute_ls.remove(execute)
     removed_entitlements = Entitlements(edit=tuple(edit_ls),
                                         admin=tuple(admin_ls),
                                         query=tuple(query_ls),
                                         upload=tuple(upload_ls),
                                         view=tuple(view_ls),
                                         execute=tuple(execute_ls))
     self.entitlements = removed_entitlements
예제 #11
0
def test_get_risk_model_factors(mocker):
    factors = {
        'results': [
            RiskModelFactor.from_dict({
                "type": "Factor",
                "identifier": "Factor1"
            }),
            RiskModelFactor.from_dict({
                "type": "Category",
                "identifier": "Factor2"
            })
        ],
        'totalResults':
        2
    }

    expected_response = [
        RiskModelFactor(identifier='Factor1', type='Factor'),
        RiskModelFactor(identifier='Factor2', type='Category')
    ]

    # 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=factors)

    # run test
    response = GsRiskModelApi.get_risk_model_factors(model_id='id')
    GsSession.current._get.assert_called_with('/risk/models/id/factors',
                                              cls=RiskModelFactor)
    assert response == expected_response
예제 #12
0
def test_update_risk_model(mocker):
    model = RiskModel.from_dict({
        "coverage": "Global",
        "id": "WW_TEST_MODEL",
        "name": "World Wide Medium Term Test Model",
        "term": "Medium",
        "vendor": "Goldman Sachs",
        "universeIdentifier": "gsid",
        "version": 4
    })

    # 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=model)

    # run test
    response = GsRiskModelApi.update_risk_model(model)
    GsSession.current._put.assert_called_with('/risk/models/{id}'.format(id='WW_TEST_MODEL'), model, cls=RiskModel)
    assert response == model
예제 #13
0
 def __init__(self, model_id: str):
     model = GsRiskModelApi.get_risk_model(model_id)
     self.__id: str = model.id
     self.__name: str = model.name
     self.__description: str = model.description
     self.__entitlements: Entitlements = model.entitlements if type(model.entitlements) == Entitlements or not \
         model.entitlements else Entitlements.from_dict(model.entitlements)
예제 #14
0
 def get_dates(self,
               start_date: dt.date = None,
               end_date: dt.date = None) -> List:
     """ Retrieve risk model dates for existing risk model
         :param start_date: list returned including and after start_date
         :param end_date: list returned up to and including end_date """
     return GsRiskModelApi.get_risk_model_dates(self.id, start_date,
                                                end_date)
예제 #15
0
def test_get_risk_models(mocker):
    mock_response = {
        'results': [
            RiskModel.from_dict({
                "coverage": "Global",
                "id": "WW_TEST_MODEL",
                "name": "World Wide Medium Term Test Model",
                "term": "Medium",
                "vendor": "Goldman Sachs",
                "universeIdentifier": "gsid",
                "type": "Factor",
                "version": 4
            }),
            RiskModel.from_dict({
                "coverage": "Global",
                "id": "WW_TEST_MODEL_2",
                "name": "World Wide Medium Term Test Model 2",
                "term": "Medium",
                "vendor": "Goldman Sachs",
                "universeIdentifier": "gsid",
                "version": 2,
                "type": "Thematic"
            })
        ],
        'totalResults':
        2
    }

    expected_response = [
        RiskModel(coverage='Global',
                  id='WW_TEST_MODEL',
                  name='World Wide Medium Term Test Model',
                  term='Medium',
                  vendor='Goldman Sachs',
                  universe_identifier='gsid',
                  version=4,
                  type='Factor'),
        RiskModel(coverage='Global',
                  id='WW_TEST_MODEL_2',
                  name='World Wide Medium Term Test Model 2',
                  term='Medium',
                  vendor='Goldman Sachs',
                  universe_identifier='gsid',
                  version=2,
                  type='Thematic')
    ]

    # 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 = GsRiskModelApi.get_risk_models()
    GsSession.current._get.assert_called_with('/risk/models?', cls=RiskModel)
    assert response == expected_response
예제 #16
0
 def get_factor_data(self,
                     start_date: dt.date = None,
                     end_date: dt.date = None,
                     identifiers: List[str] = None,
                     include_performance_curve: bool = None) -> List[Dict]:
     """ Retrieve factor data for existing risk model """
     return GsRiskModelApi.get_risk_model_factor_data(
         self.model.id, start_date, end_date, identifiers,
         include_performance_curve)
예제 #17
0
 def __init__(self, model_id: str):
     super().__init__(model_id)
     model = GsRiskModelApi.get_risk_model(model_id)
     self.__coverage: Union[CoverageType, str] = model.coverage
     self.__term: Union[Term, str] = model.term
     self.__universe_identifier: Union[UniverseIdentifier,
                                       str] = model.universe_identifier
     self.__vendor: str = model.vendor
     self.__version: float = model.version
예제 #18
0
def test_get_risk_model_data(mocker):
    query = {'startDate': '2020-01-01', 'endDate': '2020-03-03'}

    results = {
        'results': [{
            'date':
            '2020-02-05',
            'assetData': {
                'universe': ['2407966', '2046251', 'USD'],
                'specificRisk': [12.09, 45.12, 3.09],
                'factorExposure': [{
                    '1': 0.23,
                    '2': 0.023
                }],
                'historicalBeta': [0.12, 0.45, 1.2]
            },
            'factorData': [{
                'factorId': '1',
                'factorName': 'USD',
                'factorCategory': 'Currency',
                'factorCategoryId': 'CUR'
            }],
            'covarianceMatrix': [[0.089, 0.0123, 0.345]],
            'issuerSpecificCovariance': {
                'universeId1': ['2407966'],
                'universeId2': ['2046251'],
                'covariance': [0.03754]
            },
            'factorPortfolios': {
                'universe': ['2407966', '2046251'],
                'portfolio': [{
                    'factorId': 2,
                    'weights': [0.25, 0.75]
                }]
            }
        }],
        'totalResults':
        1,
        'missingDates': []
    }

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

    # run test
    response = GsRiskModelApi.get_risk_model_data(model_id='id',
                                                  start_date=dt.date(
                                                      2020, 1, 1),
                                                  end_date=dt.date(2020, 3, 3))
    GsSession.current._post.assert_called_with(
        '/risk/models/data/{id}/query'.format(id='id'), query)
    assert response == results
예제 #19
0
 def get_issuer_specific_covariance(self,
                                    start_date: dt.date,
                                    end_date: dt.date,
                                    assets: DataAssetsRequest = None,
                                    limit_factors: bool = None,
                                    data_format: Format = None) -> Dict:
     """ Retrieve issuer specific covariance data for existing risk model """
     return GsRiskModelApi.get_risk_model_data(
         self.model.id, start_date, end_date, assets,
         [Measure.Issuer_Specific_Covariance], limit_factors, data_format)
예제 #20
0
 def save(self):
     """ Upload current Risk Model object to Marquee """
     model = RiskModelBuilder(
         self.coverage,
         self.id,
         self.name,
         self.term,
         self.universe_identifier,
         self.vendor,
         self.version,
         type_=self.type,
         description=self.description,
         entitlements=self.entitlements,
         expected_update_time=self.expected_update_time.strftime('%H:%M:%S')
         if self.expected_update_time else None)
     try:
         GsRiskModelApi.create_risk_model(model)
     except MqRequestError:
         GsRiskModelApi.update_risk_model(model)
예제 #21
0
 def get_universe_factor_exposure(self,
                                  start_date: dt.date,
                                  end_date: dt.date,
                                  assets: DataAssetsRequest = None,
                                  limit_factors: bool = None,
                                  data_format: Format = None) -> Dict:
     """ Retrieve universe factor exposure data for existing risk model """
     return GsRiskModelApi.get_risk_model_data(
         self.model.id, start_date, end_date, assets,
         [Measure.Universe_Factor_Exposure], limit_factors, data_format)
예제 #22
0
파일: risk_model.py 프로젝트: mn98/gs-quant
 def get_calendar(self, start_date: dt.date = None, end_date: dt.date = None) -> RiskModelCalendar:
     """ Get risk model calendar for existing risk model between start and end date
         :param start_date: list returned including and after start_date
         :param end_date: list returned up to and including end_date """
     calendar = GsRiskModelApi.get_risk_model_calendar(self.id)
     if not start_date and not end_date:
         return calendar
     start_idx = get_closest_date_index(start_date, calendar.business_dates, 'after') if start_date else 0
     end_idx = get_closest_date_index(end_date, calendar.business_dates, 'before') if end_date else len(
         calendar.business_dates)
     return RiskModelCalendar(calendar.business_dates[start_idx:end_idx + 1])
예제 #23
0
 def get_data(self,
              measures: List[Measure],
              start_date: dt.date,
              end_date: dt.date,
              assets: DataAssetsRequest = None,
              limit_factors: bool = None,
              data_format: Format = None) -> Dict:
     """ Retrieve data for multiple measures for existing risk model """
     return GsRiskModelApi.get_risk_model_data(self.model.id, start_date,
                                               end_date, assets, measures,
                                               limit_factors, data_format)
예제 #24
0
 def get_total_risk(self,
                    start_date: dt.date,
                    end_date: dt.date,
                    assets: DataAssetsRequest = None,
                    limit_factors: bool = None,
                    data_format: Format = None) -> Dict:
     """ Retrieve total risk data for existing risk model """
     return GsRiskModelApi.get_risk_model_data(self.model.id, start_date,
                                               end_date, assets,
                                               [Measure.Total_Risk],
                                               limit_factors, data_format)
예제 #25
0
 def get_historical_beta(self,
                         start_date: dt.date,
                         end_date: dt.date,
                         assets: DataAssetsRequest = None,
                         limit_factors: bool = None,
                         data_format: Format = None) -> Dict:
     """ Retrieve historical beta data for existing risk model """
     return GsRiskModelApi.get_risk_model_data(self.model.id, start_date,
                                               end_date, assets,
                                               [Measure.Historical_Beta],
                                               limit_factors, data_format)
예제 #26
0
 def get_residual_variance(self,
                           start_date: dt.date,
                           end_date: dt.date,
                           assets: DataAssetsRequest = None,
                           limit_factors: bool = None,
                           data_format: Format = None) -> Dict:
     """ Retrieve residual variance data for existing risk model """
     return GsRiskModelApi.get_risk_model_data(self.model.id, start_date,
                                               end_date, assets,
                                               [Measure.Residual_Variance],
                                               limit_factors, data_format)
예제 #27
0
 def get_factor_portfolios(self,
                           start_date: dt.date,
                           end_date: dt.date,
                           assets: DataAssetsRequest = None,
                           limit_factors: bool = None,
                           data_format: Format = None) -> Dict:
     """ Retrieve factor portfolios data for existing risk model """
     return GsRiskModelApi.get_risk_model_data(self.model.id, start_date,
                                               end_date, assets,
                                               [Measure.Factor_Portfolios],
                                               limit_factors, data_format)
예제 #28
0
 def get_covariance_matrix(self,
                           start_date: dt.date,
                           end_date: dt.date,
                           assets: DataAssetsRequest = None,
                           limit_factors: bool = None,
                           data_format: Format = None) -> Dict:
     """ Retrieve covariance matrix data for existing risk model """
     return GsRiskModelApi.get_risk_model_data(self.model.id, start_date,
                                               end_date, assets,
                                               [Measure.Covariance_Matrix],
                                               limit_factors, data_format)
예제 #29
0
def test_upload_risk_model_data(mocker):
    risk_model_data = {
        'date':
        '2020-02-05',
        'assetData': {
            'universe': ['2407966', '2046251', 'USD'],
            'specificRisk': [12.09, 45.12, 3.09],
            'factorExposure': [{
                '1': 0.23,
                '2': 0.023
            }],
            'historicalBeta': [0.12, 0.45, 1.2]
        },
        'factorData': [{
            'factorId': '1',
            'factorName': 'USD',
            'factorCategory': 'Currency',
            'factorCategoryId': 'CUR'
        }],
        'covarianceMatrix': [[0.089, 0.0123, 0.345]],
        'issuerSpecificCovariance': {
            'universeId1': ['2407966'],
            'universeId2': ['2046251'],
            'covariance': [0.03754]
        },
        'factorPortfolios': {
            'universe': ['2407966', '2046251'],
            'portfolio': [{
                'factorId': 2,
                'weights': [0.25, 0.75]
            }]
        }
    }

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

    # run test
    response = GsRiskModelApi.upload_risk_model_data(
        model_id='id', model_data=risk_model_data)
    GsSession.current._post.assert_called_with(
        '/risk/models/data/{id}'.format(id='id'),
        risk_model_data,
        cls=RiskModelData)
    assert response == risk_model_data
예제 #30
0
 def get_historical_beta(self,
                         start_date: dt.date,
                         end_date: dt.date,
                         assets: DataAssetsRequest = None,
                         data_format: Format = None) -> Dict:
     """ Retrieve historical beta data for existing risk model """
     return GsRiskModelApi.get_risk_model_data(
         model_id=self.model.id,
         start_date=start_date,
         end_date=end_date,
         assets=assets,
         measures=[Measure.Historical_Beta, Measure.Asset_Universe],
         limit_factors=False,
         data_format=data_format)