-
Notifications
You must be signed in to change notification settings - Fork 956
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
4baaf77
commit 3f9bd37
Showing
14 changed files
with
1,114 additions
and
127 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,117 @@ | ||
""" | ||
Copyright 2024 Goldman Sachs. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, | ||
software distributed under the License is distributed on an | ||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations | ||
under the License. | ||
""" | ||
|
||
import datetime as dt | ||
import logging | ||
from typing import Dict, List, Tuple | ||
|
||
from gs_quant.session import GsSession | ||
from gs_quant.target.risk import Scenario | ||
|
||
_logger = logging.getLogger(__name__) | ||
|
||
|
||
class GsScenarioApi: | ||
"""GS Scenarios API client implementation""" | ||
|
||
@classmethod | ||
def create_scenario(cls, scenario: Scenario) -> Scenario: | ||
return GsSession.current._post('/risk/scenarios', scenario, cls=Scenario) | ||
|
||
@classmethod | ||
def get_scenario(cls, scenario_id: str) -> Scenario: | ||
return GsSession.current._get(f'/risk/scenarios/{scenario_id}', cls=Scenario) | ||
|
||
@classmethod | ||
def get_many_scenarios(cls, | ||
ids: List[str] = None, | ||
names: List[str] = None, | ||
limit: int = 100, | ||
**kwargs) -> Tuple[Scenario]: | ||
url = f'/risk/scenarios?limit={limit}' | ||
if ids: | ||
url += f'&id={"&id=".join(ids)}' | ||
if names: | ||
url += f'&name={"&name=".join(names)}' | ||
if kwargs: | ||
for k, v in kwargs.items(): | ||
url += f'&{k}={f"&{k}=".join(v)}' if isinstance(v, list) else f'&{k}={v}' | ||
|
||
return GsSession.current._get(url, cls=Scenario).get('results', []) | ||
|
||
@classmethod | ||
def get_scenario_by_name(cls, name: str) -> Scenario: | ||
url = f"/risk/scenarios?name={name}" | ||
ret = GsSession.current._get(url, cls=Scenario) | ||
num_found = ret.get('totalResults', 0) | ||
|
||
if num_found == 0: | ||
raise ValueError(f'Scenario {name}not found') | ||
elif num_found > 1: | ||
raise ValueError(f'More than one scemario named {name}') | ||
else: | ||
return ret['results'][0] | ||
|
||
@classmethod | ||
def update_scenario(cls, scenario: Scenario) -> Dict: | ||
return GsSession.current._put(f'/risk/scenarios/{scenario.get("id")}', scenario, cls=Scenario) | ||
|
||
@classmethod | ||
def delete_scenario(cls, scenario_id: str) -> Dict: | ||
return GsSession.current._delete(f'/risk/scenarios/{scenario_id}') | ||
|
||
@classmethod | ||
def calculate_scenario(cls, request: Dict) -> Dict: | ||
return GsSession.current._post('/scenarios/calculate', request) | ||
|
||
|
||
class GsFactorScenarioApi(GsScenarioApi): | ||
def __init__(self): | ||
super().__init__() | ||
|
||
@classmethod | ||
def get_many_scenarios(cls, | ||
ids: List[str] = None, | ||
names: List[str] = None, | ||
limit: int = 100, | ||
type: str = None, | ||
risk_model: str = None, | ||
shocked_factors: List[str] = None, | ||
shocked_factor_categories: List[str] = None, | ||
propagated_shocks: bool = None, | ||
start_date: dt.date = None, | ||
end_date: dt.date = None) -> Tuple[Scenario]: | ||
factor_scenario_args = {} | ||
if risk_model: | ||
factor_scenario_args['riskModel'] = risk_model | ||
if type: | ||
factor_scenario_args['factorScenarioType'] = type | ||
if shocked_factors: | ||
factor_scenario_args['shockedFactor'] = shocked_factors | ||
if shocked_factor_categories: | ||
factor_scenario_args['shockedFactorCategory'] = shocked_factor_categories | ||
if propagated_shocks: | ||
factor_scenario_args['propagatedShocks'] = propagated_shocks | ||
if start_date: | ||
factor_scenario_args['historicalSimulationStartDate'] = start_date | ||
if end_date: | ||
factor_scenario_args['historicalSimulationEndDate'] = end_date | ||
|
||
return super().get_many_scenarios(ids=ids, names=names, limit=limit, **factor_scenario_args) | ||
|
||
@classmethod | ||
def calculate_scenario(cls, calculation_request: Dict) -> Dict: | ||
return super().calculate_scenario(request=calculation_request) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
""" | ||
Copyright 2024 Goldman Sachs. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, | ||
software distributed under the License is distributed on an | ||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
KIND, either express or implied. See the License for the | ||
specific language governing permissions and limitations | ||
under the License. | ||
""" | ||
|
||
from typing import Union | ||
|
||
import pandas as pd | ||
|
||
|
||
def _explode_data(data: pd.Series, | ||
parent_label: str) -> Union[pd.DataFrame, pd.Series]: | ||
parent_to_child_map = { | ||
"factorCategories": "factors", | ||
"factors": "byAsset", | ||
"sectors": "industries", | ||
"industries": None, | ||
"countries": None, | ||
"direction": None | ||
} | ||
|
||
labels_to_ignore_map = { | ||
"factorCategories": ["factorExposure", "estimatedPnl", "factors"], | ||
"factors": ["factorExposure", "estimatedPnl", "byAsset"], | ||
"sectors": ["exposure", "estimatedPnl", "industries"], | ||
"industries": [], | ||
"countries": [], | ||
"direction": [], | ||
"byAsset": [] | ||
} | ||
|
||
data = data.rename({'name': parent_label}) if parent_label in parent_to_child_map.keys() else data | ||
child_label = parent_to_child_map.get(parent_label) | ||
|
||
if child_label and child_label in data.index.values: | ||
child_df = pd.DataFrame(data[child_label]) | ||
child_df = child_df.apply(_explode_data, axis=1, parent_label=child_label) | ||
|
||
data = data.drop(labels=labels_to_ignore_map.get(parent_label)) | ||
if isinstance(child_df, pd.Series): | ||
child_df = pd.concat(child_df.values, ignore_index=True) | ||
child_df = child_df.assign(**data.to_dict()) | ||
|
||
return child_df | ||
|
||
return data |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.