<jupyter_start><jupyter_text>Author: <NAME> (<EMAIL>)  Key/Value API In this example we will show what are the principles behind Key/Value API.For this example we will create an FX Barrier Pricer.We will also introduce **NxPyTools.Create** and **NxPyTools.View** modules.  Excel example *Open FX_Barrier_option.xlsx*  Python Example  Most basic way of creating objects First we do all necessary imports<jupyter_code>from __future__ import print_function
import NxPySDK as nx    # this is standard Numerix SDK

import datetime<jupyter_output><empty_output><jupyter_text>First we need to create an Application object. All computations are going to be performed in that context.<jupyter_code>app = nx.Application()   # computation context
warning = nx.ApplicationWarning()     # needed to capture if something went wrong<jupyter_output><empty_output><jupyter_text>We may look at what is in an empty Application<jupyter_code>print(app)<jupyter_output>ID              UPDATED TYPE            WARNINGS
GLOBALHELPINFO  5       GLOBALHELPINFO  0       
GLOBALINDEXINFO 4       GLOBALINDEXINFO 0       
GLOBALINFO      0       GLOBALINFO      0       
GLOBALOBJECTS   1       GLOBALOBJECTS   0       
GLOBALPARSEINFO 3       GLOBALPARSEINFO 0       
GLOBALWARNINGS  2       GLOBALWARNINGS  0<jupyter_text>Then we need to start creating all objects one by one. The overall scheme is going to be the same:  - create ApplicationCall  - add headers and values  - register the object in the Application<jupyter_code># TODAY OBJECT:
# Create ApplicationCall first
c = nx.ApplicationCall()

# add headers and values
c.addValue('ID', 'TODAY')
c.addValue('NAME', 'TODAY')
c.addValue('OBJECT', 'EVENTS')
c.addValue('TYPE', 'SINGLE DATE')
c.addValue('DATES', datetime.date(2016, 7, 27))

# registering this object with Application
app.call(c, warning)<jupyter_output><empty_output><jupyter_text>let's see if this object actually showed up in the Application<jupyter_code>print(app)<jupyter_output>ID              UPDATED TYPE               WARNINGS
GLOBALHELPINFO  5       GLOBALHELPINFO     0       
GLOBALINDEXINFO 4       GLOBALINDEXINFO    0       
GLOBALINFO      0       GLOBALINFO         0       
GLOBALOBJECTS   1       GLOBALOBJECTS      0       
GLOBALPARSEINFO 3       GLOBALPARSEINFO    0       
GLOBALWARNINGS  2       GLOBALWARNINGS     0       
TODAY           6       EVENTS::SINGLEDATE 0<jupyter_text>Convenience functions We see that this will be a repetitive task so we might as well create some convenience functions for that. There are some convenience functions already implemented. Those are gathered in the **NxPyTools.Create module**.<jupyter_code># import Create module:
import NxPyTools.Create as nxCreate<jupyter_output><empty_output><jupyter_text>Now we can create objects a bit more easily. There is a number of possibilities which we encourage you to explore but here we will use the most straightforward one.Let's start with getting some help on that module:<jupyter_code># to find out what functions are available one may write:
help(nxCreate)
# let's create USD Yield Curve
nxCreate.register_call(app=app, headers=['ID', 'OBJECT', 'TYPE', 'NOWDATE', 'CURRENCY', 'RATE/DIVIDEND'], values=['YC_USD', 'MARKET DATA', 'YIELD', 'TODAY', 'USD', 0.05])<jupyter_output><empty_output><jupyter_text>We see that it returns registered ID for further use<jupyter_code># let's create GBP curve:
nxCreate.register_call(app=app, headers=['ID', 'OBJECT', 'TYPE', 'NOWDATE', 'CURRENCY', 'RATE/DIVIDEND'], values=['YC_GBP', 'MARKET DATA', 'YIELD', 'TODAY', 'GBP', 0.02])
# Instrument to be priced
instrument_id = nxCreate.register_call(app=app,
                       headers=['ID', 'OBJECT', 'TYPE', 'BARRIER LEVEL', 'BARRIER TYPE', 'BARRIER DIRECTION', 'CURRENCY', 'FOREIGN 1 CURRENCY', 'EXPIRY', 'PAYOUT CURRENCY'],
                       values=['FX_GBP_USD_INSTRUMENT', 'INSTRUMENT', 'FX BARRIER', 1.5, 'Knock In', 'DOWN', 'USD', 'GBP', datetime.date(2017, 7, 27), 'GBP'])
print(instrument_id)
# and the Pricer
nxCreate.register_call(app=app,
                      headers=['ID', 'OBJECT', 'TYPE', 'NOWDATE', 'SIGMA1', 'OPTION', 'DOMESTIC YIELD CURVE', 'FOREIGN 1 YIELD CURVE', 'SPOT PRICE', 'MODEL'],
                      values=['FX_BARRIER_PRICER', 'ANALYTIC', 'BARRIER OPTION', 'TODAY', 0.1, instrument_id, 'YC_USD', 'YC_GBP', 1.61, 'BLACK'])
