Ejemplo n.º 1
0
def test_aggregation_with_empty_measures(mocker):
    with MockCalc(mocker):
        swaptions = (IRSwaption(notional_currency='EUR',
                                termination_date='7y',
                                expiration_date='1y',
                                pay_or_receive='Receive',
                                strike='ATM+35',
                                name='EUR 1y7y'),
                     IRSwaption(notional_currency='EUR',
                                termination_date='10y',
                                expiration_date='2w',
                                pay_or_receive='Receive',
                                strike='ATM+50',
                                name='EUR 2w10y'))
        portfolio = Portfolio(swaptions)

        from_date = dt.date(2021, 11, 18)
        to_date = dt.date(2021, 11, 19)
        explain_2d = PnlExplain(CloseMarket(date=to_date))

        with PricingContext(pricing_date=from_date, visible_to_gs=True):
            portfolio.resolve()
            result_explain = portfolio.calc(explain_2d)

        total_risk = aggregate_risk(result_explain[explain_2d])['value'].sum()
        risk_swaption_1 = result_explain[0]['value'].sum()
        risk_swaption_2 = result_explain[1]['value'].sum()

        assert total_risk == risk_swaption_1 + risk_swaption_2
Ejemplo n.º 2
0
def test_aggregation_with_diff_risk_keys(mocker):
    with MockCalc(mocker):
        portfolio1 = Portfolio([
            IRSwaption('Pay',
                       '10y',
                       'EUR',
                       expiration_date='3m',
                       name='EUR3m10ypayer')
        ])
        portfolio2 = Portfolio([
            IRSwaption('Pay',
                       '10y',
                       'EUR',
                       expiration_date='6m',
                       name='EUR6m10ypayer')
        ])

        with PricingContext(csa_term='EUR-OIS', visible_to_gs=True):
            r1 = portfolio1.price()
        with PricingContext(csa_term='EUR-EuroSTR'):
            r2 = portfolio2.price()

        combined_result = r1 + r2

    with pytest.raises(ValueError):
        combined_result.aggregate()

    assert isinstance(combined_result.aggregate(allow_mismatch_risk_keys=True),
                      float)
Ejemplo n.º 3
0
def test_aggregate_triggger():
    # Test Aggregate Trigger
    action_1 = AddTradeAction(IRSwap())
    action_2 = AddTradeAction(IRSwaption())
    trigger_1 = DateTrigger(
        DateTriggerRequirements([
            dt.date(2021, 11, 9),
            dt.date(2021, 11, 10),
            dt.date(2021, 11, 11)
        ]), [action_1])

    trigger_2 = DateTrigger(
        DateTriggerRequirements([
            dt.date(2021, 11, 8),
            dt.date(2021, 11, 10),
            dt.date(2021, 11, 12)
        ]), [action_2])

    agg_trigger = AggregateTrigger(
        AggregateTriggerRequirements([trigger_1, trigger_2],
                                     aggregate_type=AggType.ALL_OF))

    assert not agg_trigger.has_triggered(dt.date(2021, 11, 9))
    assert agg_trigger.has_triggered(dt.date(2021, 11, 10))
    assert len(agg_trigger.actions) == 2

    agg_trigger = AggregateTrigger(
        AggregateTriggerRequirements([trigger_1, trigger_2],
                                     aggregate_type=AggType.ANY_OF))

    assert agg_trigger.has_triggered(dt.date(2021, 11, 8))
    assert isinstance(agg_trigger.actions[0].priceables[0], IRSwaption)
    assert agg_trigger.has_triggered(dt.date(2021, 11, 10))
    assert len(agg_trigger.actions) == 2
Ejemplo n.º 4
0
def test_from_frame():
    swap = IRSwap('Receive', '3m', 'USD', fixed_rate=0, notional_amount=1)
    swaption = IRSwaption(notional_currency='GBP', expiration_date='10y', effective_date='0b')
    portfolio = Portfolio((swap, swaption))
    port_df = portfolio.to_frame()
    new_port_df = Portfolio.from_frame(port_df)

    assert new_port_df[swap] == swap
    assert new_port_df[swaption] == swaption
