<jupyter_start><jupyter_text>Pull Backcasted Factor Risk**First define your positions and risk model:***We will resolve all identifiers (bloomberg IDs, SEDOLs, RICs, etc) historically on our end as of the position date*<jupyter_code>import datetime as dt
from gs_quant.datetime import business_day_offset

from gs_quant.markets.portfolio import Portfolio
from gs_quant.markets.portfolio_manager import PortfolioManager
from gs_quant.markets.position_set import PositionSet
from gs_quant.markets.report import FactorRiskReport
from gs_quant.models.risk_model import FactorRiskModel
from gs_quant.session import GsSession, Environment

GsSession.use(Environment.PROD)

positions = [
    {
        'identifier': 'AAPL UW',
        'quantity': 25
    }, {
        'identifier': 'GS UN',
        'quantity': 50
    }, {
        'identifier': 'FB UW',
        'quantity': 25
    }, {
        'identifier': 'AMZN UN',
        'quantity': 50
    }, {
        'identifier': 'MSFT UW',
        'quantity': 25
    }, {
        'identifier': 'AZN UW',
        'quantity': 50
    }
]
risk_model_id = 'AXUS4M'

print('Positions and risk model ID saved.')<jupyter_output><empty_output><jupyter_text>Quick Tip!*Premium clients get access to many more risk models (including premium vendors like MSCI Barra),while non-premium clients get access to a limited suite of models. To see which models you have access to,simply run the following:*<jupyter_code>risk_models = FactorRiskModel.get_many(limit=100)
for risk_model in risk_models:
    print(f'{risk_model.name}: {risk_model.id}\n')<jupyter_output><empty_output><jupyter_text>**Create a portfolio with those positions held on the last previous business day:**<jupyter_code>portfolio = Portfolio(name='My Backcasted Portfolio')
portfolio.save()

pm = PortfolioManager(portfolio.id)
pm.update_positions([PositionSet.from_dicts(date=business_day_offset(dt.date.today(), -1, roll='forward'),
                                            positions=positions)])<jupyter_output><empty_output><jupyter_text>**Now we can create a factor risk report for the portfolio...**<jupyter_code>pm.schedule_reports(backcast=True)
risk_report = FactorRiskReport(risk_model_id='AXUS4M', fx_hedged=True)
risk_report.set_position_source(portfolio.id)
risk_report.save()

print(f'Portfolio created with ID "{portfolio.id}".')<jupyter_output><empty_output><jupyter_text>**And run risk calculations backcasted one year:**<jupyter_code>risk_results = risk_report.run(backcast=True, is_async=False)<jupyter_output><empty_output><jupyter_text>**Once that's done, you can pull the results directly from the `risk_results` object:**<jupyter_code>risk_results = risk_results[risk_results['factorCategory'] == 'Aggregations']

factor_exposures = risk_results.filter(items=['date', 'factor', 'exposure']).pivot(index='date', columns='factor', values='exposure')
factor_pnl= risk_results.filter(items=['date', 'factor', 'pnl']).pivot(index='date', columns='factor', values='pnl')

factor_exposures.plot(title='Factor Exposures')
factor_pnl.cumsum().plot(title='Factor PnL')


print(f'Compare to your portfolio UI here: https://marquee.gs.com/s/portfolios/{portfolio.id}/attribution')<jupyter_output><empty_output><jupyter_text>risk_results = risk_results[risk_results['factorCategory'] == 'Aggregations']factor_exposures = risk_results.filter(items=['date', 'factor', 'exposure']).pivot(index='date', columns='factor', values='exposure')factor_pnl= risk_results.filter(items=['date', 'factor', 'pnl']).pivot(index='date', columns='factor', values='pnl')factor_exposures.plot(title='Factor Exposures')factor_pnl.cumsum().plot(title='Factor PnL')print(f'Compare to your portfolio UI here: https://marquee.gs.com/s/portfolios/{portfolio.id}/attribution')<jupyter_code>pm.schedule_reports(backcast=True)
risk_report = FactorRiskReport(risk_model_id='AXUS4M', fx_hedged=True)
risk_report.set_position_source(portfolio.id)
risk_report.save()

print(f'Portfolio created with ID "{portfolio.id}".')<jupyter_output><empty_output><jupyter_text>**And run risk calculations backcasted one year:**<jupyter_code>risk_results = risk_report.run(backcast=True, is_async=False)<jupyter_output><empty_output><jupyter_text>**Once that's done, you can pull the results directly from the `risk_results` object:**<jupyter_code>risk_results = risk_results[risk_results['factorCategory'] == 'Aggregations']

factor_exposures = risk_results.filter(items=['date', 'factor', 'exposure']).pivot(index='date', columns='factor', values='exposure')
factor_pnl= risk_results.filter(items=['date', 'factor', 'pnl']).pivot(index='date', columns='factor', values='pnl')

factor_exposures.plot(title='Factor Exposures')
factor_pnl.cumsum().plot(title='Factor PnL')


print(f'Compare to your portfolio UI here: https://marquee.gs.com/s/portfolios/{portfolio.id}/attribution')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1364290117115266, 'fraction_numerical': 0.003903842202588864, 'mean_word_length': 6.889789303079416, 'pattern_counts': {'":': 0, '<': 37, '<?xml version=': 0, '>': 37, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '637197', 'license': 'Apache-2.0', 'n_tokens_mistral': 1664, 'n_tokens_neox': 1561, 'n_words': 305, 'path': 'gs_quant/documentation/10_one_delta/demos/Create Backcasted Portfolio.ipynb', 'repo_name': 'webclinic017/gs-quant', 'size': '4867'}