print(app)<jupyter_output>ID                    UPDATED TYPE                    WARNINGS
FX_BARRIER_PRICER     10      ANALYTIC::BARRIEROPTION 0       
FX_GBP_USD_INSTRUMENT 9       INSTRUMENT::FXBARRIER   0       
GLOBALHELPINFO        5       GLOBALHELPINFO          0       
GLOBALINDEXINFO       4       GLOBALINDEXINFO         0       
GLOBALINFO            0       GLOBALINFO              0       
GLOBALOBJECTS         1       GLOBALOBJECTS           0       
GLOBALPARSEINFO       3       GLOBALPARSEINFO         0       
GLOBALWARNINGS        2       GLOBALWARNINGS          0       
TODAY                 6       EVENTS::SINGLEDATE      0       
YC_GBP                8       MARKETDATA::YIELD       0       
YC_USD                7       MARKETDATA::YIELD       0<jupyter_text>Reading results Similarly there are *standard ways* to read results from the objects being created. From Excel one knows Object Viewer. This is achieved in the following way in SDK:<jupyter_code>d = nx.ApplicationData()   # object where to store results
app.view('FX_BARRIER_PRICER', d, warning)<jupyter_output><empty_output><jupyter_text>Now *d* has results from the pricer. Let's see everything:<jupyter_code>print(d)<jupyter_output>NOWDATE               SPOT PRICE SIGMA1 SPOT DATE             CALL HEADERS          CALL VALUES           OUTPUT HEADERS  OUTPUT VALUES         DEPENDENCIES          QUOTES                      
27-jul-2016 0:0:0 UTC 1.61       0.1    27-jul-2016 0:0:0 UTC ID                    FX_BARRIER_PRICER     PRICE           0.573236490778931     FX_GBP_USD_INSTRUMENT #FX_BARRIER_PRICER.SIGMA1   
                                                              OBJECT                ANALYTIC              DELTA           -5.61468197532505     TODAY                 #FX_BARRIER_PRICER.SPOTPRICE
                                                              TYPE                  BARRIER OPTION        DELTA TRADER    -0.000903963798027332 YC_GBP                                            
                                                              NOWDATE               TODAY                 GAMMA           42.1175015910114      YC_USD                                            
                         [...]<jupyter_text>We see Object Viewer precisely. But often times we don't want to have access to everything but only to something specific.There are different ways to achieve this but let's use some convenience functions from the **NxPyTools.View module**.<jupyter_code>import NxPyTools.View as nxView
help(nxView)<jupyter_output>Help on module NxPyTools.View in NxPyTools:

NAME
    NxPyTools.View

FUNCTIONS
    all_as_dictionary(app, object_id, warning=None, headers_subset=[])
        Function returns a given object as a dictionary with dictionary keys from object view headers and
        with dictionary values from object view values (lists)
        
        :param app: Application object
        :param object_id: ID of the object to be queried
        :param warning: warning object to be used while querying the object. If C{None} a temporary will be created.
        :param headers_subset: request only provided list of headers. If C{subset} is empty then no restrictions.
        :return: Dictionary (key'd by headers) with corresponding lists as values
        :rtype: dict
    
    as_matrix(app, object_id, warning=None)
        This function returns an ApplicationMatrix instance from the Application.
        None and an error msg if there are any fatal errors
    
    as_string(app, object_id)
        This fu[...]<jupyter_text>We see a range of functions we could use. Let's briefly go through some of them:<jupyter_code># single output:
print('Delta: {}'.format(nxView.single_output(app=app, object_id='FX_BARRIER_PRICER', field_id='Delta', warning=warning)[0]))   # this function always returns list, so should access the first element<jupyter_output>Delta: -5.614681975325046<jupyter_text>Now this is fairly convenient but if there are **more outputs** you may want to grab all of them at once:<jupyter_code>res = nxView.outputs_as_dictionary(app=app, object_id='FX_BARRIER_PRICER')  # this returns a dictionary
print(res['Delta'])   # accessing single entries in the dictionary
print(res['Gamma'])<jupyter_output>-5.614681975325046
42.11750159101139<jupyter_text>Writing results to an XML file If one wants to save that structure in an XML file he can use the built in functionality:<jupyter_code>app.writeXML('C:/Python/XMLFiles/fx_pricer_manual.xml', warning)    
from myfirstpackage.specialfunctions import specialsum<jupyter_output><empty_output><jupyter_text>We will use that file in our next example<jupyter_code>sum = specialsum(1,2)

print (sum)
specialsum??<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.0754260582737768, 'fraction_numerical': 0.024189114898295765, 'mean_word_length': 2.802675585284281, 'pattern_counts': {'":': 0, '<': 56, '<?xml version=': 0, '>': 56, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 1}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '112478', 'license': 'MIT', 'n_tokens_mistral': 2857, 'n_tokens_neox': 2648, 'n_words': 851, 'path': '01_basic_object_creation_FX_BARRIER_OPTION.ipynb', 'repo_name': 'happy14142/JupyterWorkFlow', 'size': '9119'}