Ejemplo n.º 5
0
def test_multiple_measures(mocker):
    day = [
        [
            [{
                '$type': 'RiskVector',
                'asset': [0.01, 0.015],
                'points': [
                    {'type': 'IR Vol', 'asset': 'USD-LIBOR-BBA', 'class_': 'Swap', 'point': '1y'},
                    {'type': 'IR Vol', 'asset': 'USD-LIBOR-BBA', 'class_': 'Swap', 'point': '2y'}
                ]
            }]
        ],
        [
            [{
                '$type': 'RiskVector',
                'asset': [0.01, 0.015],
                'points': [
                    {'type': 'IR', 'asset': 'USD', 'class_': 'Swap', 'point': '1y'},
                    {'type': 'IR', 'asset': 'USD', 'class_': 'Swap', 'point': '2y'}
                ]
            }],
        ],
        [
            [{'$type': 'Risk', 'val': 0.01}]
        ]
    ]

    mocker.return_value = [day, day, day]

    set_session()

    ir_swaption = IRSwaption('Pay', '10y', 'USD')

    dates = (dt.date(2019, 10, 7), dt.date(2019, 10, 8), dt.date(2019, 10, 9))
    with HistoricalPricingContext(dates=dates, use_cache=True):
        ir_swaption.price()
        ir_swaption.calc(risk.IRDelta)
        ir_swaption.calc(risk.IRVega)

    # make sure all the risk measures got cached correctly
    for date in dates:
        with PricingContext(pricing_date=date) as pc:
            for risk_measure in (risk.Price, risk.IRDelta, risk.IRVega):
                val = PricingCache.get(pc._PricingContext__risk_key(risk_measure, ir_swaption.provider), ir_swaption)
                assert val is not None

    with PricingContext(pricing_date=dt.date(2019, 10, 11)) as pc:
        for risk_measure in (risk.Price, risk.IRDelta, risk.IRVega):
            val = PricingCache.get(pc._PricingContext__risk_key(risk_measure, ir_swaption.provider), ir_swaption)
            assert val is None
Ejemplo n.º 6
0
def test_not_triggger():
    # Test Not Trigger
    action = AddTradeAction(IRSwap())
    not_action = AddTradeAction(IRSwaption())
    trigger = DateTrigger(
        DateTriggerRequirements([
            dt.date(2021, 11, 9),
            dt.date(2021, 11, 10),
            dt.date(2021, 11, 11)
        ]), [action])

    not_trigger = NotTrigger(NotTriggerRequirements(trigger), [not_action])

    assert not_trigger.has_triggered(dt.date(2021, 11, 8))
    assert isinstance(not_trigger.actions[0].priceables[0], IRSwaption)
    assert not not_trigger.has_triggered(dt.date(2021, 11, 10))
Ejemplo n.º 7
0
def test_mkt_trigger_data_sources(mocker):
    with MockCalc(mocker):
        s = pd.Series({
            date(2021, 10, 1): 0.984274,
            date(2021, 10, 4): 1.000706,
            date(2021, 10, 5): 1.044055,
            date(2021, 10, 6): 1.095361,
            date(2021, 10, 7): 1.129336,
            date(2021, 10, 8): 1.182954,
            date(2021, 10, 12): 1.200108,
            date(2021, 10, 13): 1.220607,
            date(2021, 10, 14): 1.172837,
            date(2021, 10, 15): 1.163660,
            date(2021, 10, 18): 1.061084,
            date(2021, 10, 19): 1.025012,
            date(2021, 10, 20): 1.018035,
            date(2021, 10, 21): 1.080751,
            date(2021, 10, 22): 1.069340,
            date(2021, 10, 25): 1.033413
        })

        action = AddTradeAction(
            IRSwaption(notional_currency='USD',
                       expiration_date='1y',
                       termination_date='1y'), 'expiration_date')
        data_source = GenericDataSource(s, MissingDataStrategy.fill_forward)
        mkt_trigger = MktTrigger(
            MktTriggerRequirements(data_source, 1.1, TriggerDirection.ABOVE),
            action)
        strategy = Strategy(None, mkt_trigger)

        engine = GenericEngine()

        # backtest = engine.run_backtest(strategy, start=date(2021, 10, 1), end=date(2021, 10, 25), frequency='1b',
        #                                show_progress=True)
        backtest = engine.run_backtest(strategy,
                                       states=s.index,
                                       show_progress=True)

        summary = backtest.result_summary
        ledger = backtest.trade_ledger()
        assert len(summary) == 12
        assert len(ledger) == 6
        assert round(summary[Price].sum()) == 25163614
        assert round(summary['Cumulative Cash'].sum()) == -2153015
Ejemplo n.º 8
0
"""
`Portfolio` supports the same methods as `Instrument` including `resolve()`, `calc()`, and `price()`
Resolving the portfolio resolves each individual instrument within the portfolio.
"""
from gs_quant.common import PayReceive, Currency  # import constants
from gs_quant.instrument import IRSwaption  # import instruments
from gs_quant.markets.portfolio import Portfolio
from gs_quant.session import Environment, GsSession  # import sessions

client_id = None  # Supply your application id
client_secret = None  # Supply your client secret
scopes = ('run_analytics', )
GsSession.use(Environment.PROD, client_id, client_secret, scopes)

swaption1 = IRSwaption(PayReceive.Pay,
                       '5y',
                       Currency.EUR,
                       expiration_date='3m',
                       name='EUR-3m5y')
swaption2 = IRSwaption(PayReceive.Pay,
                       '5y',
                       Currency.EUR,
                       expiration_date='6m',
                       name='EUR-6m5y')

portfolio = Portfolio((swaption1, swaption2))
portfolio.resolve()
print(portfolio.as_dict())
Ejemplo n.º 9
0
from gs_quant.common import AssetClass
from gs_quant.instrument import CommodSwap, EqForward, EqOption, FXOption, IRBasisSwap, IRSwap, IRSwaption, IRCap,\
    IRFloor
from gs_quant.markets import PricingContext
from gs_quant.session import Environment, GsSession
from gs_quant.target.risk import PricingDateAndMarketDataAsOf, RiskPosition, RiskRequestParameters, \
    OptimizationRequest

priceables = (
    CommodSwap('Electricity', '1y'),
    EqForward('GS.N', '1y'),
    EqOption('GS.N', '3m', 'ATMF', 'Call', 'European'),
    FXOption('EUR', 'USD', '1y', 'Call', strike_price='ATMF'),
    IRSwap('Pay', '10y', 'USD'),
    IRBasisSwap('10y', 'USD'),
    IRSwaption('Pay', '10y', 'USD'),
    IRCap('10y', 'EUR'),
    IRFloor('10y', 'EUR')
)


def set_session():
    from gs_quant.session import OAuth2Session
    OAuth2Session.init = mock.MagicMock(return_value=None)
    GsSession.use(Environment.QA, 'client_id', 'secret')


def structured_calc(mocker, priceable: Priceable, measure: risk.RiskMeasure):
    set_session()

    values = {
Ejemplo n.º 10
0
import gs_quant.risk as risk
from gs_quant.api.gs.risk import GsRiskApi
from gs_quant.base import Priceable
from gs_quant.common import AssetClass
from gs_quant.instrument import CommodSwap, EqForward, EqOption, FXOption, IRBasisSwap, IRSwap, IRSwaption, IRCap,\
    IRFloor
from gs_quant.markets import PricingContext
from gs_quant.session import Environment, GsSession
from gs_quant.target.risk import PricingDateAndMarketDataAsOf, RiskPosition, RiskRequestParameters, \
    APEXOptimizationRequest

priceables = (CommodSwap('Electricity', '1y'), EqForward('GS.N', '1y'),
              EqOption('GS.N', '3m', 'ATMF', 'Call', 'European'),
              FXOption('EUR', 'USD', '1y', 'Call',
                       strike_price='ATMF'), IRSwap('Pay', '10y', 'USD'),
              IRBasisSwap('10y', 'USD'), IRSwaption('Pay', '10y', 'USD'),
              IRCap('10y', 'EUR'), IRFloor('10y', 'EUR'))


def set_session():
    from gs_quant.session import OAuth2Session
    OAuth2Session.init = mock.MagicMock(return_value=None)
    GsSession.use(Environment.QA, 'client_id', 'secret')


def structured_calc(mocker, priceable: Priceable, measure: risk.RiskMeasure):
    set_session()

    values = {
        '$type':
        'RiskVector',
Ejemplo n.º 11
0
def test_multiple_measures(mocker):
    values = [[[{
        'date': '2019-10-07',
        'marketDataType': 'IR Vol',
        'assetId': 'USD-LIBOR-BBA',
        'pointClass': 'Swap',
        'point': '1y',
        'value': 0.01
    }, {
        'date': '2019-10-07',
        'marketDataType': 'IR Vol',
        'assetId': 'USD-LIBOR-BBA',
        'pointClass': 'Swap',
        'point': '2y',
        'value': 0.015
    }, {
        'date': '2019-10-08',
        'marketDataType': 'IR Vol',
        'assetId': 'USD-LIBOR-BBA',
        'pointClass': 'Swap',
        'point': '1y',
        'value': 0.01
    }, {
        'date': '2019-10-08',
        'marketDataType': 'IR Vol',
        'assetId': 'USD-LIBOR-BBA',
        'pointClass': 'Swap',
        'point': '2y',
        'value': 0.015
    }, {
        'date': '2019-10-09',
        'marketDataType': 'IR Vol',
        'assetId': 'USD-LIBOR-BBA',
        'pointClass': 'Swap',
        'point': '1y',
        'value': 0.01
    }, {
        'date': '2019-10-09',
        'marketDataType': 'IR Vol',
        'assetId': 'USD-LIBOR-BBA',
        'pointClass': 'Swap',
        'point': '2y',
        'value': 0.015
    }]],
              [[{
                  'date': '2019-10-07',
                  'marketDataType': 'IR',
                  'assetId': 'USD',
                  'pointClass': 'Swap',
                  'point': '1y',
                  'value': 0.01
              }, {
                  'date': '2019-10-07',
                  'marketDataType': 'IR',
                  'assetId': 'USD',
                  'pointClass': 'Swap',
                  'point': '2y',
                  'value': 0.015
              }, {
                  'date': '2019-10-08',
                  'marketDataType': 'IR',
                  'assetId': 'USD',
                  'pointClass': 'Swap',
                  'point': '1y',
                  'value': 0.01
              }, {
                  'date': '2019-10-08',
                  'marketDataType': 'IR',
                  'assetId': 'USD',
                  'pointClass': 'Swap',
                  'point': '2y',
                  'value': 0.015
              }, {
                  'date': '2019-10-09',
                  'marketDataType': 'IR',
                  'assetId': 'USD',
                  'pointClass': 'Swap',
                  'point': '1y',
                  'value': 0.01
              }, {
                  'date': '2019-10-09',
                  'marketDataType': 'IR',
                  'assetId': 'USD',
                  'pointClass': 'Swap',
                  'point': '2y',
                  'value': 0.015
              }]],
              [[{
                  'date': '2019-10-07',
                  'value': 0.01
              }, {
                  'date': '2019-10-08',
                  'value': 0.01
              }, {
                  'date': '2019-10-09',
                  'value': 0.01
              }]]]
    mocker.return_value = values

    set_session()

    ir_swaption = IRSwaption('Pay', '10y', 'USD')

    dates = (dt.date(2019, 10, 7), dt.date(2019, 10, 8), dt.date(2019, 10, 9))
    with HistoricalPricingContext(dates=dates, use_cache=True):
        market_data_location = PricingContext.current.market_data_location
        ir_swaption.price()
        ir_swaption.calc(risk.IRDelta)
        ir_swaption.calc(risk.IRVega)

    # make sure all the risk measures got cached correctly
    cached = PricingCache.get(ir_swaption, market_data_location, risk.Price,
                              dates)
    assert len(cached) == len(dates)

    cached1 = PricingCache.get(ir_swaption, market_data_location, risk.IRDelta,
                               dates)
    assert len(cached1.index.unique()) == len(dates)

    cached2 = PricingCache.get(ir_swaption, market_data_location, risk.IRVega,
                               dates)
    assert len(cached2.index.unique()) == len(dates)

    # date not in cache
    cached3 = PricingCache.get(ir_swaption, market_data_location, risk.IRVega,
                               dt.date(2019, 10, 11))
    assert cached3 is None

    # subset from cache
    subset = dates[0:2]
    cached4 = PricingCache.get(ir_swaption, market_data_location, risk.Price,
                               subset)
    assert len(cached4) == len(subset)

    # intersection
    subset += (dt.date(2019, 10, 2), )
    cached5 = PricingCache.get(ir_swaption, market_data_location, risk.Price,
                               subset)
    assert len(cached5) == len(subset) - 1
Ejemplo n.º 12
0
swap_4 = IRSwap("Pay", "10y", "USD", fixed_rate=-0.005, name="10y")
swap_5 = IRSwap("Pay", "5y", "GBP", fixed_rate=-0.005, name="5y")
swap_6 = IRSwap("Pay", "10y", "GBP", fixed_rate=-0.005, name="10y")
swap_7 = IRSwap("Pay", "5y", "JPY", fixed_rate=-0.005, name="5y")
swap_8 = IRSwap("Pay", "10y", "JPY", fixed_rate=-0.005, name="10y")
eur_port = Portfolio([swap_1, swap_2], name="EUR")
usd_port = Portfolio([swap_3, swap_4], name="USD")
gbp_port = Portfolio([swap_5, swap_6], name="GBP")
jpy_port = Portfolio([swap_7, swap_8], name='JPY')
port1 = Portfolio([eur_port, gbp_port], name='EURGBP')
port2 = Portfolio([jpy_port, usd_port], name='USDJPY')
port = Portfolio([port1, port2])
swaption_port = Portfolio([
    IRSwaption("Receive",
               '5y',
               'USD',
               expiration_date='2m',
               strike='atm',
               name='Swaption1'),
    IRSwaption("Receive",
               '10y',
               'USD',
               expiration_date='3m',
               strike='atm',
               name='Swaption2')
])

bs = IRBasisSwap(termination_date="2y",
                 notional_currency="GBP",
                 notional_amount="$405392/bp",
                 effective_date="10y",
                 payer_rate_option="OIS",
Ejemplo n.º 13
0
import pandas as pd

import gs_quant.risk as risk
from gs_quant.api.gs.risk import GsRiskApi, RiskModelRequest
from gs_quant.base import Priceable
from gs_quant.common import AssetClass
from gs_quant.instrument import CommodSwap, EqForward, EqOption, FXOption, IRBasisSwap, IRSwap, IRSwaption, IRCap, \
    IRFloor
from gs_quant.markets import PricingContext
from gs_quant.session import Environment, GsSession

priceables = (CommodSwap('Electricity', '1y'), EqForward('GS.N', '1y', 100.0),
              EqOption('GS.N', '3m', 'ATMF', 'Call', 'European'),
              FXOption('EUR', 'USD', '1y', 'Call', strike='ATMF'),
              IRSwap('Pay', '10y', 'USD'), IRBasisSwap('10y', 'USD', 'EUR'),
              IRSwaption('Pay', '10y',
                         'USD'), IRCap('10y', 'EUR'), IRFloor('10y', 'EUR'))


def set_session():
    from gs_quant.session import OAuth2Session
    OAuth2Session.init = mock.MagicMock(return_value=None)
    GsSession.use(Environment.QA, 'client_id', 'secret')


def structured_calc(mocker, priceable: Priceable, measure: risk.RiskMeasure):
    set_session()

    values = [{
        'marketDataType': 'IR',
        'assetId': 'USD',
        'pointClass': 'Swap',
Ejemplo n.º 14
0
def test_multiple_measures(mocker):
    values = [[[{
        '$type':
        'RiskVector',
        'asset': [0.01, 0.015],
        'points': [{
            'type': 'IR Vol',
            'asset': 'USD-LIBOR-BBA',
            'class_': 'Swap',
            'point': '1y'
        }, {
            'type': 'IR Vol',
            'asset': 'USD-LIBOR-BBA',
            'class_': 'Swap',
            'point': '2y'
        }]
    }, {
        '$type':
        'RiskVector',
        'asset': [0.01, 0.015],
        'points': [{
            'type': 'IR Vol',
            'asset': 'USD-LIBOR-BBA',
            'class_': 'Swap',
            'point': '1y'
        }, {
            'type': 'IR Vol',
            'asset': 'USD-LIBOR-BBA',
            'class_': 'Swap',
            'point': '2y'
        }]
    }, {
        '$type':
        'RiskVector',
        'asset': [0.01, 0.015],
        'points': [{
            'type': 'IR Vol',
            'asset': 'USD-LIBOR-BBA',
            'class_': 'Swap',
            'point': '1y'
        }, {
            'type': 'IR Vol',
            'asset': 'USD-LIBOR-BBA',
            'class_': 'Swap',
            'point': '2y'
        }]
    }]],
              [[{
                  '$type':
                  'RiskVector',
                  'asset': [0.01, 0.015],
                  'points': [{
                      'type': 'IR',
                      'asset': 'USD',
                      'class_': 'Swap',
                      'point': '1y'
                  }, {
                      'type': 'IR',
                      'asset': 'USD',
                      'class_': 'Swap',
                      'point': '2y'
                  }]
              }, {
                  '$type':
                  'RiskVector',
                  'asset': [0.01, 0.015],
                  'points': [{
                      'type': 'IR',
                      'asset': 'USD',
                      'class_': 'Swap',
                      'point': '1y'
                  }, {
                      'type': 'IR',
                      'asset': 'USD',
                      'class_': 'Swap',
                      'point': '2y'
                  }]
              }, {
                  '$type':
                  'RiskVector',
                  'asset': [0.01, 0.015],
                  'points': [{
                      'type': 'IR',
                      'asset': 'USD',
                      'class_': 'Swap',
                      'point': '1y'
                  }, {
                      'type': 'IR',
                      'asset': 'USD',
                      'class_': 'Swap',
                      'point': '2y'
                  }]
              }]],
              [[{
                  '$type': 'Risk',
                  'val': 0.01
              }, {
                  '$type': 'Risk',
                  'val': 0.01
              }, {
                  '$type': 'Risk',
                  'val': 0.01
              }]]]
    mocker.return_value = [values]

    set_session()

    ir_swaption = IRSwaption('Pay', '10y', 'USD')

    dates = (dt.date(2019, 10, 7), dt.date(2019, 10, 8), dt.date(2019, 10, 9))
    with HistoricalPricingContext(dates=dates, use_cache=True) as hpc:
        pricing_key = hpc.pricing_key
        ir_swaption.price()
        ir_swaption.calc(risk.IRDelta)
        ir_swaption.calc(risk.IRVega)

    # make sure all the risk measures got cached correctly
    cached = PricingCache.get(ir_swaption, risk.Price, pricing_key)
    assert len(cached) == len(dates)

    cached1 = PricingCache.get(ir_swaption, risk.IRDelta, pricing_key)
    assert len(cached1.index.unique()) == len(dates)

    cached2 = PricingCache.get(ir_swaption, risk.IRVega, pricing_key)
    assert len(cached2.index.unique()) == len(dates)

    # date not in cache
    cached3 = PricingCache.get(
        ir_swaption, risk.IRVega,
        PricingContext(pricing_date=dt.date(2019, 10, 11)).pricing_key)
    assert cached3 is None

    # subset from cache
    subset_key = HistoricalPricingContext(dates=dates[0:2]).pricing_key
    cached4 = PricingCache.get(ir_swaption, risk.Price, subset_key)
    assert len(cached4) == 2

    # intersection
    subset_key = HistoricalPricingContext(dates=dates[0:2] +
                                          (dt.date(2019, 10, 2), )).pricing_key
    cached5 = PricingCache.get(ir_swaption,
                               risk.Price,
                               subset_key,
                               return_partial=True)
    assert len(cached5) == 2