<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Umer Nalla on Medium]]></title>
        <description><![CDATA[Stories by Umer Nalla on Medium]]></description>
        <link>https://medium.com/@umer.nalla?source=rss-b172232f4cfa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*w732AD7LUTfOBWCD565n-Q.jpeg</url>
            <title>Stories by Umer Nalla on Medium</title>
            <link>https://medium.com/@umer.nalla?source=rss-b172232f4cfa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:06:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@umer.nalla/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Docker and Refinitiv Real-Time Connector for testing Streaming Market Data applications]]></title>
            <link>https://medium.com/lseg-developer-community/using-docker-and-refinitiv-real-time-connector-for-testing-streaming-market-data-applications-f4f6e2b56660?source=rss-b172232f4cfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4f6e2b56660</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Umer Nalla]]></dc:creator>
            <pubDate>Wed, 19 Jan 2022 16:35:01 GMT</pubDate>
            <atom:updated>2022-01-19T16:35:01.449Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Knowledge Prerequisite:</em></strong></p><ul><li>Working knowledge of Windows, developer tools, Refinitiv RT-SDK and basic Linux + Windows command line usage</li><li>Some experience of developing with Refinitiv Streaming APIs such as EMA, ETA and/or Websocket API</li></ul><h3>Introduction</h3><p>The Refinitiv Real-Time SDK, consisting of the high-level Enterprise Message API and lower-level Enterprise Transport API is recommended for developers writing or migrating a real-time streaming data Consumer, Posting (Contributor) or Provider application in Java or C++. <br>Alternatively, if you are using Python or other languages then you can also consider using the Websocket API for Consumer + Contributor applications.</p><h3>Testing your code</h3><p>Under normal circumstances, developers can test their:</p><ul><li>EMA, ETA or Websocket Consumer applications by connecting to a live feed:<br>- over the internet via Real-Time Optimised (RTO),<br>- via a deployed Refinitiv Real-Time Distribution System (RTDS)<br>- or the Refinitiv Real-Time Connector (RTC).</li><li>Provider type applications generally require an RTDS to publish the data to and to consume the published data from.</li><li>Contributor (Posting) applications require access to either<br>- Refinitiv Contributions Channel (for external contributions)<br>- RTDS (+ Contribution gateway — for external contributions)</li></ul><p>However, there can be scenarios when you as a developer may want to test your code without a live feed or access to an RTDS — for example:</p><ul><li>no access to an internet connection</li><li>no credentials or user ID required to consume data</li><li>test with a specific payload/content set</li><li>no access to your corporate network</li><li>your market Data team has not yet configured your RTDS system to receive data from your Provider</li><li>you want to test a Provider or Posting application with different payloads etc without causing any issue on the RTDS system</li><li>and so on…</li></ul><p>In my previous article — <a href="https://developers.refinitiv.com/en/article-catalog/article/testing-ema-consumer-provider-applications">Testing EMA Consumer and Provider Applications</a>, I covered a few different options such as<br>– direct connect between Provider and Consumer<br>– capture and playback of data<br>– playback of canned data<br>– using the Refinitiv Real-Time Connector (formerly known as ADS POP)</p><p>Of the above, I would say my favourite is probably using the Refinitiv Real-Time Connector. A simplistic way of describing RTC is ‘<em>a cut down RTDS in a single application</em>’ — a description which no doubt undersells RTC — but from a developer’s perspective, it provides what I need to test my applications without accessing (or disturbing) a real RTDS deployment. You may already be aware of the similar ADS POP application — which in simple terms was the precursor to RTC.</p><p>Why do I prefer using RTC to the other methods? Because it allows greater flexibility in my testing e.g.:<br>· some control over the ADS/ADH type functionality e.g., drop a service, log out a user, check various statistics and so on<br>· to Post (contribute) data to a Cache service that I define on the RTC<br>· connect &amp; test my Interactive and Non-Interactive providers without a dependency on the Market Data team</p><h3>Do you have access to an RTC?</h3><p>As mentioned in the above mentioned article, RTC is a licenced product — so may not be an option for all developers. However, many of our client organisations have the required licences which allow them access to RTC — so please check with your Market Data team or your Refinitiv Account team.</p><p>If you plan to attempt the following steps, you will need a valid Licence file for RTC in order to successfully complete the process.</p><p>If you do have an RTC licence available to you, in this article I am going to show how you can use RTC installed deployed in a Docker Desktop to test your Consumer, Provider and Contributor applications on your localhost Windows PC. If like me, you are relative Docker newbie, I will share some of what I have learnt about Docker along the way too.</p><p>If you are a competent Linux user, you should be able to adapt the notes below and achieve the same on your Linux device as well.</p><p><strong>NOTE</strong>: Before proceeding, please be aware of the two key points:</p><p>· Refinitiv does not officially support RTC running in a (Windows) Docker Desktop instance — official support is available with a standard Linux Docker deployment. However, I have found the above to be quite stable and given the next point — this should not be a major issue ….<br>· Whilst RTC is very convenient for local testing during the development phase, you are strongly advised to test all applications within the appropriate ‘<em>real</em>’ UAT environment before moving to UAT and Production stage. The live system will almost certainly be configured/optimised differently from the RTC container instance we are about to create.</p><h3>An article of two halves</h3><p>Due to the detailed nature of this article, it has been split into two parts</p><ul><li>This 1st half covers Basic installation and configuration to get an instance of RTC running inside a Docker container — supporting Consumer functionality</li><li>The 2nd half details the additional configuration of RTC to support Providers and Posting (contributions) — as well as a brief look at the RTC monitoring tool</li></ul><h3>Part 1 - Deploying RTC inside Docker</h3><p>Firstly, you need to ensure you have the Docker Desktop installed on your host PC. If you have not already done so, you can follow the official guides on the Docker website e.g. <a href="https://docs.docker.com/desktop/windows/install/">Install Docker Desktop on Windows</a> — guides for other OSs are available on the same website.</p><p>Assuming you have obtained an RTC Licence file from your Market Data team or Refinitiv Account team, you can then deploy an RTC Docker image and build the Docker container as detailed below.</p><h4>Local config, log and licence files</h4><p>Firstly, I am going to create a localhost directory structure, where I store and access my RTC config, log files and licence file — outside of the Docker container.<br>I do this so that these files persist outside of the RTC container — allowing me to</p><ul><li>deploy the licence file, edit the config file, view the log files easily from Windows</li><li>rebuild the docker container (e.g. when a new version is released) easily</li></ul><p>So, for example, I created the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*XvZ4Gf2tH5Km8CWAGW8BaA.png" /><figcaption>My RTC container directory structure</figcaption></figure><p>where the:</p><ul><li><strong>config</strong> folder contains my RTC config file and licence file</li><li>the <strong>debug</strong> folder is where any RTC debug will be stored</li><li>and <strong>log</strong> folder will contain the RTC log files</li></ul><p>The above folders are on my localhost (Windows) drive, However, the RTC container also needs to access the config files and output debug and log files. Therefore, I will need to define some <strong>bind mounts</strong>, to mount the above directories inside my RTC container.</p><p>Why am I creating bind mounts? Docker does not store persistent data inside containers and files written to a container’s storage won’t be accessible once the container is stopped. Also, accessing files inside a container’s storage even while it’s running is not easy. By using bind mounts, we can ensure these files persist outside the container and are easily accessible using the standard host’s file system tools.</p><p>In the <strong>config </strong>folder, I will place the<br>· RTC config file — <strong>rtc.cnf</strong><em> </em>(see later for details)<br>· RTC License file — <strong>REFINITIV_LICENSE </strong>(you should have already obtained)</p><h4>My Docker Compose file</h4><p>The bind mounts and other docker operations &amp; config can be performed on the command line using docker commands. However, I prefer to use a <strong>docker-compose.yml</strong> file which will allow me to put my related config in one place and do the following with a single docker command:</p><p>· specify and pull my RTC image<br>· define my ports<br>· define my bind mounts<br>· compose my container</p><p>I created a <strong>docker-compose.yml</strong> file that looks like this:</p><pre>version: &quot;3&quot;<br>services: <br>    <strong>rtc</strong>:<br>        container_name: <strong>rtc</strong><br>        hostname: <strong>rtc</strong><br>        restart: &quot;always&quot;<br>        image: <strong>refinitivrealtime/rtc:3.5.4.L1</strong><br>        ports: <br>            <strong>- 14002:14002<br>            - 14005:14005<br>            - 14003:14003<br>            - 15000:15000<br>            - 8080:8080<br>            - 8101:8101</strong><br>        volumes: <br>            - <strong>&quot;c:/docker/rtc353/config:/opt/distribution/config&quot;<br>            - &quot;c:/docker/rtc353/debug:/opt/distribution/debug&quot;<br>            - &quot;c:/docker/rtc353/log:/opt/distribution/log&quot;</strong></pre><p>For now, I copied the above docker-compose.yml file into my c:\docker\rtc354 folder — and I will come back to this later.</p><p>Let’s breakdown of the above in a bit more detail:</p><p>1. set the <strong>service</strong>, <strong>container</strong> and <strong>host</strong> name all to <strong>rtc<br></strong>2. set to <strong>restart</strong> policy to automatically restart the container if it stops (unless manually stopped) — full details at <a href="https://docs.docker.com/config/containers/start-containers-automatically/">Start containers automatically | Docker Documentation</a><br>3. specify the docker image to pull from the Docker Hub — at the time of writing that was version <strong>3.5.4.L1</strong> <br>4. <a href="https://docs.docker.com/config/containers/container-networking/">publish</a> the ports for the RTC container that I want to interact with from my Windows OS:<br>· 14002: RSSL Consumer connecting to RTC<br>· 14003: Non-interactive provider connecting to RTC<br>· 14005: Interactive provider to listen for RTC connection (<em>non-default value</em>)<br>· 15000: WebSocket Consumer to RTC<br>· 8101: Legacy MarketFeed SSL subscriber to RTC</p><p>5. specify my bind mounts e.g., <em>c:/docker/rtc354/config:/opt/distribution/config</em></p><ul><li>Where <em>c:/docker/rtc354/config</em> is my local host path for my config files and</li><li>Where <em>/opt/distribution/config</em> is the RTC docker container config file path</li></ul><p>By default, an Interactive Provider and the RTC would communicate on port 14002 — however, since I may want to run both Consumer and IProvider on my host PC, I have changed the IProvider port to 14005 (I will come back to this in the 2nd half).</p><p>Before I can create my RTC container, I need to configure my RTC as per my requirements. For my usage scenarios, I want to configure my RTC to:</p><ul><li>Connect to a Refinitiv Real-Time Optimized (RTO) feed for my live streaming data.</li><li>Define a cache service so that I can test Contributions code by Posting data to the cache</li><li>Configure at least one Interactive and one Non-Interactive service</li></ul><h3>Initial RTC Configuration</h3><p>For the initial phase, I configured only the basics required to get an instance of RTC up and connected to RTO (the Refinitiv Real-Time internet based streaming data service). If you don’t have access to RTO and want to use your own internal RTDS feeds — speak to your Market Data team for the necessary config parameters.</p><p>I am not an RTDS or RTC expert, so I took a vanilla <strong>rtc.cnf</strong> file from an RTC package and just ‘hacked’ it to meet my above requirements. I have included a <a href="https://github.com/umernalla/My-Cnf-Files/raw/main/vanilla-rtc.cnf">vanilla rtc.cnf</a> for your reference.<br>I have also provided a copy of <a href="https://github.com/umernalla/My-Cnf-Files/raw/main/my-rtc.cnf">my modified rtc.cnf</a> file — minus my credentials. So, in theory, you could just add your credentials/connectivity params and run.<br>However, I think it would be useful to look at the key changes I made — to provide some understanding for when want to customise RTC to your needs. Just to be clear, whichever file you use — it will need to be renamed to <strong>rtc.cnf</strong></p><p>If you have an internal Market Data team — they should be able to help you configure your RTC as per your needs.</p><p><strong>NOTE</strong>: for some of the following rtc.cnf entries, you will be <strong>updating</strong> existing entries — for others, you will be <strong>adding</strong> new entries — so note the wording I use.</p><h4>Connect to an RTO feed</h4><p>This step is only required if you are using Refinitiv Real-Time Optimised — if you are sourcing your real-time data from an internal ADS, speak to your Market Data team — they should be able to help you configure your RTC appropriately.</p><p>Most of the RTO related changes I made were based on my colleague’s excellent article — <a href="https://developers.refinitiv.com/en/article-catalog/article/introduction-to-the-refinitivrealtime-adspop-docker-image">Configuring adspop docker to connect to Refinitiv Real-Time Optimized</a> (adspop is the precursor to RTC)<br>In the rtc.cnf, update the <strong>routeList </strong>configuration to cloud so it will connect to the Refinitiv Real-Time Optimized.</p><p><strong>*rtc*routeList : <em>cloud</em></strong></p><p>Next, I need to provide my RTO MachineID and Password — however, the password needs to be obfuscated first</p><p>To obfuscate my password, I used the <strong>dacsObfuscatePassword </strong>tool that comes with the RTC package — which your Market Data team should be able to supply you with.</p><p>If not, you can download the same tool from our Developer Portal’s RT-SDK Tools Downloads page — <a href="https://developers.refinitiv.com/en/api-catalog/refinitiv-real-time-opnsrc/rt-sdk-cc/downloads#refinitiv-real-time-sdk-tools">Refinitiv Real-Time SDK — Tools</a>. On that page, you will note there is a <a href="https://developers.refinitiv.com/content/dam/devportal/api-families/elektron/elektron-sdk-c/downloads/dacs_obfuscate_login.zip">Windows</a> and <a href="https://developers.refinitiv.com/content/dam/devportal/api-families/elektron/elektron-sdk-c/downloads/obfuscate_tool_b_1_0.zip">Linux</a> version of ‘<em>RCC — Dacs Obfuscate Login Tool</em>’.</p><p>Once you unpack the above zip file, you will find the dacsObfuscatePassword tool which you can run as follow:</p><p><strong>C:&gt; DacsObfuscateLogin -e &lt;your MachineID password&gt;<br></strong>Or<br> <strong>#./dacsObfuscatePassword -e &lt;your MachineID password&gt;</strong></p><p>to generate an obfuscated version of your password.</p><p>And then update the userName and obfuscated userPassword entries in the rtc.cnf as follows:<br><strong> *rtc*cloud.route*userName : <em>&lt;your RTO machine ID&gt;</em><br> *rtc*cloud.route*userPassword : <em>&lt;your obfuscated password&gt;</em></strong></p><p>You can also update your location entry — so that RTO will connect to the closest endpoints — the default is us-east. However, as I am based in the UK, I updated mine to:<br> <strong>*rtc*cloud.route*location : <em>eu-west</em></strong></p><p>If you are in APAC, you could update it to:<br> <strong>*rtc*cloud.route*location</strong> : <strong><em>ap-southeast</em></strong></p><p><strong>Note</strong>: Whilst the RTC container is running, it will be logged into RTO using the above MachineID. So, if you need to use the same MachineID in another application — you can stop the RTC container, to avoid any login conflicts.</p><h4>Licence File</h4><p>I also updated the location of my licence file to match the bind mount folder I defined earlier in my docker-compose.yml file:<br> <strong>*rtc*licenseFile</strong> : <strong>/<em>opt/distribution/config</em>/</strong>REFINITIV_LICENSE</p><p>For reference, the licence file you have been provided should look something like this:</p><pre>{<br>LICENSEID = &lt;xxx&gt;<br>KEY = &lt;license &gt;<br>LICENSEE = &lt;your details&gt;<br>NODEID = * (for temp licence)<br>EXPIRATION = &lt;Date&gt;<br>LICENSETYPE = &lt;Type&gt;<br>PRODUCT = RTC<br>VERSION = 3.5<br>…<br>…<br>}</pre><h4>Dictionary + Logfile folders</h4><p>I also updated the log file path to match the container folder defined in my docker-compose.yml file:<br><strong> *rtc*logger*file : <em>/opt/distribution/log</em>/rtc.log</strong></p><p>RTC needs dictionary files to decode the data — a set of which are included in the RTC docker image. When the container is created, it places them in the container’s /opt/distribution/etc folder.<br>However, a default rtc.cnf is looking elsewhere, so I updated the location as below:<br><strong> *fieldDictionary : <em>/opt/distribution/etc</em>/RDMFieldDictionary<br> *enumFile : <em>/opt/distribution/etc</em>/enumtype.def</strong></p><h3>Deploy and run the RTC container — finally(!)</h3><p>Once I copied the updated rtc.cnf and REFINITIV_LICENSE files into my config folder, I then proceeded to build and run my RTC container.<br>If you recall, earlier on I copied by docker-compose.yml file into my c:\docker\rtc354 folder — which I then ‘<em>run’</em> using the following command.</p><p><strong>c:\docker\rtc354&gt; <em>docker-compose up -d</em></strong></p><p>The above command creates and starts my RTC instance in detached mode — i.e., runs the container in the background. The first time you run the above, the output should look something like this:</p><pre>[+] Running 16/16<br> - rtc Pulled                        16.1s<br>   - 1e7cdd8e55f9 Pull complete       9.4s<br>   - ac8f959ec7d9 Pull complete       9.5s<br>   - fd08f01e9913 Pull complete       9.8s<br>   - db7070756e15 Pull complete       9.8s<br>   - 491754c3df24 Pull complete       9.9s<br>   - 97edfd880226 Pull complete       9.9s<br>   - 6334591e144e Pull complete      10.0s<br>   - 4a0d7610dbad Pull complete      10.0s<br>   - 61fa6819281f Pull complete      10.1s<br>   - 28ebdd3b2b7c Pull complete      10.2s<br>   - 7d59bce42f1c Pull complete      11.5s<br>   - 6e0927527697 Pull complete      11.6s<br>   - 2596cef2f39d Pull complete      11.7s<br>   - b2240f2b1c86 Pull complete      13.1s<br>   - f75501f123b7 Pull complete      13.1s<br>[+] Running 1/1<br> - Container rtc  Started             1.7s</pre><p>To confirm the RTC container is running, you can execute:</p><p><strong>C:&gt;<em>docker inspect -f {{.State.Running}} rtc</em></strong></p><p>which should return true.</p><p>You could also use the Docker Desktop Dashboard to check the status:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*aX-G0Qn-5iyqN7Uh6RZasw.png" /><figcaption>Docker dashboard showing RTC is up and running</figcaption></figure><p>If the RTC fails to start, then you can check the log folder e.g., c:\docker\rtc354\log for the rtc.log file. If the content of the log file does not help you identify the issue, please speak to you Market Data team or raise a support ticket on <a href="https://my.refinitiv.com/content/mytr/en/productsupport.html">My.Refinitiv</a> for the <em>Refinitiv Real-Time Distribution System</em> product.</p><h4>Using VS Code to interact with Docker</h4><p>I should mention here that if like me, you are a fan of Visual Studio Code, you can also use that to deploy Docker Containers and interact with them — by installing the various Docker related extensions for VS Code — <a href="https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-docker">Docker — Visual Studio Marketplace</a></p><p>For example, if I open the folder containing my docker-compose.yml file inside VS code, I can then right-click the yml file and run Compose Up / Down / Restart etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*715d6vgvkZxVb_E2.png" /></figure><p>I can also inspect the Docker Containers and Images from within VS Code as well restart/stop a container or delete an Image/Container and so on:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/0*0e8HPBc2rcruzhQ4.png" /></figure><p>Assuming the RTC container started up and RTC is running, you can then connect a Websocket API or RT-SDK consumer example to consume some data from RTC using localhost:14002 (for RSSL connection) or localhost:15000 (for Websocket connection).</p><p>For instance, I can test it with any Consumer example such as 100_MP_Streaming that is supplied with EMA Java or C++.<br>I just need to ensure I have<br>· changed the code to consume data from the ELEKTRON_DD service<br>· and the host is set to localhost:14002</p><pre>OmmConsumer consumer( OmmConsumerConfig().host( &quot;localhost:14002&quot; ).username( &quot;user&quot; ));<br> <br>consumer.registerClient( ReqMsg().serviceName( &quot;ELEKTRON_DD&quot; ).name( &quot;IBM.N&quot; ), client );</pre><p>When I run the Consumer example it will connect to the RTC instance on port 14002 and request some data from the ELKTRON_DD service.</p><p>If you are using the Websocket API and normally request data without specifying a service name e.g.:</p><pre>{<br>  &quot;ID&quot;: 2,<br>  &quot;Key&quot;: {<br>    &quot;Name&quot;: &quot;TRI.N&quot;<br>  }<br>}</pre><p>there is one more change you will need to make to the rtc.cnf file — i.e., specifying a default service for WebSocket requests — see towards the end of the article for details. <br>In the meantime, you could just change your code to specify a service name in the JSON request message e.g.:</p><pre>{<br>  &quot;ID&quot;: 2,<br>  &quot;Key&quot;: {<br>    &quot;Name&quot;: &quot;TRI.N&quot;,<br>    <strong>&quot;Service&quot;:&quot;ELEKTRON_DD&quot;</strong><br>  }<br>}</pre><h3>Part 2 — Configure RTC for Providers and Posting</h3><p>Once I had the basic Docker install, deployment and RTC configuration out of the way, I moved onto the focus of these articles — i.e., configuring the RTC to allow me to:</p><ul><li>Post data to a cache</li><li>Test both Interactive and Non-Interactive Providers more easily</li><li>Access some functionality normally only available to the MDS admin team</li></ul><h3>Configure RTC for a Posting Cache and NIProvider service</h3><p>The first thing I added was a service that would allow me to test Post (Contributor) type applications as well as Non-Interactive provider code.</p><p>To enable the NI-Provider functionality of the RTC, I activated the RsslServer as follows (in the rtc.cnf file):</p><pre>!!! RSSL<br>*rtc*enableRsslServer : True<br>*rtc*rsslServerPort : distribution_rssl_source<br>*rtc*distribution_rssl_source*serverToClientPings : True<br>*rtc*distribution_rssl_source*clientToServerPings : True<br>*rtc*distribution_rssl_source*pingTimeout : 30<br>*rtc*distribution_rssl_source*minPingTimeout : 6<br>*rtc*distribution_rssl_source*maxConnections : 100<br>*rtc*distribution_rssl_source*guaranteedOutputBuffers : 200<br>*rtc*distribution_rssl_source*maxOutputBuffers : 400<br>*rtc*distribution_rssl_source*compressionType : 0<br>*rtc*distribution_rssl_source*zlibCompressionLevel : 3<br>*rtc*distribution_rssl_source*interfaceName :<br>*rtc*distribution_rssl_source*reusePort : False<br>*rtc*distribution_rssl_source*connectionType : 0<br>*rtc*distribution_rssl_source*serverCert :<br>*rtc*distribution_rssl_source*serverPrivateKey :</pre><p>In the above section, I set the first parameter to <strong><em>True </em></strong>and removed the ‘<strong>!</strong>’ comment from the remaining lines in the section.</p><p>I then defined a service called <strong>NI_PUB </strong>that I could</p><ul><li>Post (contribute) data from a Posting application</li><li>Publish data to from a NIProvider application:</li></ul><pre>!!! Non-interactive Cache for Posting + NIPROV<br>*rtc*cacheServiceList : NI_PUB<br>*rtc*NI_PUB*cacheLocation : ssl<br>*rtc*NI_PUB*cacheType : sourceDriven<br>*rtc*NI_PUB*maxCache : 50000<br>*rtc*NI_PUB*domainsCached : ALL<br>*rtc*NI_PUB*capabilityList : 6, 7, 8, 9, 10<br>*rtc*NI_PUB*buildCacheFromUpdates : False<br>*rtc*NI_PUB*markItemsOkOnUpdate : False<br>*rtc*NI_PUB*forwardPostUserInfo : False<br>*rtc*NI_PUB*dumpAccessLockFileName :<br>*rtc*NI_PUB*dumpAuditUserInfoFileName :<br>*rtc*NI_PUB*convertMfeedDataToRWF : False<br>*rtc*NI_PUB*validateMfeedToRWFConvForPosts : False<br>*rtc*NI_PUB*enableOverrideInsertRecordResp : False<br>*rtc*NI_PUB*overrideClearCache : False</pre><p>Once I saved the above changes to my rtc.cnf file, I restarted my RTC container — via the Docker Dashboard, VS Code or from the cmd line e.g.</p><p><strong>C:&gt;<em>docker restart rtc</em></strong></p><p>Where rtc is the container name — as defined in the yml file.</p><p>To test if the above changes were valid, I used an EMA Posting example and NIProvider example.</p><p><strong>NOTE</strong>: For all the test scenarios below, I am using EMA C++ examples — the same tests can be done with EMA Java — by making similar changes to the equivalent EMA Java example. Likewise, ETA developers should also be able to perform similar testing with the appropriate changes to the equivalent ETA examples.</p><h4>Testing the Post (contribution) functionality</h4><p>For a Posting test, we can use the EMA example 341_MP_OffStreamPost with the following changes in the <strong><em>main()</em></strong> and <strong><em>onRefreshMsg()</em></strong> methods:</p><pre>// changes to <strong><em>main()</em></strong> method<br>UInt64 handle = consumer.registerClient( ReqMsg()<br> .domainType( MMT_MARKET_PRICE )<br> .serviceName( &quot;<strong>NI_PUB</strong>&quot; ).name( &quot;<strong>MYTEST.RIC</strong>&quot; ), client, closure );<br> <br>// changes to <strong><em>onRefreshMsg()</em></strong> method:<br>_pOmmConsumer-&gt;submit( PostMsg().postId( postId++ )<br>  .serviceName( &quot;NI_PUB&quot; )<br>  .name( &quot;MYTEST.RIC&quot; ).solicitAck( true ).complete().payload(<br>      RefreshMsg().payload(FieldList()<br>          .addReal(<strong>25,35</strong>,OmmReal::<strong>ExponentPos1Enum </strong>).complete())<br>          .complete() ), ommEvent.getHandle() );</pre><p>Once you build and run the example, you should some output like:</p><pre>Received:    AckMsg<br>Item Handle: 1999905924208<br>Closure:     0000000000000001<br>Item Name: not set<br>Service Name: not set<br>Ack Id: 1<br> <br>Received:    RefreshMsg<br>Handle: 1999902871904 Closure:     0000000000000001<br>Item Name: <strong>MYTEST.RIC</strong><br>Service Name: <strong>NI_PUB</strong><br>Item State: Open / Ok / None / &#39;&#39;<br>Name: <strong>ASK </strong>Value: <strong>350</strong></pre><p>As you will note, we first get</p><ul><li>the AckMsg acknowledging the Post was accepted by the RTC server</li><li>then we see the RefreshMsg confirming that the MYTEST.RIC subscription request to the RTC server was successful</li><li>and the payload has an ASK field as per the Post message we submitted earlier.</li></ul><p>NOTE: As a colleague (thank you Zoya!) rightly pointed out — the first time you test the Posting functionality described above, you may see an ‘<strong><em>F10 — Not in Cache</em></strong>’ error. This would be the case if the RIC you are contributing to, does not yet exist (and we are requesting it in the <em>main()</em> method).</p><h4>Test the NI-Provider functionality</h4><p>For the NIProvider testing, we can use any of the EMA NIProvider examples such as <strong>100_MP_Streaming</strong> — from the <strong>NIProvider </strong>folder (– not Consumer folder).</p><p>The example as provided should already have the host set to<em> </em><strong><em>localhost:14003</em></strong> and the service name should be set to <strong><em>NI_PUB</em></strong> in the source code.</p><p>If you run the NIProv100 example, you should see some warnings about missing Dictionary configuration, followed by something like:</p><pre>loggerMsg<br> TimeStamp: 16:11:17.744<br> ClientName: ChannelCallbackClient<br> Severity: Success<br> Text: Received ChannelUp event on channel Channel_7<br> Instance Name Provider_1_1<br> Connected component version: rtc3.5.3.L1.linux.rrg 64-bit<br>loggerMsgEnd</pre><p>The above message confirms that the NIProvider successfully connected to the RTC instance. The example will then run for around 60 seconds publishing updates to the RTC server before exiting. To see some evidence that the data is really being published, we will need to fire up a Consumer example connecting to the RTC and subscribing to the service and instrument name as used by the NIProvider.</p><p>We can re-use the Consumer example <strong>100_MP_Streaming</strong> example — just change the service and instrument name as follows:</p><pre>consumer.registerClient(ReqMsg()<br>    .serviceName(&quot;<strong>NI_PUB</strong>&quot;).name(&quot;<strong>IBM.N</strong>&quot;), client );</pre><p>If you then run <strong>NIProv100 </strong>in one console and <strong>Cons100 </strong>in a 2nd console, you should see Cons100 receiving a Refresh and Updates for IBM.N from NI_PUB</p><pre><strong><em>&gt;Cons100</em></strong><br>RefreshMsg<br>    streamId=&quot;5&quot;<br>    name=&quot;IBM.N&quot;<br>    serviceName=&quot;NI_PUB&quot;<br>    Payload dataType=&quot;FieldList&quot;<br>        FieldList FieldListNum=&quot;0&quot; DictionaryId=&quot;0&quot;<br>            FieldEntry fid=&quot;22&quot; name=&quot;BID&quot; dataType=&quot;Real&quot; value=&quot;33.94&quot;<br>            FieldEntry fid=&quot;25&quot; name=&quot;ASK&quot; dataType=&quot;Real&quot; value=&quot;39.94&quot;<br>            FieldEntry fid=&quot;30&quot; name=&quot;BIDSIZE&quot; dataType=&quot;Real&quot; value=&quot;13&quot;<br>            FieldEntry fid=&quot;31&quot; name=&quot;ASKSIZE&quot; dataType=&quot;Real&quot; value=&quot;19&quot;<br>        FieldListEnd<br>    PayloadEnd<br>RefreshMsgEnd<br> <br>UpdateMsg<br>    streamId=&quot;5&quot;<br>    name=&quot;IBM.N&quot;<br>    serviceId=&quot;10000&quot;<br>    serviceName=&quot;NI_PUB&quot;<br>    Payload dataType=&quot;FieldList&quot;<br>        FieldList<br>            FieldEntry fid=&quot;22&quot; name=&quot;BID&quot; dataType=&quot;Real&quot; value=&quot;33.95&quot;<br>            FieldEntry fid=&quot;30&quot; name=&quot;BIDSIZE&quot; dataType=&quot;Real&quot; value=&quot;14&quot;<br>        FieldListEnd<br>    PayloadEnd<br>UpdateMsgEnd</pre><h3>Configure for Interactive Provider services</h3><p>Finally, I wanted to configure the RTC to support a couple of IProvider services — i.e., the RTC mounting an IProvider application running on my local (Windows) host PC. When the RTC receives any data requests for those services, it will forward those requests onto my IProvider — which can then choose to fulfil or reject the requests.</p><p>The first step was to define a route for my Interactive Provider service — so I updated the existing route list:</p><p><strong>*rtc*routeList : cloud,<em>iprov</em></strong></p><p>And then declared the services for that route — note that I am also changing the port for this route to <strong><em>14005</em></strong></p><pre>!!! IPROV on Windows Host Route<br>*rtc*iprov.route*serviceList : <strong>IPROV, DIRECT_FEED</strong><br>*rtc*iprov.route*port : <strong>14005</strong><br>*rtc*iprov.route*hostList : host.docker.internal<br>*rtc*iprov.route*userName : umer.nalla<br>*rtc*iprov.route*protocol : rssl<br>*rtc*iprov.route*singleOpen : True<br>*rtc*iprov.route*allowSuspectData : True<br>*rtc*iprov.route*disableDataConversion : True<br>*rtc*iprov.route*compressionType : 1<br>*rtc*iprov.route*pingInterval : 2<br>*rtc*iprov.route*maxCache : 50000<br>*rtc*iprov.route*IPROV*appServiceName : IPROV<br>*rtc*iprov.route*DIRECT_FEED*appServiceName : DIRECT_FEED</pre><p>You could just define a single service — however, I wanted some flexibility for testing purposes. Most of the EMA IProvider examples and the default EMA config file are hardcoded with the <strong>DIRECT_FEED </strong>service name. Defining an additional <strong>IPROV </strong>service just allows me to validate any config changes etc I make (to ensure I am not inadvertently relying on some defaults).</p><p>I defined the services as follows:</p><pre>!!! Interactive Provider<br>*rtc*serviceList : IPROV, DIRECT_FEED<br>*rtc*IPROV*cacheLocation : srcApp<br>*rtc*IPROV*cacheType : sinkDriven<br>*rtc*IPROV*maxCache : 50000<br>*rtc*IPROV*domainsCached : ALL<br>*rtc*IPROV*capabilityList : 6, 7, 8, 9, 10<br>*rtc*IPROV*buildCacheFromUpdates : False<br>*rtc*IPROV*markItemsOkOnUpdate : False<br>*rtc*IPROV*forwardPostUserInfo : False<br>*rtc*IPROV*dumpAccessLockFileName :<br>*rtc*IPROV*dumpAuditUserInfoFileName :<br>*rtc*IPROV*convertMfeedDataToRWF : False<br>*rtc*IPROV*validateMfeedToRWFConvForPosts : False<br>*rtc*IPROV*enableOverrideInsertRecordResp : False<br>*rtc*IPROV*overrideClearCache : False<br>!!! Interactive Provider<br>*rtc*DIRECT_FEED*cacheLocation : srcApp<br>*rtc*DIRECT_FEED*cacheType : sinkDriven<br>*rtc*DIRECT_FEED*maxCache : 50000<br>*rtc*DIRECT_FEED*domainsCached : ALL<br>*rtc*DIRECT_FEED*capabilityList : 6, 7, 8, 9, 10</pre><p>As before, once the modified rtc.cnf file had been saved, I restarted the RTC container — via the Docker Dashboard, VS Code or from the cmd line e.g.</p><p><strong>C:&gt;<em>docker restart rtc</em></strong></p><h4>Test the Interactive-Provider functionality</h4><p>Once restarted, I can test my IProvider application. However, I need to ensure that the IProvider application will listen on port <strong><em>14005 </em></strong>(for the inbound RTC connection) — rather than the default 14002 (I covered the reason for doing this in part 1).</p><p>For instance, as I was using the <strong>IProv100 </strong>example, I changed the OmmProvider port configuration as follow:</p><pre>OmmProvider <strong>provider</strong>( OmmIProviderConfig()<br>    .<strong>port</strong>( &quot;<strong>14005</strong>&quot; ), appClient );</pre><p>Once I make the above change, rebuild and and fire up <strong>IProv100</strong>, I should see something like:</p><pre>&gt;<strong><em>IProv100.exe<br></em></strong>loggerMsg<br>TimeStamp: 15:38:49.023<br>    ClientName: ServerChannelHandler<br>    Severity: Success<br>    Text:    Received ChannelUp event on client handle 2214874061056<br>        Instance Name Provider_1_1<br>        Connected component version: rtc3.5.3.L1.linux.rrg 64-bit<br>loggerMsgEnd</pre><p>To test the IProvider I can then run a Consumer example connecting to the RTC and requesting data from the DIRECT_FEED service. Once again, I can re-use the Consumer example <strong>100_MP_Streaming </strong>example — by just changing the service name as follows:</p><pre>consumer.registerClient(ReqMsg()<br>    .serviceName(&quot;<strong>DIRECT_FEED</strong>&quot;).name(&quot;<strong>TRI.N</strong>&quot;), client );</pre><p><strong>NOTE</strong>: Just to be clear, the consumer will still be using port 14002 — connecting to the RTC, which will forward any item requests onto the IProvider on port 14005.</p><p>Provided the IProv100 (pun intended!) is still running, the Consumer should get some data back e.g.:</p><pre>RefreshMsg<br>    streamId=&quot;5&quot;<br>    domain=&quot;MarketPrice Domain&quot;<br>    Solicited<br>    RefreshComplete<br>    state=&quot;Open / Ok / None / &#39;Refresh Completed&#39;&quot;<br>    name=&quot;TRI.N&quot;<br>    serviceName=&quot;DIRECT_FEED&quot;<br>    Payload dataType=&quot;FieldList&quot;<br>        FieldList<br>            FieldEntry fid=&quot;22&quot; name=&quot;BID&quot; dataType=&quot;Real&quot; value=&quot;39.90&quot;<br>            FieldEntry fid=&quot;25&quot; name=&quot;ASK&quot; dataType=&quot;Real&quot; value=&quot;39.94&quot;<br>            FieldEntry fid=&quot;30&quot; name=&quot;BIDSIZE&quot; dataType=&quot;Real&quot; value=&quot;9&quot;<br>            FieldEntry fid=&quot;31&quot; name=&quot;ASKSIZE&quot; dataType=&quot;Real&quot; value=&quot;19&quot;<br>        FieldListEnd<br>    PayloadEnd</pre><p>And so on….</p><p>When you move on from your development phase &amp; your Interactive Provider application is ready for UAT testing and connecting to your real RTDS system, remember to change the port back to the default 14002 (or whichever port your RTDS system uses).</p><h3>Admin functions with rtcmon</h3><p>The RTC package also includes an admin and monitoring tool called <strong>rtcmon </strong>(short for RTC Monitor)– which can be found in the /opt/distribution folder of the RTC container.</p><p>So, if I attach a shell to the RTC container with:<br> <strong>C:&gt; <em>docker exec -it rtc /bin/bash<br></em></strong>And then run rtcmon:<br> <strong># <em>rtcmon</em></strong></p><p><strong>OR </strong>as pointed out by a reader (thank you!), you can use the one-line alternative:<br><strong> C:&gt;</strong> <strong><em>docker exec -it -w /opt/distribution/ rtc ./rtcmon<br></em></strong>(where the -w param is setting the working directory to the location of rtcmon before executing it)</p><p>You should see something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*xEHGhDoG3QdkEXJc.png" /></figure><p>You can then experiment with the tool to see things like how many items each connected application has open or to drop services to observe the impact on your application etc.</p><p><strong>Note:</strong> you will need to use Linux style navigation keys e.g. H, J, K, L for cursor movement, Tab for changing sections etc — as detailed in the <a href="https://my.refinitiv.com/content/dam/myrefinitiv/products/9936/en/Technical/633574.pdf">RTC System Admin manual</a>.</p><p>For example, to drop a service I perform the following:<br>· Select ‘<strong><em>Source Routes and Application Proxies</em></strong>’<br>· Tab to the ‘<strong><em>List of Source Routes</em></strong>’<br>· Select the route for the service you want to drop e.g. ‘<strong><em>cloud</em></strong>’<br>· Select the routeEnabled value (<em>Enter to edit, Ctrl+U to delete existing value</em>)<br>· Replace the True with False to drop the service</p><p>My application should then receive a Status Message indicating ‘Service down’ for any open instruments.<br>Once I have checked my application behaviour, I can set the above value back to True and the instrument should recover with a Refresh Message.</p><h4>Configure a default service for WebSocket Requests</h4><p>As mentioned earlier, the RTC can be configured such that when making Websocket API requests, you don’t need to explicitly specify a service name — RTC can default to a configured service.<br>This requires an additional change to the rtc.cnf file as follows:<br> <strong>*rtc*defaultJsonServiceId : <em>10002</em></strong></p><p>Where the <strong><em>10002 </em></strong>represents the default service to use — however, this value may differ on your RTC installation.<br>To work out the correct Service Id, I fired up <strong>rtcmon </strong>and selected the ‘<strong><em>Service Statistics</em></strong>’ option and noted the ID for ELEKTRON_DD — which in my case was <strong><em>10002:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*2ecS-eANeOCC_Nfq.png" /></figure><p>Once I added the above ServiceId to my rtc.cnf, I restarted rtc as before</p><p><strong>C:&gt;<em>docker restart rtc</em></strong></p><p>I should then be able to make Websocket API requests from ELEKTRON_DD, without specifying the service name:</p><pre>{<br>  &quot;ID&quot;: 2,<br>  &quot;Key&quot;: {<br>    &quot;Name&quot;: &quot;TRI.N&quot;<br>  }<br>}</pre><h3>Other rtcmon + RTC functionality</h3><p>There are probably other stats/figures and functions you can discover &amp; experiment with in the relative safety of your own little ‘<em>RTDS</em>’ installation — by referring to the RTC System Admin manual linked below (your MDS admin team may also be able to advise you further) .</p><p>You can also experiment with/test other scenarios to observe their impacts on your application e.g.</p><ul><li>stop/restart RTC container</li><li>kill RTC service from the docker bash shell</li><li>restart docker</li><li>deploy multiple RTC instances — to test scenarios like<br>- failover (with ChannelSets) when one RTC instance is stopped (and possibly restarted later)<br>- publishing to multiple servers<br>- source aggregation</li></ul><h3>Summary</h3><p>As a developer having to code &amp; test their Refinitiv Real-time Consumers, Providers and Posting (Contribution) applications there are certain test scenarios that have a certain level of reliance on our local Market Data Admin teams. These teams are often quite stretched and may not able to be able to provide access to the RTDS testing resources in a timely manner — potentially causing a bottleneck in our testing regime.</p><p>Having access to our own Refinitiv Real-Time Connector can allow us to perform some of the tests at our pace and time of choosing — before we do our final testing in the ‘real’ RTDS environment. I hope the above guide will help you in the same way it has helped me in my RTDS testing regime without having to vie for my Market Data admin’ time.</p><h3>Documentation/Articles referenced:</h3><ul><li><a href="https://docs.docker.com/desktop/windows/install/">Install Docker Desktop on Windows</a></li><li><a href="https://docs.docker.com/config/containers/start-containers-automatically/">Start containers automatically | Docker Documentation</a></li><li><a href="https://developers.refinitiv.com/en/article-catalog/article/testing-ema-consumer-provider-applications">Testing EMA Consumer and Provider Applications</a></li><li><a href="https://docs.docker.com/config/containers/container-networking/">Docker Container Networking</a></li><li><a href="https://developers.refinitiv.com/en/article-catalog/article/introduction-to-the-refinitivrealtime-adspop-docker-image">Configuring ‘adspop’ docker to connect to Refinitiv Real-Time Optimized</a></li><li><a href="https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-docker">Docker — Visual Studio Marketplace</a></li><li><a href="https://my.refinitiv.com/content/dam/myrefinitiv/products/9936/en/Technical/633574.pdf">Real-Time Connector System Admin manual</a></li><li>A vanilla <a href="https://github.com/umernalla/My-Cnf-Files/raw/main/vanilla-rtc.cnf">rtc.cnf</a> — for you to modify as you work through the article</li><li>My modified <a href="https://github.com/umernalla/My-Cnf-Files/raw/main/my-rtc.cnf">rtc.cnf</a> (in case you don’t!) — just fill in your credentials</li></ul><p><strong>NOTE</strong>: As mentioned before, I am nothing like an RTDS/RTC or Docker expert by a long shot — the above is based on my experimentation and pulling materials from various Refinitiv sources — feel free to contact me with corrections/improvements.</p><p>You can find additional links to related articles and the official Developer Portal pages for the RT-SDK etc in the right-hand panel at the top of this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4f6e2b56660" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lseg-developer-community/using-docker-and-refinitiv-real-time-connector-for-testing-streaming-market-data-applications-f4f6e2b56660">Using Docker and Refinitiv Real-Time Connector for testing Streaming Market Data applications</a> was originally published in <a href="https://medium.com/lseg-developer-community">LSEG Developer Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coding & Testing Linux Applications on Windows using WSL and VS Code]]></title>
            <link>https://medium.com/lseg-developer-community/coding-testing-linux-applications-on-windows-using-wsl-and-vs-code-5afcd7a8721c?source=rss-b172232f4cfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/5afcd7a8721c</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[wsl]]></category>
            <dc:creator><![CDATA[Umer Nalla]]></dc:creator>
            <pubDate>Thu, 02 Sep 2021 10:12:29 GMT</pubDate>
            <atom:updated>2021-09-02T10:12:29.401Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will share my experience of using <strong>Windows Subsystem for Linux</strong> along with <strong>Visual Studio Code</strong> for some basic coding and testing in C++ &amp; Java. Whilst I will be using some of the examples from the Refinitiv Real-time SDKs — the notes below should be applicable to general C++ and Java development.</p><p>I will start with</p><ul><li>an overview of some key relevant WSL + VS Code features I discovered</li><li>followed by the detailed steps I carried out in order to be able to edit, compile and run C++ &amp; Java examples inside the WSL environment.</li></ul><p><strong><em>Knowledge Prerequisite</em> </strong>— working knowledge of Windows, developer tools such as make, JVMs and a basic understanding of Linux console usage</p><h3>A Windows diehard!</h3><p>I have been a Windows developer for most of my career — I started with MS-DOS-based development before quickly moving onto Windows development. I may have interacted with a SQL Server or Oracle systems over the years, but these would have always been via a Windows-based interface/utility.</p><p>When I joined Reuters back in 2004 I discovered that our real-time streaming APIs came in both Windows and Linux versions and most of our clients’ real-time data applications were deployed on Linux — which makes sense — improved performance and stability compared to Windows (certainly back then).</p><p>So, I had to adapt and start familiarising myself with Linux. But for someone who had spent most of their working life with Windows and MS-DOS, this did not come easy. I seriously struggled — the joys of Vi, the considerable difference between cmd.exe and the various Linux shells etc. When possible I always did my coding or tried recreating a customer issue on Windows. If all worked OK on Windows, then I would migrate it to Linux or try and recreate the issue on Linux as required. I had to rely on tools like <strong>WinSCP</strong> and <strong>PuTTY</strong> to transfer files and access our Linux test machines.</p><p>It’s not like I did not want to learn Linux — just the infrequent usage and lack of time meant I never made any reasonable progress.</p><p>Things got a bit easier with virtualisation products such as VMWare and VirtualBox — allowing me to use a GUI interface with Linux and only resort to a Linux shell when I absolutely had to. However, there was always the issue of reduced performance and the headache of maintaining the VM, configuring the network settings etc and VMs that mysteriously stopped working…</p><p>Some of you may ask <em>‘What about Docker?’- </em>we have published some Docker Container Images for our Real-Time SDKs (see links below) which I find useful for basic testing. However, I personally did not find that Docker offered me the same flexibility and integration suited to my workflow.</p><h3>Windows Subsystem for Linux</h3><p>You can imagine my hopefulness when I first started hearing the great promises Microsoft were making around their new Windows Subsystem for Linux.</p><p>My first experiments around WSL simply involved copying across the Linux versions of our SDKs and trying to build and run them. Any coding/editing was still done on Windows and copying the files/changes back and forth between Windows to Linux as required.</p><p>Initially, I was typing long winded command lines like:</p><pre><strong>cp /mnt/c/Refinitiv/RTSDK-2.0.2.L1.win.rrg/Cpp-C/Ema/Examples/Training/Consumer/100_Series/100_MP_Streaming/Consumer.cpp .</strong></pre><p>before I discovered the WSL File Explorer integration.</p><p>The integration works really well — allowing you to access the WSL directory structure from Windows File Explorer by navigating to <strong>Network-&gt;wsl$</strong> — if you cannot see the wsl$ share then just type in wsl$ into the address bar and then selecting the required WSL installation (you will note below that I got carried away and installed four WSL versions):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*xJs_suMetayzDvsH.png" /><figcaption>View all WSL Distro file systems from Windows File Explorer</figcaption></figure><p>You can then navigate the Linux directory structure using Windows File Explorer — below I have navigated to my Linux home directory and into the RT-SDK directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*4EkmHwz37VjQ2lmY.png" /><figcaption>Exploring WSL File system from Windows File Explorer</figcaption></figure><p>Alternatively, from a WSL terminal, you can invoke File Explorer by typing in <strong>explorer.exe .</strong> — where the dot specifies the current Linux directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/0*s7czzTjhg4mPT7v3.png" /><figcaption>Invoke Windows File Explorer from WSL Terminal</figcaption></figure><p>which brings up file explorer in the same directory as the WSL terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/0*PFo-KPBuFSKngAmr.png" /><figcaption>Windows File Explore view of WSL file system directories</figcaption></figure><h3>Visual Studio Code WSL Integration</h3><p>Whilst I used full-blown Visual C++ for my Windows RT-SDK C++ coding etc, around the same time as I was exploring WSL, I had also started using Visual Studio Code for editing and running Python scripts — it starts up quicker and Microsoft is continuously improving the Python integration with VS Code.</p><p>At some point, VS Code alerted me to the existence of a WSL extension — <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl"><strong>Remote — WSL</strong></a><strong> </strong>— which ‘<em>allows VS Code on Windows to build Linux applications that run on WSL</em>’.<strong> </strong>After installing and checking out the extension, I initially felt the phrase ‘build Linux applications’ was a bit of an exaggeration — nonetheless, the ability to directly edit source code in my WSL file system directly from a Windows IDE definitely scored points with me (no more manual having to navigate the $wsl — which to me seems slower than using VS Code + WSL extension).</p><p>It is worth noting here that the <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl"><strong>Remote — WSL</strong></a> extension is actually part of the VS Code <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack">Remote Development</a> extension pack — which include SSH support and Docker integration.</p><h3>Visual Studio 2019 and 2022 — Improved WSL Integration</h3><p>If you are a C++ developer and have a full Visual Studio licence, then it gets even more interesting:</p><ul><li><a href="https://devblogs.microsoft.com/cppblog/c-with-visual-studio-2019-and-windows-subsystem-for-linux-wsl/">Visual Studio 2019 version 16.1 added native support for using C++ with WSL</a></li><li><a href="https://devblogs.microsoft.com/cppblog/build-and-debug-c-with-wsl-2-distributions-and-visual-studio-2022/">Visual Studio 2022 introduces an improved WSL 2 toolset for C++ development</a> — which allows you to build and debug C++ code on WSL</li></ul><p>I did briefly try out the steps in the VS2019 blog post, but it did not work for me as described — will no doubt try again at a later date.</p><p>That’s the background covered, so let’s crack on and look at what I did in order to set up my C++ and Java dev environment on WSL.</p><h3>Setting up a basic C++ Linux Dev environment on WSL</h3><p>As you may have guessed, my primary objective was to be able to run build and run Linux versions of our APIs/SDKs such as the Refinitiv Real-Time SDK.</p><p>As the RT-SDK is qualified/tested with RHEL and other related distros such as Centos, Oracle Linux — I installed the <strong>Fedora Remix for WSL</strong> — which is available from both the Microsoft store and Github (see links below). I also briefly tested with Pengwin Enterprise WSL (upgraded to Oracle Linux) and that seemed to work fine too.</p><h3>Enabling WSL and Installing a Linux distro</h3><p>As there are plenty of online resources on how to install WSL on Windows, I will refer you to the Microsoft one that I used — <a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10">Install WSL on Windows 10 | Microsoft Docs</a>. At Step <strong>6</strong> of these instructions, you can install Fedora Remix from the <a href="https://www.microsoft.com/en-gb/p/fedora-remix-for-wsl/9n6gdm4k2hnc?activetab=pivot:overviewtab">Microsoft Store</a> or <a href="https://github.com/WhitewaterFoundry/Fedora-Remix-for-WSL">GitHub</a> — or another Redhat based distro such as Pengwin Enterprise or Centos (I have not tested with Centos or others).</p><h3>Setting up our basic Linux Dev environment</h3><p>Once I had complete my Fedora Remix WSL installation and set my root password etc, I had to carry out the following steps to install the basic development tools such as git, cmake, compiler etc (If you use a different distro, the installation requirements may vary based on what is already packaged with that distro).</p><p>Note that I will be installing the Refintiv Real-Time SDK in my Linux home directory (rather than the commonly used <em>opt </em>directory) — as the <em>opt </em>directory needs sudo permissions — and I don’t want to keep having to <em>sudo</em> or <em>su root </em>each time I want to change some source code etc.</p><p>Open up a WSL terminal and perform the following steps to</p><ul><li>install git</li><li>install my c++ related tools</li><li>clone the RT-SDK repository from GitHub</li><li>install cmake</li><li>get an XML library used by RT-SDK</li></ul><pre># install git<br>sudo yum install git</pre><pre># install openssl and development package<br>sudo yum install openssl<br>sudo yum install openssl-devel</pre><pre># some development tools<br>sudo yum group install &quot;Development Tools&quot;</pre><pre># some distros include gcc-c++ in dev tools - so you may not need this step - but I did<br>sudo yum install gcc-c++</pre><pre># download clone the Refinitiv RT-SDK into my home directory (~)<br><strong>cd</strong>~<br>git <strong>clone</strong> --recursive <a href="https://github.com/refinitiv/Real-Time-SDK.git">https://github.com/refinitiv/Real-Time-SDK.git</a></pre><pre># download and unpack cmake into the <em>opt </em>directory<br><strong>cd</strong> /opt<br>sudo wget <a href="https://cmake.org/files/v3.21/cmake-3.21.0-linux-x86_64.tar.gz">https://cmake.org/files/v3.21/cmake-3.21.0-linux-x86_64.tar.gz</a><br>sudo tar -xvf cmake-3.21.0-linux-x86_64.tar.gz</pre><pre># download XML Library<br>sudo wget <a href="http://xmlsoft.org/sources/libxml2-2.9.9.tar.gz">http://xmlsoft.org/sources/libxml2-2.9.9.tar.gz</a></pre><h3>Build our RT-SDK Makefiles</h3><p>We can now use the previously downloaded <strong>cmake</strong> to create our Linux Makefiles for the RT-SDK (cmake v3.14 or higher) — which I will do in a sub-directory of my home directory.</p><pre># change to home directory<br><strong>cd</strong> ~</pre><pre># create a directory for our makefiles<br>mkdir rtbuild<br><strong>cd</strong> rtbuild</pre><pre># create a subdirectory for external XML library<br>mkdir -p external/dlcache<br>cp /opt/libxml2-2.9.9.tar.gz external/dlcache</pre><pre># add cmake to PATH<br><strong>export</strong> PATH=/opt/cmake-3.21.0-linux-x86_64/bin:<strong>$PATH</strong></pre><pre>#build the makefiles - see documentation for list of parameters<br>cmake ../Real-Time-SDK -DBUILD_UNIT_TESTS=OFF</pre><h3>Build an example and run it</h3><p>Once we have our makefiles, we can then build one of the examples and run it</p><pre># build Consumer example 100<br>make Cons100</pre><pre># LD_LIBRARY_PATH = directories where executables search for shared libraries<br><strong>export</strong> LD_LIBRARY_PATH=~/rtbuild/install/lib64</pre><pre># change to executables directory and run example 100<br><strong>cd</strong> ~/Real-Time-SDK/Cpp-C/Ema/Executables/LIN5_64_GCC1121/Optimized/<br>./Cons100</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/0*VUe-JGQpmUUH4uZg.png" /><figcaption>Running a Linux C++ application in WSL</figcaption></figure><h3>Editing the Linux source in VS Code</h3><p>Once I had an example running, the next step was to modify the code e.g. to test out a customer scenario.</p><p>As mentioned above, previously I would edit the code in Windows and then copy the file across to the relevant Linux directory before running the make command again.</p><p>However, once I discovered the <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl">Remote — WSL</a> extension for VS Code, my workflow became much smoother.</p><p>There are a couple of different ways of utilising the VS Code WSL integration.</p><h3>Invoke VS Code from WSL Terminal</h3><p>If you already have a WSL Terminal then you could invoke VS Code from the command line by typing <strong><em>code .</em></strong> from the directory where your source code is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-lO0NjTpQRl18YG2.png" /><figcaption>Invoke Visual Studio Code from WSL terminal</figcaption></figure><p>Which should present Visual Studio code with the WSL directory opened up for you.</p><p>Note below the WSL Distro name is shown in the bottom left corner and the title bar makes it clear you are editing a WSL file (as opposed to a local one)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IeyQNA7EIaA33SVb.png" /><figcaption>Editing code from WSL file system in VS Code</figcaption></figure><p>If however, you don’t have a WSL terminal open and perhaps you are already in VS Code or you just want to go straight to editing a source file, you can invoke WSL from VS Code.</p><h3>Invoking WSL from VS Code</h3><p>Click the WSL button in the bottom left-hand corner and choose the appropriate choice from the drop-down list presented by VS Code.</p><p>For example, if you only have one WSL distro installed or you want to use your default distro, you can just select <strong><em>New WSL Window</em></strong>.</p><p>If you have multiple distros, then you can select <strong><em>New WSL Window Using Distro…</em></strong> and choose the required Distro you wish to work with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/0*DP7qS-bRWf1M5W36.png" /><figcaption>VS Code — attach to WSL distro</figcaption></figure><p>You can change the default WSL distro by opening a windows CMD prompt or Powershell and executing <em>wslconfig /l</em> to list your distros and then<em> wslconfig /s &lt;distroname&gt;</em> to change your default.</p><h3>Building and Executing code direct from VS Code</h3><p>Once you have made your code changes, you can build and execute the application from within VS Code by opening a Terminal inside VS Code and executing your make and run commands within the terminal.</p><p>I personally prefer to have two terminals open — one in the makefile folder (e.g my <strong><em>rtbuild </em></strong>in this instance) and one in the executables folder — so I can easily make changes, build and execute. Note the two <strong><em>bash </em></strong>icons on the right-hand side — which you can use to flick between the terminals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GFILQ18xvZNfg-G-.png" /><figcaption>C++ Example running in VS Code WSL Terminal</figcaption></figure><p>As you can see, the WSL + VS Code Remote extension certainly makes it easier to code, edit and run C++ Linux applications on a Windows device.</p><p>As a next step, I plan to explore the newer features of Visual Studio 2019 and 2022 — which promise to provide an even simpler workflow. I will hopefully report back my findings here or in another article.</p><h3>Setting up a basic Java development environment on WSL?</h3><p>Given that Java is designed to be ‘Write Once, Run Everywhere” I should NOT really need to set up a Java Linux dev environment on WSL.</p><p>However, for me, I just wanted to have the option to test the Java version of our RT-SDK on Linux. I recall several years ago, there was an incident with one of our older Java APIs where the customer issue could only be recreated on a Linux environment. I have never come across this with our newer RT-SDK — nevertheless, I felt it was better to be prepared — just in case.</p><h3>Building and running a Java example on my Fedora Remix WSL</h3><p>Very little action was required in order to run one of the RT-SDK Java examples on my WSL.</p><p>I just did a search to see what packages were available, picked a version compatible with our RT-SDK and installed it.</p><pre># get a list of available Java packages<br>sudo dnf search openjdk</pre><pre># install a compatible development package<br>sudo dnf install java-11-openjdk-devel</pre><pre># build and run an RT-SDK example<br><strong>cd</strong> ~/Real-Time-SDK/Java/</pre><pre># build the jar files (a once off)<br>./gradlew jar</pre><pre># Run consumer example 100<br>./gradlew runconsumer100</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/0*CI-SFOizeNzT4wGy.png" /><figcaption>Java Example running in WSL Terminal</figcaption></figure><p>As per before, I can also edit the code and run the example from VS Code as required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IrMD0HXwNZCOjMSY.png" /><figcaption>Java Example running in VS Code WSL Terminal</figcaption></figure><h3>Summary</h3><p>As a Windows developer having to code &amp; test under Linux, the combination of Windows Subsystem for Linux and Visual Studio Code really has made life simpler for me. I can do most of my work in my comfort zone of Windows and still easily recreate customer’s Linux specific scenarios and test Linux versions of our examples with a minimum of effort.</p><p>I hope you found my experience useful and are able to apply some of the above in your own developer workflows.</p><p><strong>Some of the key links referenced in the article:</strong></p><ul><li>VS Code <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl">Remote — WSL</a> extension (part of the <a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack">Remote Development</a> extension pack)</li><li>Microsoft blog post: <a href="https://devblogs.microsoft.com/cppblog/c-with-visual-studio-2019-and-windows-subsystem-for-linux-wsl/">Visual Studio 2019 version 16.1 added native support for using C++ with WSL</a></li><li>Microsoft blog post: <a href="https://devblogs.microsoft.com/cppblog/build-and-debug-c-with-wsl-2-distributions-and-visual-studio-2022/">Visual Studio 2022 introduces an improved WSL 2 toolset for C++ development</a></li><li>Microsoft Guide to <a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10">Installing WSL on Windows 10 | Microsoft Docs</a></li><li>Fedora Remix WSL from the <a href="https://www.microsoft.com/en-gb/p/fedora-remix-for-wsl/9n6gdm4k2hnc?activetab=pivot:overviewtab">Microsoft Store</a> or <a href="https://github.com/WhitewaterFoundry/Fedora-Remix-for-WSL">GitHub</a></li><li>Our <a href="https://github.com/Refinitiv/Real-Time-SDK">Refinitiv/Real-Time-SDK on github.com</a></li></ul><h4>Developer Portal Resources for the Refinitiv Real-Time-SDK</h4><ul><li><a href="https://developers.refinitiv.com/en/article-catalog/article/choosing-your-refinitiv-realtime-streaming-api">Choosing your Refinitiv Real-Time Streaming API | Refinitiv Developers</a></li><li><a href="https://developers.refinitiv.com/en/article-catalog/article/introduction-elektron-message-api">Introduction to Enterprise Message API | Refinitiv Developers</a></li><li><a href="https://developers.refinitiv.com/en/article-catalog/article/introduction-to-the-refinitivapis-elektronsdkc-docker-image">Introduction to the refinitivapis/realtimesdk_c Docker Image | Refinitiv Developers</a></li><li><a href="https://developers.refinitiv.com/en/article-catalog/article/introduction-to-the-refinitivapis-realtimesdkjava-docker-image">Introduction to the refinitivapis/realtimesdk_java Docker Image | Refinitiv Developers</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5afcd7a8721c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lseg-developer-community/coding-testing-linux-applications-on-windows-using-wsl-and-vs-code-5afcd7a8721c">Coding &amp; Testing Linux Applications on Windows using WSL and VS Code</a> was originally published in <a href="https://medium.com/lseg-developer-community">LSEG Developer Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Instrument Pricing Analytics — Zero Coupon Curves]]></title>
            <link>https://medium.com/lseg-developer-community/instrument-pricing-analytics-zero-coupon-curves-379fd1b396bb?source=rss-b172232f4cfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/379fd1b396bb</guid>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[curves]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[bonds]]></category>
            <category><![CDATA[interest-rates]]></category>
            <dc:creator><![CDATA[Umer Nalla]]></dc:creator>
            <pubDate>Mon, 24 May 2021 15:39:24 GMT</pubDate>
            <atom:updated>2021-05-24T15:39:24.134Z</atom:updated>
            <content:encoded><![CDATA[<h3>Instrument Pricing Analytics — Zero Coupon Curves</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_T3RlTYhGhEhItw6rjC0SA.jpeg" /></figure><p>In one of my earlier articles on<a href="https://medium.com/refinitiv-developer-community/instrument-pricing-analytics-volatility-surfaces-and-curves-developer-community-8b70b01cd277"> Instrument Pricing Analytics — Volatility Surfaces and Curves</a>, I mentioned I would deliver a follow up article on Zero Coupon Curves — another of the related IPA content sets.</p><p>Zero Coupon Curves, like other pricing data (Volatility Surfaces, Inflation Curves), are used to model risk factors and can be used to power risk management or valuation systems.</p><p>As with the previous article I think the best way to highlight this content is via some code and a few graphs — so let me dive straight into the code….</p><p><strong>NOTE</strong>: As some of the actual <strong>JSON input requests </strong>and output <strong>responses </strong>are very long, I have <strong>heavily truncated</strong> some of them in the code sections below. The full inputs and outputs are included in the<strong> </strong><a href="https://github.com/Refinitiv-API-Samples/Article.RDPLibrary.Python.ZeroCouponCurves"><strong>Jupyter Notebook file on GitHub</strong></a><strong>.</strong></p><h4>Initialisation</h4><p>First thing I need to do is import my libraries and then run my scripts to define my helper functions. As you will note I am importing the Refinitiv Data Platform library which will be my main interface to the Platform — as well as few commonly used Python libraries.</p><pre>import json<br>import <strong>refinitiv.dataplatform as rdp</strong><br>import configparser as cp<br>from IPython.display import HTML<br>import matplotlib.pyplot as plt<br>import pandas as pd<br><br>%run &quot;../plotting_helper.ipynb&quot;</pre><p>As the name would suggest, the plotting_helper contains the full plotting code. I won&#39;t share any of the plotting code snippets in this article - please refer to the actual file on GitHub (see link in right hand panel).</p><h4>Connect to the Refinitiv Data Platform</h4><p>I fetch my credentials from a configuration file and use them to open a Platform session — If I were a Desktop user of Eikon or Refinitiv Workspace, I could open a Desktop session instead.</p><pre>config = cp.ConfigParser()<br>config.read(&quot;c:/Refinitiv/config.cfg&quot;)<br>session = rdp.<strong>open_platform_session</strong>(config[&#39;platform&#39;][&#39;<strong>app_key</strong>&#39;],<br>    rdp.GrantPassword( username=config[&#39;platform&#39;][&#39;<strong>user</strong>&#39;], <br>                      password=config[&#39;platform&#39;][&#39;<strong>password</strong>&#39;] )<br>)</pre><pre># OR for Eikon / Workspace account<br>#session = rdp.<strong>open_desktop_session</strong>(app_key=config[&#39;desktop&#39;][&#39;<strong>app_key</strong>&#39;])</pre><h4>Endpoint Interface</h4><p>In my previous article I mentioned how the Refinitiv Data Platform library consists of different layers:</p><ol><li>Function: Highest level — single function call to get data</li><li>Content: High level — Fuller response and Level 1 Streaming data too</li><li>Delivery: For Level 2 Streaming data and data sets not supported by above Layers</li></ol><p>Whilst there is some support for Instrument Pricing Analytics (IPA) data in the Function Layer, I will use the Delivery layer as it works for all IPA content on the platform. <br>Each unique content set on the Platform has its own Endpoint and we can use the Delivery Layers Endpoint interface to access that content.</p><p>Using the Endpoint interface to request IPA content is fairly straightforward</p><ol><li>Identify the required IPA Endpoint (URL)</li><li>Use the Endpoint Interface to send a request to the Endpoint</li><li>Decode the response and extract the IPA data</li></ol><h4>Identifying the Surfaces Endpoint</h4><p>To ascertain the Endpoint, we can use the Refinitiv Data Platform’s <a href="http://api.refinitiv.com/">API Playground</a> — an interactive documentation site you can access once you have a valid Refinitiv Data Platform account.</p><p>So, firstly I can search for <em>‘curves’</em> to narrow down the list of Endpoints and then select the relevant Endpoint from the list. At the time of writing, there are 3 related Endpoints available and I will use all of them in this article.</p><p>I copy the required Endpoint URLs e.g. — <strong><em>/data/quantitative-analytics-curves-and-surfaces/v1/curves/zc-curves</em></strong> — to use with the Endpoint interface as follows:</p><h4>Define our API Endpoints for the ZC Curve definitions and ZC Curves data</h4><pre>zcCurveDefinitions_endpoint = rdp.Endpoint(session, <br>    &#39;https://api.refinitiv.com/data/<strong>quantitative-analytics-curves-and-surfaces/v1/curves/zc-curve-definitions</strong>&#39;)<br><br>zcCurve_endpoint = rdp.Endpoint(session, <br>    &#39;https://api.refinitiv.com/data/<strong>quantitative-analytics-curves-and-surfaces/v1/curves/zc-curves</strong>&#39;)<br><br>forward_zcCurve_endpoint = rdp.Endpoint(session, <br>    &quot;https://api.refinitiv.com/data/<strong>quantitative-analytics-curves-and-surfaces/v1/curves/forward-curves</strong>&quot;)</pre><h4>Querying Curve Definitions</h4><p>Before we can request a ZC Curve we need to have an idea of what curves are actually available on the Refinitiv Data Platform.</p><p>Our interactions with the platform takes the form of JSON messages i.e. <strong>JSON</strong> <strong>requests </strong>and JSON <strong>responses</strong>.</p><p>We can use the Curve Definitions Endpoint to discover what is currently available by sending a JSON request.</p><p>For instance, if I want to discover the full list of what Refinitiv has available in terms of ZC Curves, I can send a request with a single parameter i.e. the Source:</p><pre>request_body={<br>  &quot;universe&quot;: [<br>    {<br>      &quot;<strong>source</strong>&quot;: &quot;<strong>Refinitiv</strong>&quot;<br>    }<br>  ]<br>}<br><br>response = <strong>zcCurveDefinitions_endpoint</strong>.send_request(<br>    method = rdp.Endpoint.RequestMethod.POST,<br>    body_parameters = request_body<br>)<br><br>pd.DataFrame(data=response.data.raw[&quot;data&quot;][0][&quot;curveDefinitions&quot;]).sort_values(by=&#39;currency&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWkgLcPllY_fu2l01o53Vw.png" /><figcaption>Curve Definitions from Refinitiv Source</figcaption></figure><p>I extract the Curve Definitions data from the JSON response and convert it to a Pandas Dataframe for easier viewing.<br> As you will note, the definition includes various properties including the Currency as well as available Tenors and Discounting Tenors.</p><p>At the time of writing, we have 61 Curves available from Refinitiv on the Data Platform.<br> It is also possible that in the future we could offer Curves from other non-Refinitiv Sources.</p><h4>Filtering the list of Curve Definitions</h4><p>You can restrict the list of curves returned by specifying a filter e.g. <strong>Currency</strong>:</p><pre>request_body={<br>  &quot;universe&quot;: [<br>    {<br>      &quot;source&quot;: &quot;Refinitiv&quot;,<br>      &quot;<strong>currency</strong>&quot;: &quot;<strong>USD</strong>&quot;<br>    }<br>  ]<br>}<br><br>response = zcCurveDefinitions_endpoint.send_request(<br>    method = rdp.Endpoint.RequestMethod.POST,<br>    body_parameters = request_body<br>)<br><br>pd.DataFrame(data=response.data.raw[&quot;data&quot;][0][&quot;curveDefinitions&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwmacWhHCtpHm50hbL31Pw.png" /><figcaption>Curve Definitions for USD</figcaption></figure><p>Note that the source is optional at present, as Refinitiv is the only source available.</p><h4>Multiple Curve Definitions for some Currencies</h4><p>Some currencies have multiple curves e.g. <strong>JPY</strong> and <strong>EUR</strong>:</p><pre>request_body={<br>  &quot;universe&quot;: [<br>    {<br>      &quot;currency&quot;: &quot;<strong>JPY</strong>&quot;<br>    }<br>  ]<br>}<br><br>response = zcCurveDefinitions_endpoint.send_request(<br>    method = rdp.Endpoint.RequestMethod.POST,<br>    body_parameters = request_body<br>)<br><br>pd.DataFrame(data=response.data.raw[&quot;data&quot;][0][&quot;curveDefinitions&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5FOafisr-MA0TnM8FBSuA.png" /><figcaption>JPY Curves</figcaption></figure><p>You can refer to the curve properties to identify the differences e.g. a given currency may have curves based on different indices as well as Market Data Locations — as we see above with the <strong>‘JPY TIBOR EMEA’</strong> curve.</p><pre>request_body={<br>  &quot;universe&quot;: [<br>    {<br>      &quot;currency&quot;: &quot;EUR&quot;<br>    }<br>  ]<br>}<br><br>response = zcCurveDefinitions_endpoint.send_request(<br>    method = rdp.Endpoint.RequestMethod.POST,<br>    body_parameters = request_body<br>)<br><br>pd.DataFrame(data=response.data.raw[&quot;data&quot;][0][&quot;curveDefinitions&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8ITRjAwXWT67vTy1e8eeg.png" /></figure><h4>Requesting a curve by its ID</h4><p>Once you have discovered the ID of a curve you can request it directly — for example the <strong>JPY TIBOR (EMEA) Swap ZC Curve</strong> — note that I have selected the <strong>1M Discounting Tenor</strong> from the available ones:</p><pre>request_body = {<br>    &quot;universe&quot;: [<br>        {<br>            &quot;curveDefinition&quot;: {<br>                &quot;id&quot;: &quot;<strong>a865716b-e437-4045-84b5-f6483d8b6a25</strong>&quot;,<br>                &quot;discountingTenor&quot;: &quot;1M&quot;<br>            }<br>        }]<br>}<br><br>response = zcCurve_endpoint.send_request(<br>    method = rdp.Endpoint.RequestMethod.POST,<br>    body_parameters = request_body<br>)</pre><h4>Detailed Response — curve points data — Definition + Parameters</h4><p>Note how the JSON Response contains the Curve points data, which is preceded by the full definition and the default Parameters that were used to generate the curve.<br> If you wish to request user defined curves with some variations, you can extract these details from the response and tweak some of the parameters to form your own custom request.</p><pre>print(json.dumps(response.data.raw, indent=2))</pre><pre>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;<strong>curveParameters</strong>&quot;: {<br>        &quot;extrapolationMode&quot;: &quot;None&quot;,<br>        &quot;interpolationMode&quot;: &quot;CubicDiscount&quot;,<br>        &quot;interestCalculationMethod&quot;: &quot;Dcb_Actual_Actual&quot;,<br>        &quot;priceSide&quot;: &quot;Mid&quot;,<br>        &quot;calendarAdjustment&quot;: &quot;Calendar&quot;,<br>        &quot;calendars&quot;: [<br>          &quot;JAP_FI&quot;<br>        ],<br>        &quot;compoundingType&quot;: &quot;Compounded&quot;,<br>        &quot;useMultiDimensionalSolver&quot;: true,<br>        &quot;useConvexityAdjustment&quot;: true,<br>        &quot;useSteps&quot;: false,<br>        &quot;convexityAdjustment&quot;: {<br>          &quot;meanReversionPercent&quot;: -6.9606,<br>          &quot;volatilityPercent&quot;: 0.142<br>        },<br>        &quot;valuationDate&quot;: &quot;2021-05-19&quot;,<br>        &quot;ignoreExistingDefinition&quot;: false<br>      },<br>      &quot;<strong>curveDefinition</strong>&quot;: {<br>        &quot;availableTenors&quot;: [<br>          &quot;OIS&quot;,<br>          &quot;1M&quot;,<br>          &quot;3M&quot;,<br>          &quot;6M&quot;<br>        ],<br>        &quot;currency&quot;: &quot;JPY&quot;,<br>        &quot;mainConstituentAssetClass&quot;: &quot;Swap&quot;,<br>        &quot;riskType&quot;: &quot;InterestRate&quot;,<br>        &quot;indexName&quot;: &quot;TIBOR&quot;,<br>        &quot;source&quot;: &quot;Refinitiv&quot;,<br>        &quot;name&quot;: &quot;JPY TIBOR (EMEA) Swap ZC Curve&quot;,<br>        &quot;marketDataLocation&quot;: &quot;EMEA&quot;,<br>        &quot;id&quot;: &quot;a865716b-e437-4045-84b5-f6483d8b6a25&quot;,<br>        &quot;discountingTenor&quot;: &quot;1M&quot;,<br>        &quot;indexTenors&quot;: [<br>          &quot;1M&quot;,<br>          &quot;3M&quot;,<br>          &quot;6M&quot;<br>        ]<br>      },<br>      &quot;<strong>curves</strong>&quot;: {<br>        &quot;<strong>1M</strong>&quot;: {<br>          &quot;curvePoints&quot;: [<br>            {<br>              &quot;discountFactor&quot;: 1.0,<br>              &quot;endDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;ratePercent&quot;: 0.033463900578256656,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;0D&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 0.9999981666700277,<br>              &quot;endDate&quot;: &quot;2021-05-21&quot;,<br>              &quot;ratePercent&quot;: 0.033463900578256656,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;2D&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 0.9999917500562983,<br>              &quot;endDate&quot;: &quot;2021-05-28&quot;,<br>              &quot;ratePercent&quot;: 0.03346384092193233,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;1W&quot;,<br>              &quot;instruments&quot;: [<br>                {<br>                  &quot;instrumentCode&quot;: &quot;ZTIJPY1WD=&quot;<br>                }<br>              ]<br>            },<br>          ],<br>          &quot;isDiscountCurve&quot;: true<br>        },<br>.....<br><strong><em>Truncated</em></strong><br>.....        &quot;3M&quot;: {<br>          &quot;curvePoints&quot;: [<br>            {<br>              &quot;discountFactor&quot;: 1.0,<br>              &quot;endDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;ratePercent&quot;: 0.033463900578256656,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;0D&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 0.9999981666700277,<br>              &quot;endDate&quot;: &quot;2021-05-21&quot;,<br>              &quot;ratePercent&quot;: 0.033463900578256656,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;2D&quot;<br>            },<br><br>          ],<br>          &quot;isDiscountCurve&quot;: false<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>        },<br>        &quot;6M&quot;: {<br>          &quot;curvePoints&quot;: [<br>            {<br>              &quot;discountFactor&quot;: 1.0,<br>              &quot;endDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;ratePercent&quot;: 0.033463900578256656,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;0D&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 0.9999981666700277,<br>              &quot;endDate&quot;: &quot;2021-05-21&quot;,<br>              &quot;ratePercent&quot;: 0.033463900578256656,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;2D&quot;<br>            },<br>          ],<br>          &quot;isDiscountCurve&quot;: false<br>        }<br>      }<br>    }<br>  ]<br>}</pre><h4>Plot the data</h4><p>I can then use the curve points to generate my curve plot</p><pre>plot_zc_curves(response.data.raw[&#39;data&#39;][0], [&#39;3M&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9JLniq-C7f6Yfdae_wLpjQ.png" /></figure><p>Getting our Curve points into a Dataframe</p><pre>pd.DataFrame(response.data.raw[&#39;data&#39;][0][&quot;curves&quot;][&quot;3M&quot;][&quot;curvePoints&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*YU26OBEhSxZPQdPIwlAHmw.png" /></figure><p>Note the final column, which shows the <strong>Instrument</strong> that was used for the bootstrapping when generating the individual curve points</p><h4>Requesting Curve using Parameters</h4><p>As an alternative to using the Curve ID, I can also request a curve using Curve Parameters and Definition values.<br> Some of the key Parameters here are:</p><ul><li>Valuation Date</li><li>InterpolationMode e.g. CubicSpline, CubicDiscount, Linear etc</li><li>Day Count Basis e.g.</li><li>Actual, AFD, ISDA, 360, 365…</li><li>30_360, 30_360_US, 30_360_German…</li><li>30_365, 30_365_US, 30_365_German…</li></ul><p>One thing to be aware of here is that if we had more than one EUR curve, I would need to specify sufficient <strong>Definition</strong> parameters to uniquely identify the curve I want.<br> So, for example if we had two ‘EURIBOR’ based curves, I would need to specify the full <strong>name</strong> as well (or other unique definition parameter) — but as we currently only have one, I can just specify the <strong>indexName</strong> as I have done below.</p><pre>request_body={<br>    &quot;universe&quot;: [<br>    {<br>        &quot;<strong>curveParameters</strong>&quot;: {<br>            &quot;valuationDate&quot;:&quot;2020-06-30&quot;,<br>            &quot;interpolationMode&quot;: &quot;CubicSpline&quot;,<br>            &quot;priceSide&quot;: &quot;Mid&quot;,<br>            &quot;interestCalculationMethod&quot;: &quot;Dcb_Actual_Actual&quot;,<br>            &quot;extrapolationMode&quot;: &quot;Linear&quot;<br>        },<br>        <br>        &quot;<strong>curveDefinition</strong>&quot;: {<br>            &quot;currency&quot;: &quot;EUR&quot;,<br>            &quot;<strong>indexName</strong>&quot;:&quot;<strong>EURIBOR</strong>&quot;,<br>            &quot;discountingTenor&quot;: &quot;OIS&quot;,<br>            &quot;indexTenors&quot;:[&quot;6M&quot;]<br>        }<br>    }],<br>    <br>    &quot;outputs&quot;:[&quot;Constituents&quot;]<br>}<br><br>response = zcCurve_endpoint.send_request(<br>    method = rdp.Endpoint.RequestMethod.POST,<br>    body_parameters = request_body<br>)<br>print(json.dumps(response.data.raw, indent=2))</pre><p>Generates a response like:</p><pre>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;<strong>curveParameters</strong>&quot;: {<br>        &quot;extrapolationMode&quot;: &quot;Linear&quot;,<br>        &quot;interpolationMode&quot;: &quot;CubicSpline&quot;,<br>        &quot;interestCalculationMethod&quot;: &quot;Dcb_Actual_Actual&quot;,<br>        &quot;priceSide&quot;: &quot;Mid&quot;,<br>        &quot;calendarAdjustment&quot;: &quot;Calendar&quot;,<br>        &quot;calendars&quot;: [<br>          &quot;EMU_FI&quot;<br>        ],<br>        &quot;compoundingType&quot;: &quot;Compounded&quot;,<br>        &quot;useMultiDimensionalSolver&quot;: true,<br>        &quot;useConvexityAdjustment&quot;: true,<br>        &quot;useSteps&quot;: false,<br>        &quot;convexityAdjustment&quot;: {<br>          &quot;meanReversionPercent&quot;: -1.3584,<br>          &quot;volatilityPercent&quot;: 0.474<br>        },<br>        &quot;valuationDate&quot;: &quot;2020-06-30&quot;,<br>        &quot;ignoreExistingDefinition&quot;: false<br>      },<br>      &quot;<strong>curveDefinition</strong>&quot;: {<br>        &quot;<strong>availableTenors</strong>&quot;: [<br>          &quot;OIS&quot;,<br>          &quot;1M&quot;,<br>          &quot;3M&quot;,<br>          &quot;6M&quot;,<br>          &quot;1Y&quot;<br>        ],<br>        &quot;currency&quot;: &quot;EUR&quot;,<br>        &quot;mainConstituentAssetClass&quot;: &quot;Swap&quot;,<br>        &quot;riskType&quot;: &quot;InterestRate&quot;,<br>        &quot;indexName&quot;: &quot;EURIBOR&quot;,<br>        &quot;source&quot;: &quot;Refinitiv&quot;,<br>        &quot;name&quot;: &quot;EUR EURIBOR Swap ZC Curve&quot;,<br>        &quot;id&quot;: &quot;9d619112-9ab3-45c9-b83c-eb04cbec382e&quot;,<br>        &quot;discountingTenor&quot;: &quot;OIS&quot;,<br>        &quot;indexTenors&quot;: [<br>          &quot;OIS&quot;,<br>          &quot;6M&quot;<br>        ]<br>      },<br>      &quot;<strong>curves</strong>&quot;: {<br>        &quot;<strong>OIS</strong>&quot;: {<br>          &quot;<strong>curvePoints</strong>&quot;: [<br>            {<br>              &quot;discountFactor&quot;: 1.0,<br>              &quot;endDate&quot;: &quot;2020-06-30&quot;,<br>              &quot;ratePercent&quot;: -0.5222187504691722,<br>              &quot;startDate&quot;: &quot;2020-06-30&quot;,<br>              &quot;tenor&quot;: &quot;0D&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 1.0000143057602073,<br>              &quot;endDate&quot;: &quot;2020-07-01&quot;,<br>              &quot;ratePercent&quot;: -0.5222187504691722,<br>              &quot;startDate&quot;: &quot;2020-06-30&quot;,<br>              &quot;tenor&quot;: &quot;ON&quot;,<br>              &quot;instruments&quot;: [<br>                {<br>                  &quot;instrumentCode&quot;: &quot;EUROND=&quot;<br>                }<br>              ]<br>            },<br>          &quot;isDiscountCurve&quot;: true<br>.....<br><strong><em>Truncated</em></strong><br>.....        },<br>        &quot;<strong>6M</strong>&quot;: {<br>          &quot;<strong>curvePoints</strong>&quot;: [<br>            {<br>              &quot;discountFactor&quot;: 1.0,<br>              &quot;endDate&quot;: &quot;2020-06-30&quot;,<br>              &quot;ratePercent&quot;: -0.5222187504691722,<br>              &quot;startDate&quot;: &quot;2020-06-30&quot;,<br>              &quot;tenor&quot;: &quot;0D&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 1.0000143057602073,<br>              &quot;endDate&quot;: &quot;2020-07-01&quot;,<br>              &quot;ratePercent&quot;: -0.5222187504691722,<br>              &quot;startDate&quot;: &quot;2020-06-30&quot;,<br>              &quot;tenor&quot;: &quot;ON&quot;,<br>              &quot;instruments&quot;: [<br>                {<br>                  &quot;instrumentCode&quot;: &quot;EUROND=&quot;<br>                }<br>              ]<br>            },<br>.....<br><strong><em>Truncated</em></strong><br>.....          ],<br>          &quot;isDiscountCurve&quot;: false<br>        }<br>      },<br>      &quot;<strong>constituents</strong>&quot;: {<br>        &quot;<strong>interestRateInstruments</strong>&quot;: {<br>          &quot;EUR&quot;: {<br>            &quot;deposits&quot;: [<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.58<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: -0.45<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUROND=&quot;,<br>                  &quot;template&quot;: &quot;EUR&quot;,<br>                  &quot;tenor&quot;: &quot;ON&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1M&quot;,<br>                  &quot;3M&quot;,<br>                  &quot;6M&quot;,<br>                  &quot;1Y&quot;,<br>                  &quot;OIS&quot;<br>                ]<br>              },<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.55<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: -0.4<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EURTND=&quot;,<br>                  &quot;template&quot;: &quot;EUR&quot;,<br>                  &quot;tenor&quot;: &quot;TN&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1M&quot;,<br>                  &quot;3M&quot;,<br>                  &quot;6M&quot;,<br>                  &quot;1Y&quot;,<br>                  &quot;OIS&quot;<br>                ]<br>              },<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.225<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: -0.225<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EURIBOR1YD=&quot;,<br>                  &quot;template&quot;: &quot;EUR&quot;,<br>                  &quot;tenor&quot;: &quot;1Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1Y&quot;<br>                ]<br>              }<br>            ],<br>            &quot;<strong>fras</strong>&quot;: [<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.52<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: -0.5<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR0X1F=SMKR&quot;,<br>                  &quot;template&quot;: &quot;EURFRA&quot;,<br>                  &quot;tenor&quot;: &quot;0X1&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1M&quot;<br>                ]<br>              },<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.432<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: -0.412<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR0X3F=SMKR&quot;,<br>                  &quot;template&quot;: &quot;EURFRA&quot;,<br>                  &quot;tenor&quot;: &quot;0X3&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;3M&quot;<br>                ]<br>              },<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>            ],<br>            &quot;<strong>futures</strong>&quot;: [<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: 100.455<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: 100.46<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;FEIcm1&quot;,<br>                  &quot;template&quot;: &quot;FEI&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;3M&quot;<br>                ]<br>              },<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: 100.46<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: 100.465<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;FEIcm2&quot;,<br>                  &quot;template&quot;: &quot;FEI&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;3M&quot;<br>                ]<br>              },<br>.....<br><strong><em>Truncated</em></strong><br>.....            ],<br>            &quot;<strong>interestRateSwaps</strong>&quot;: [<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.481<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: -0.473<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EURAB3E2Y=TWEB&quot;,<br>                  &quot;template&quot;: &quot;EUR_AB3E&quot;,<br>                  &quot;tenor&quot;: &quot;2Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;3M&quot;<br>                ]<br>              },<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.476<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: -0.468<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EURAB3E3Y=TWEB&quot;,<br>                  &quot;template&quot;: &quot;EUR_AB3E&quot;,<br>                  &quot;tenor&quot;: &quot;3Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;3M&quot;<br>                ]<br>              },<br>.....<br><strong><em>Truncated</em></strong><br>.....            ],<br>            &quot;<strong>overnightIndexSwaps</strong>&quot;: [<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.511<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: -0.411<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUREONSW=ICAP&quot;,<br>                  &quot;template&quot;: &quot;OIS_EONIA&quot;,<br>                  &quot;tenor&quot;: &quot;SW&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;OIS&quot;<br>                ]<br>              },<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.511<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: -0.411<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUREON2W=ICAP&quot;,<br>                  &quot;template&quot;: &quot;OIS_EONIA&quot;,<br>                  &quot;tenor&quot;: &quot;2W&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;OIS&quot;<br>                ]<br>              },<br>.....<br><strong><em>Truncated</em></strong><br>.....            ],<br>            &quot;<strong>tenorBasisSwaps</strong>&quot;: [<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: 10.3<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: 10.3<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR6E12E2Y=ICAP&quot;,<br>                  &quot;template&quot;: &quot;LBOTH CROSS:EUR CLDR:EMU SETTLE:2WD LRECEIVED LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:1 PDELAY:0 LPAID LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:2 PDELAY:0&quot;,<br>                  &quot;tenor&quot;: &quot;2Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1Y&quot;<br>                ]<br>              },<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: 9.5<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: 9.5<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR6E12E3Y=ICAP&quot;,<br>                  &quot;template&quot;: &quot;LBOTH CROSS:EUR CLDR:EMU SETTLE:2WD LRECEIVED LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:1 PDELAY:0 LPAID LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:2 PDELAY:0&quot;,<br>                  &quot;tenor&quot;: &quot;3Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1Y&quot;<br>                ]<br>              },<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>                &quot;basis&quot;: [<br>                  &quot;1M&quot;<br>                ]<br>              }<br>            ]<br>          }<br>        }<br>      }<br>    }<br>  ]<br>}</pre><p>As you can see from the above response, it contains the following:</p><ol><li>The full set of Curve Parameters and Definition used to produce the curve</li><li>Curve point data for each available Tenor</li><li>List of Constituents</li></ol><h4>Plot the data</h4><pre>plot_zc_curves(response.data.raw[&#39;data&#39;][0], [&#39;6M&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFlGrt7VSUrIVYCBO_I6Dg.png" /></figure><p>If a particular Currency e.g. SEK, has only one curve available, the <strong>indexName</strong> attribute can be omitted.<br> Likewise, there are several other parameters where you can override the default to control the results.</p><h4>Specifying the curve output Tenors</h4><p>Generating a forward curve built with the market date of Jan 30th, 2021</p><p>As well as the Index Tenor, we provide the Start Tenor and the Tenors we wish to generate the Forward Curve for and use the <strong>Forward Curves Endpoint</strong> we defined towards the start of the article.</p><pre>request_body={<br>    &quot;universe&quot;:[<br>        {<br>            &quot;curveDefinition&quot;: {<br>                &quot;currency&quot;: &quot;JPY&quot;,<br>                &quot;indexName&quot;: &quot;LIBOR&quot;,<br>               &quot;discountingTenor&quot;: &quot;1M&quot;<br>              },<br>            <br>            &quot;curveParameters&quot;:{<br>            &quot;valuationDate&quot;:&quot;2021-01-30&quot;<br>            },<br><br>            &quot;forwardCurveDefinitions&quot;: [<br>                  {<br>                      &quot;indexTenor&quot;: &quot;1M&quot;,<br>                      &quot;forwardStartTenor&quot;:&quot;2D&quot;,<br>                      &quot;forwardCurveTenors&quot;: [<br>                          &quot;0M&quot;,&quot;1M&quot;,&quot;2M&quot;,&quot;3M&quot;,&quot;4M&quot;,&quot;5M&quot;,&quot;6M&quot;,&quot;7M&quot;,&quot;8M&quot;,&quot;9M&quot;,&quot;10M&quot;,&quot;11M&quot;,&quot;12M&quot;,&quot;13M&quot;,&quot;14M&quot;,&quot;15M&quot;,<br>                          &quot;16M&quot;,&quot;17M&quot;,&quot;18M&quot;,&quot;19M&quot;,&quot;20M&quot;,&quot;21M&quot;,&quot;22M&quot;,&quot;23M&quot;,&quot;24M&quot;,&quot;25M&quot;,&quot;26M&quot;,&quot;27M&quot;,&quot;28M&quot;,&quot;29M&quot;,&quot;30M&quot;,<br>                          &quot;31M&quot;,&quot;32M&quot;,&quot;33M&quot;,&quot;34M&quot;,&quot;35M&quot;,&quot;36M&quot;,&quot;37M&quot;,&quot;38M&quot;,&quot;39M&quot;,&quot;40M&quot;,&quot;41M&quot;,&quot;42M&quot;,&quot;43M&quot;,&quot;44M&quot;,&quot;45M&quot;,<br>                          &quot;46M&quot;,&quot;47M&quot;,&quot;48M&quot;,&quot;49M&quot;,&quot;50M&quot;,&quot;51M&quot;,&quot;52M&quot;,&quot;53M&quot;,&quot;54M&quot;,&quot;55M&quot;,&quot;56M&quot;,&quot;57M&quot;,&quot;58M&quot;,&quot;59M&quot;,&quot;60M&quot;,&quot;61M&quot;]<br>                  }<br>              ]<br>        }<br>    ]<br>}<br><br>response = forward_zcCurve_endpoint.send_request(<br>    method = rdp.Endpoint.RequestMethod.POST,<br>    body_parameters = request_body)<br><br><br>print(json.dumps(response.data.raw, indent=2))</pre><p>Provides a response as below:</p><pre>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;<strong>curveParameters</strong>&quot;: {<br>        &quot;interestCalculationMethod&quot;: &quot;Dcb_Actual_Actual&quot;,<br>        &quot;priceSide&quot;: &quot;Mid&quot;,<br>        &quot;calendarAdjustment&quot;: &quot;Calendar&quot;,<br>        &quot;calendars&quot;: [<br>          &quot;JAP_FI&quot;<br>        ],<br>        &quot;compoundingType&quot;: &quot;Compounded&quot;,<br>        &quot;useConvexityAdjustment&quot;: true,<br>        &quot;useSteps&quot;: false,<br>        &quot;valuationDate&quot;: &quot;2021-01-30&quot;,<br>        &quot;ignoreExistingDefinition&quot;: false<br>      },<br>      &quot;<strong>curveDefinition</strong>&quot;: {<br>        &quot;availableTenors&quot;: [<br>          &quot;6M&quot;,<br>          &quot;OIS&quot;,<br>          &quot;3M&quot;,<br>          &quot;1M&quot;<br>        ],<br>        &quot;currency&quot;: &quot;JPY&quot;,<br>        &quot;mainConstituentAssetClass&quot;: &quot;Swap&quot;,<br>        &quot;riskType&quot;: &quot;InterestRate&quot;,<br>        &quot;indexName&quot;: &quot;LIBOR&quot;,<br>        &quot;source&quot;: &quot;Refinitiv&quot;,<br>        &quot;name&quot;: &quot;JPY LIBOR Swap ZC Curve&quot;,<br>        &quot;id&quot;: &quot;cbf84acf-5328-4efc-8d23-f476ac495d82&quot;,<br>        &quot;discountingTenor&quot;: &quot;1M&quot;<br>      },<br>      &quot;<strong>forwardCurves</strong>&quot;: [<br>        {<br>          &quot;curvePoints&quot;: [<br>            {<br>              &quot;discountFactor&quot;: 1.000002876383664,<br>              &quot;endDate&quot;: &quot;2021-02-03&quot;,<br>              &quot;ratePercent&quot;: -0.05262389411501145,<br>              &quot;startDate&quot;: &quot;2021-02-01&quot;,<br>              &quot;tenor&quot;: &quot;0M&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 1.0000474669650439,<br>              &quot;endDate&quot;: &quot;2021-03-03&quot;,<br>              &quot;ratePercent&quot;: -0.057733431373796495,<br>              &quot;startDate&quot;: &quot;2021-02-01&quot;,<br>              &quot;tenor&quot;: &quot;1M&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 1.000106523884317,<br>              &quot;endDate&quot;: &quot;2021-04-05&quot;,<br>              &quot;ratePercent&quot;: -0.06169389328620767,<br>              &quot;startDate&quot;: &quot;2021-02-01&quot;,<br>              &quot;tenor&quot;: &quot;2M&quot;<br>            },<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>          ],<br>          &quot;forwardCurveTag&quot;: &quot;2DForward&quot;,<br>          &quot;forwardStart&quot;: &quot;2D&quot;,<br>          &quot;indexTenor&quot;: &quot;1M&quot;<br>        }<br>      ]<br>    }<br>  ]<br>}</pre><p>Get our Curve points into a Dataframe</p><pre>pd.DataFrame(response.data.raw[&#39;data&#39;][0][&#39;forwardCurves&#39;][0][&#39;curvePoints&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*VdtM7t4bLkK04JbqGO-onw.png" /></figure><h4>Implied Foreign Currencies / Currency Adjusted ZC Curves</h4><p>Here we are using the <strong>referenceCurveDefinition</strong> parameter to calculate a JPY curve currency adjusted for the USD using LIBOR i.e. integrate currency basis swap, starting with the USD Libor as the reference curve.</p><pre>request_body={<br>    &quot;universe&quot;: [<br>        {<br>            &quot;<strong>curveDefinition</strong>&quot;: {<br>                &quot;currency&quot;:&quot;<strong>JPY</strong>&quot;,<br>                &quot;indexName&quot;:&quot;<strong>LIBOR</strong>&quot;,<br>                &quot;discountingTenor&quot;: &quot;6M&quot;,<br>                &quot;<strong>referenceCurveDefinition</strong>&quot;: {<br>                    &quot;currency&quot;:&quot;<strong>USD</strong>&quot;,<br>                    &quot;indexName&quot;:&quot;<strong>LIBOR</strong>&quot;,<br>                    &quot;mainConstituentAssetClass&quot;:&quot;<strong>Swap</strong>&quot;,<br>                    &quot;discountingTenor&quot;: &quot;6M&quot;,<br>                }<br>            }            <br>        }]<br>}<br><br>response = zcCurve_endpoint.send_request(<br>    method = rdp.Endpoint.RequestMethod.POST,<br>    body_parameters = request_body<br>)</pre><pre>print(json.dumps(response.data.raw, indent=2))</pre><p>Generates the following response payload:</p><pre>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;<strong>curveParameters</strong>&quot;: {<br>        &quot;extrapolationMode&quot;: &quot;None&quot;,<br>        &quot;interpolationMode&quot;: &quot;CubicDiscount&quot;,<br>        &quot;interestCalculationMethod&quot;: &quot;Dcb_Actual_Actual&quot;,<br>        &quot;priceSide&quot;: &quot;Mid&quot;,<br>        &quot;calendarAdjustment&quot;: &quot;Calendar&quot;,<br>        &quot;calendars&quot;: [<br>          &quot;JAP_FI&quot;<br>        ],<br>        &quot;compoundingType&quot;: &quot;Compounded&quot;,<br>        &quot;useMultiDimensionalSolver&quot;: true,<br>        &quot;useConvexityAdjustment&quot;: true,<br>        &quot;useSteps&quot;: false,<br>        &quot;convexityAdjustment&quot;: {<br>          &quot;meanReversionPercent&quot;: -6.9606,<br>          &quot;volatilityPercent&quot;: 0.142<br>        },<br>        &quot;valuationDate&quot;: &quot;2021-05-19&quot;,<br>        &quot;ignoreExistingDefinition&quot;: false,<br>        &quot;referenceCurveParameters&quot;: {<br>          &quot;priceSide&quot;: &quot;Mid&quot;,<br>          &quot;calendarAdjustment&quot;: &quot;Calendar&quot;,<br>          &quot;compoundingType&quot;: &quot;Compounded&quot;,<br>          &quot;useMultiDimensionalSolver&quot;: true,<br>          &quot;useConvexityAdjustment&quot;: true,<br>          &quot;useSteps&quot;: false,<br>          &quot;convexityAdjustment&quot;: {<br>            &quot;meanReversionPercent&quot;: 1.295,<br>            &quot;volatilityPercent&quot;: 0.795<br>          }<br>        }<br>      },<br>      &quot;<strong>curveDefinition</strong>&quot;: {<br>        &quot;availableTenors&quot;: [<br>          &quot;OIS&quot;,<br>          &quot;1M&quot;,<br>          &quot;3M&quot;,<br>          &quot;6M&quot;<br>        ],<br>        &quot;currency&quot;: &quot;JPY&quot;,<br>        &quot;mainConstituentAssetClass&quot;: &quot;Swap&quot;,<br>        &quot;riskType&quot;: &quot;InterestRate&quot;,<br>        &quot;indexName&quot;: &quot;LIBOR&quot;,<br>        &quot;source&quot;: &quot;Refinitiv&quot;,<br>        &quot;name&quot;: &quot;JPY LIBOR Swap ZC Curve&quot;,<br>        &quot;id&quot;: &quot;cbf84acf-5328-4efc-8d23-f476ac495d82&quot;,<br>        &quot;discountingTenor&quot;: &quot;6M&quot;,<br>        &quot;indexTenors&quot;: [<br>          &quot;6M&quot;<br>        ],<br>        &quot;<strong>referenceCurveDefinition</strong>&quot;: {<br>          &quot;availableTenors&quot;: [<br>            &quot;OIS&quot;,<br>            &quot;1M&quot;,<br>            &quot;3M&quot;,<br>            &quot;6M&quot;<br>          ],<br>          &quot;currency&quot;: &quot;USD&quot;,<br>          &quot;mainConstituentAssetClass&quot;: &quot;Swap&quot;,<br>          &quot;riskType&quot;: &quot;InterestRate&quot;,<br>          &quot;indexName&quot;: &quot;LIBOR&quot;,<br>          &quot;source&quot;: &quot;Refinitiv&quot;,<br>          &quot;name&quot;: &quot;USD LIBOR Swap ZC Curve&quot;,<br>          &quot;id&quot;: &quot;1ef0692f-1cde-4b71-bad7-e39198633e0e&quot;,<br>          &quot;discountingTenor&quot;: &quot;6M&quot;<br>        }<br>      },<br>      &quot;<strong>curves</strong>&quot;: {<br>        &quot;<strong>6M</strong>&quot;: {<br>          &quot;<strong>curvePoints</strong>&quot;: [<br>            {<br>              &quot;discountFactor&quot;: 1.0,<br>              &quot;endDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;ratePercent&quot;: -0.037043027411154394,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;0D&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 1.0000050753402816,<br>              &quot;endDate&quot;: &quot;2021-05-24&quot;,<br>              &quot;ratePercent&quot;: -0.037043027411154394,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;5D&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 1.0000224357858043,<br>              &quot;endDate&quot;: &quot;2021-05-28&quot;,<br>              &quot;ratePercent&quot;: -0.09094717303220756,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;1W&quot;<br>            },<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>          ],<br>          &quot;isDiscountCurve&quot;: true<br>        }<br>      }<br>    }<br>  ]<br>}</pre><pre>pd.DataFrame(response.data.raw[&#39;data&#39;][0][&#39;curves&#39;][&#39;<strong>6M</strong>&#39;][&#39;curvePoints&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*VSmFVLnudCoaWSlERqfsgA.png" /></figure><h4>Alternative Discounting Tenor</h4><p>Here we are requesting the GBP 6M LIBOR Curve by it’s ID, collateralized with the USD 6M LIBOR curve</p><pre>request_body={<br>    &quot;universe&quot;: [<br>        {<br>            &quot;<strong>curveDefinition</strong>&quot;: { #GBP 6M LIBOR.<br>            &quot;id&quot;: &quot;<strong>69348bb7-d0b3-49b3-b2b2-782ab4ad29f8</strong>&quot;, <br>                &quot;discountingTenor&quot;:&quot;6M&quot;,<br>                &quot;<strong>referenceCurveDefinition</strong>&quot;: { #USD 6M LIBOR.<br>                    &quot;id&quot;: &quot;<strong>1ef0692f-1cde-4b71-bad7-e39198633e0e</strong>&quot;, <br>                    &quot;discountingTenor&quot;:&quot;6M&quot;<br>                }<br>            }<br>        }],<br>    &quot;outputs&quot;: [&quot;DetailedCurvePoint&quot;]<br>}<br><br>response = zcCurve_endpoint.send_request(<br>    method = rdp.Endpoint.RequestMethod.POST,<br>    body_parameters = request_body<br>)<br><br>print(json.dumps(response.data.raw, indent=2))<br>curves = response.data.raw[&#39;data&#39;][0][&quot;curves&quot;][&quot;6M&quot;][&quot;curvePoints&quot;]</pre><p>The resulting response payload is:</p><pre>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;<strong>curveParameters</strong>&quot;: {<br>        &quot;extrapolationMode&quot;: &quot;None&quot;,<br>        &quot;interpolationMode&quot;: &quot;CubicDiscount&quot;,<br>        &quot;interestCalculationMethod&quot;: &quot;Dcb_Actual_Actual&quot;,<br>        &quot;priceSide&quot;: &quot;Mid&quot;,<br>        &quot;calendarAdjustment&quot;: &quot;Calendar&quot;,<br>        &quot;calendars&quot;: [<br>          &quot;UKG_FI&quot;<br>        ],<br>        &quot;compoundingType&quot;: &quot;Compounded&quot;,<br>        &quot;useMultiDimensionalSolver&quot;: true,<br>        &quot;useConvexityAdjustment&quot;: true,<br>        &quot;useSteps&quot;: false,<br>        &quot;convexityAdjustment&quot;: {<br>          &quot;meanReversionPercent&quot;: -0.7192,<br>          &quot;volatilityPercent&quot;: 0.656<br>        },<br>        &quot;valuationDate&quot;: &quot;2021-05-19&quot;,<br>        &quot;ignoreExistingDefinition&quot;: false,<br>        &quot;referenceCurveParameters&quot;: {<br>          &quot;priceSide&quot;: &quot;Mid&quot;,<br>          &quot;calendarAdjustment&quot;: &quot;Calendar&quot;,<br>          &quot;compoundingType&quot;: &quot;Compounded&quot;,<br>          &quot;useMultiDimensionalSolver&quot;: true,<br>          &quot;useConvexityAdjustment&quot;: true,<br>          &quot;useSteps&quot;: false,<br>          &quot;convexityAdjustment&quot;: {<br>            &quot;meanReversionPercent&quot;: 1.295,<br>            &quot;volatilityPercent&quot;: 0.795<br>          }<br>        }<br>      },<br>      &quot;<strong>curveDefinition</strong>&quot;: {<br>        &quot;availableTenors&quot;: [<br>          &quot;OIS&quot;,<br>          &quot;1M&quot;,<br>          &quot;3M&quot;,<br>          &quot;6M&quot;<br>        ],<br>        &quot;<strong>currency</strong>&quot;: &quot;<strong>GBP</strong>&quot;,<br>        &quot;mainConstituentAssetClass&quot;: &quot;Swap&quot;,<br>        &quot;riskType&quot;: &quot;InterestRate&quot;,<br>        &quot;indexName&quot;: &quot;LIBOR&quot;,<br>        &quot;source&quot;: &quot;Refinitiv&quot;,<br>        &quot;name&quot;: &quot;GBP LIBOR Swap ZC Curve&quot;,<br>        &quot;id&quot;: &quot;69348bb7-d0b3-49b3-b2b2-782ab4ad29f8&quot;,<br>        &quot;discountingTenor&quot;: &quot;6M&quot;,<br>        &quot;indexTenors&quot;: [<br>          &quot;6M&quot;<br>        ],<br>        &quot;<strong>referenceCurveDefinition</strong>&quot;: {<br>          &quot;availableTenors&quot;: [<br>            &quot;OIS&quot;,<br>            &quot;1M&quot;,<br>            &quot;3M&quot;,<br>            &quot;6M&quot;<br>          ],<br>          &quot;<strong>currency</strong>&quot;: &quot;<strong>USD</strong>&quot;,<br>          &quot;mainConstituentAssetClass&quot;: &quot;Swap&quot;,<br>          &quot;riskType&quot;: &quot;InterestRate&quot;,<br>          &quot;indexName&quot;: &quot;LIBOR&quot;,<br>          &quot;source&quot;: &quot;Refinitiv&quot;,<br>          &quot;name&quot;: &quot;USD LIBOR Swap ZC Curve&quot;,<br>          &quot;id&quot;: &quot;1ef0692f-1cde-4b71-bad7-e39198633e0e&quot;,<br>          &quot;discountingTenor&quot;: &quot;6M&quot;<br>        }<br>      },<br>      &quot;<strong>curves</strong>&quot;: {<br>        &quot;<strong>6M</strong>&quot;: {<br>          &quot;<strong>curvePoints</strong>&quot;: [<br>            {<br>              &quot;discountFactor&quot;: 1.0,<br>              &quot;endDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;ratePercent&quot;: 0.09415395921494873,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;0D&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 0.9999871083485532,<br>              &quot;endDate&quot;: &quot;2021-05-24&quot;,<br>              &quot;ratePercent&quot;: 0.09415395921494873,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;5D&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 0.9999780472258979,<br>              &quot;endDate&quot;: &quot;2021-05-28&quot;,<br>              &quot;ratePercent&quot;: 0.08907131717752481,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;1W&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 0.9999427709698175,<br>              &quot;endDate&quot;: &quot;2021-06-21&quot;,<br>              &quot;ratePercent&quot;: 0.06332062619058831,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;1M&quot;<br>            },<br>.....<br><strong><em>Truncated</em></strong><br>.....          ],<br>          &quot;isDiscountCurve&quot;: true<br>        }<br>      }<br>    }<br>  ]<br>}</pre><h4>Taking collateral currency into account</h4><p>Similarly, we can use a <strong>Pivot </strong>Curve — so for example, instead of going directly from EUR to JPY, we are going via USD.</p><pre>request_body={<br>    &quot;universe&quot;: [<br>        {<br>            &quot;curveDefinition&quot;: {<br>                <strong>&quot;currency&quot;:&quot;JPY&quot;</strong>,<br>                &quot;indexName&quot;:&quot;<strong>LIBOR</strong>&quot;,<br>                &quot;discountingTenor&quot;: &quot;OIS&quot;,<br>                &quot;<strong>pivotCurveDefinition</strong>&quot;:{<br>                    &quot;currency&quot;:&quot;<strong>USD</strong>&quot;,<br>                    &quot;indexName&quot;:&quot;<strong>LIBOR</strong>&quot;,<br>                    &quot;mainConstituentAssetClass&quot;:&quot;<strong>Swap</strong>&quot;,<br>                    &quot;discountingTenor&quot;: &quot;OIS&quot;<br>                },<br>                &quot;<strong>referenceCurveDefinition</strong>&quot;: {<br>                    &quot;currency&quot;:&quot;<strong>EUR</strong>&quot;,<br>                    &quot;indexName&quot;:&quot;<strong>ESTR</strong>&quot;,<br>                    &quot;discountingTenor&quot;: &quot;OIS&quot;<br>                }<br>            }           <br>        }]<br>}<br><br>response = zcCurve_endpoint.send_request(<br>    method = rdp.Endpoint.RequestMethod.POST,<br>    body_parameters = request_body<br>)</pre><pre>print(json.dumps(response.data.raw, indent=2))</pre><p>Generates the following payload response:</p><pre>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;<strong>curveParameters</strong>&quot;: {<br>        &quot;extrapolationMode&quot;: &quot;None&quot;,<br>        &quot;interpolationMode&quot;: &quot;CubicDiscount&quot;,<br>        &quot;interestCalculationMethod&quot;: &quot;Dcb_Actual_Actual&quot;,<br>        &quot;priceSide&quot;: &quot;Mid&quot;,<br>        &quot;calendarAdjustment&quot;: &quot;Calendar&quot;,<br>        &quot;calendars&quot;: [<br>          &quot;JAP_FI&quot;<br>        ],<br>        &quot;compoundingType&quot;: &quot;Compounded&quot;,<br>        &quot;useMultiDimensionalSolver&quot;: true,<br>        &quot;useConvexityAdjustment&quot;: true,<br>        &quot;useSteps&quot;: false,<br>        &quot;convexityAdjustment&quot;: {<br>          &quot;meanReversionPercent&quot;: -6.9606,<br>          &quot;volatilityPercent&quot;: 0.142<br>        },<br>        &quot;valuationDate&quot;: &quot;2021-05-19&quot;,<br>        &quot;ignoreExistingDefinition&quot;: false,<br>        &quot;pivotCurveParameters&quot;: {<br>          &quot;priceSide&quot;: &quot;Mid&quot;,<br>          &quot;calendarAdjustment&quot;: &quot;Calendar&quot;,<br>          &quot;compoundingType&quot;: &quot;Compounded&quot;,<br>          &quot;useConvexityAdjustment&quot;: true,<br>          &quot;useSteps&quot;: false,<br>          &quot;convexityAdjustment&quot;: {<br>            &quot;meanReversionPercent&quot;: 1.295,<br>            &quot;volatilityPercent&quot;: 0.795<br>          }<br>        },<br>        &quot;<strong>referenceCurveParameters</strong>&quot;: {<br>          &quot;priceSide&quot;: &quot;Mid&quot;,<br>          &quot;calendarAdjustment&quot;: &quot;Calendar&quot;,<br>          &quot;compoundingType&quot;: &quot;Compounded&quot;,<br>          &quot;useMultiDimensionalSolver&quot;: true,<br>          &quot;useConvexityAdjustment&quot;: true,<br>          &quot;useSteps&quot;: false,<br>          &quot;convexityAdjustment&quot;: {<br>            &quot;meanReversionPercent&quot;: -0.0614,<br>            &quot;volatilityPercent&quot;: 0.564<br>          }<br>        }<br>      },<br>      &quot;<strong>curveDefinition</strong>&quot;: {<br>        &quot;availableTenors&quot;: [<br>          &quot;OIS&quot;,<br>          &quot;1M&quot;,<br>          &quot;3M&quot;,<br>          &quot;6M&quot;<br>        ],<br>        &quot;currency&quot;: &quot;JPY&quot;,<br>        &quot;mainConstituentAssetClass&quot;: &quot;Swap&quot;,<br>        &quot;riskType&quot;: &quot;InterestRate&quot;,<br>        &quot;indexName&quot;: &quot;LIBOR&quot;,<br>        &quot;source&quot;: &quot;Refinitiv&quot;,<br>        &quot;name&quot;: &quot;JPY LIBOR Swap ZC Curve&quot;,<br>        &quot;id&quot;: &quot;cbf84acf-5328-4efc-8d23-f476ac495d82&quot;,<br>        &quot;discountingTenor&quot;: &quot;OIS&quot;,<br>        &quot;indexTenors&quot;: [<br>          &quot;OIS&quot;<br>        ],<br>        &quot;<strong>pivotCurveDefinition</strong>&quot;: {<br>          &quot;availableTenors&quot;: [<br>            &quot;6M&quot;,<br>            &quot;3M&quot;,<br>            &quot;OIS&quot;,<br>            &quot;1M&quot;<br>          ],<br>          &quot;currency&quot;: &quot;USD&quot;,<br>          &quot;mainConstituentAssetClass&quot;: &quot;Swap&quot;,<br>          &quot;riskType&quot;: &quot;InterestRate&quot;,<br>          &quot;indexName&quot;: &quot;LIBOR&quot;,<br>          &quot;source&quot;: &quot;Refinitiv&quot;,<br>          &quot;name&quot;: &quot;USD LIBOR Swap ZC Curve&quot;,<br>          &quot;id&quot;: &quot;1ef0692f-1cde-4b71-bad7-e39198633e0e&quot;,<br>          &quot;discountingTenor&quot;: &quot;OIS&quot;<br>        },<br>        &quot;<strong>referenceCurveDefinition</strong>&quot;: {<br>          &quot;availableTenors&quot;: [<br>            &quot;OIS&quot;<br>          ],<br>          &quot;currency&quot;: &quot;EUR&quot;,<br>          &quot;mainConstituentAssetClass&quot;: &quot;Swap&quot;,<br>          &quot;riskType&quot;: &quot;InterestRate&quot;,<br>          &quot;indexName&quot;: &quot;ESTR&quot;,<br>          &quot;source&quot;: &quot;Refinitiv&quot;,<br>          &quot;name&quot;: &quot;EUR ESTR Swap ZC Curve&quot;,<br>          &quot;id&quot;: &quot;d734ef63-367c-4a4f-9cca-135796c9a3ed&quot;,<br>          &quot;discountingTenor&quot;: &quot;OIS&quot;<br>        }<br>      },<br>      &quot;<strong>curves</strong>&quot;: {<br>        &quot;<strong>OIS</strong>&quot;: {<br>          &quot;<strong>curvePoints</strong>&quot;: [<br>            {<br>              &quot;discountFactor&quot;: 1.0,<br>              &quot;endDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;ratePercent&quot;: -0.3184608466429206,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;0D&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 1.000043695339868,<br>              &quot;endDate&quot;: &quot;2021-05-24&quot;,<br>              &quot;ratePercent&quot;: -0.3184608466429206,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;5D&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 1.0000611763252403,<br>              &quot;endDate&quot;: &quot;2021-05-28&quot;,<br>              &quot;ratePercent&quot;: -0.24778889220563594,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;1W&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 1.0001605659935293,<br>              &quot;endDate&quot;: &quot;2021-06-21&quot;,<br>              &quot;ratePercent&quot;: -0.17742388113686225,<br>              &quot;startDate&quot;: &quot;2021-05-19&quot;,<br>              &quot;tenor&quot;: &quot;1M&quot;<br>            },<br>.....<br><strong><em>Truncated</em></strong><br>.....          ],<br>          &quot;isDiscountCurve&quot;: true<br>        }<br>      }<br>    }<br>  ]<br>}</pre><pre>pd.DataFrame(response.data.raw[&#39;data&#39;][0][&quot;curves&quot;][&quot;OIS&quot;][&quot;curvePoints&quot;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*Vrt4rVhbPYb8UeElMSf56Q.png" /></figure><h4>User defined ZC Curves</h4><p>So far I have requested <strong>Refinitiv defined Curves</strong> and how you can use parameters to customise the generated output. <br>However, one of the other great features of the Zero Coupons APIs is that you can define your own ZC Curves by <strong>specifying your own constituents</strong>.<br> You will have noted that when I requested a Refinitiv defined curve, the response included the constituents used to generate the curve. So, if required you could take one of our existing curves and modify the constituents and parameter to generate your own custom curve.</p><pre>user_defined_zc_request_body = {<br> &quot;universe&quot;: [<br>    {<br>      &quot;<strong>curveParameters</strong>&quot;: {<br>        &quot;<strong>ignoreExistingDefinition</strong>&quot;: <strong>True</strong>,<br>        &quot;valuationDate&quot;: &quot;2021-02-23&quot;<br>      },<br>      &quot;<strong>curveDefinition</strong>&quot;: {<br>        &quot;currency&quot;: &quot;EUR&quot;,<br>        &quot;discountingTenor&quot;: &quot;OIS&quot;<br>      },<br>      &quot;<strong>constituents</strong>&quot;: {<br>        &quot;<strong>interestRateInstruments</strong>&quot;: {<br>          &quot;EUR&quot;: {<br>            &quot;<strong>deposits</strong>&quot;: [<br>              {<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUROND=&quot;,<br>                  &quot;template&quot;: &quot;EUR&quot;,<br>                  &quot;tenor&quot;: &quot;ON&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;6M&quot;,<br>                  &quot;1Y&quot;,<br>                  &quot;3M&quot;,<br>                  &quot;OIS&quot;,<br>                  &quot;1M&quot;<br>                ]<br>              },<br>              {<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EURTND=&quot;,<br>                  &quot;template&quot;: &quot;EUR&quot;,<br>                  &quot;tenor&quot;: &quot;TN&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;6M&quot;,<br>                  &quot;1Y&quot;,<br>                  &quot;3M&quot;,<br>                  &quot;OIS&quot;,<br>                  &quot;1M&quot;<br>                ]<br>              },<br>              {<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EURIBOR1YD=&quot;,<br>                  &quot;template&quot;: &quot;EUR&quot;,<br>                  &quot;tenor&quot;: &quot;1Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1Y&quot;<br>                ]<br>              }<br>            ],<br>            &quot;<strong>fras</strong>&quot;: [<br>              {<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR4X10F=SMKR&quot;,<br>                  &quot;template&quot;: &quot;EURFRA&quot;,<br>                  &quot;tenor&quot;: &quot;4X10&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;6M&quot;<br>                ]<br>              },<br>              {<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR0X1F=SMKR&quot;,<br>                  &quot;template&quot;: &quot;EURFRA&quot;,<br>                  &quot;tenor&quot;: &quot;0X1&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1M&quot;<br>                ]<br>              },<br>              {<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR3X9F=SMKR&quot;,<br>                  &quot;template&quot;: &quot;EURFRA&quot;,<br>                  &quot;tenor&quot;: &quot;3X9&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;6M&quot;<br>                ]<br>              },<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>            ],<br>            &quot;<strong>futures</strong>&quot;: [<br>              {<br>                &quot;basis&quot;: [<br>                  &quot;3M&quot;<br>                ],<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;FEIcm8&quot;,<br>                  &quot;template&quot;: &quot;FEI&quot;<br>                }<br>              },<br>              {<br>                &quot;basis&quot;: [<br>                  &quot;3M&quot;<br>                ],<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;FEIcm1&quot;,<br>                  &quot;template&quot;: &quot;FEI&quot;<br>                }<br>              },<br>              {<br>                &quot;basis&quot;: [<br>                  &quot;3M&quot;<br>                ],<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;FEIcm7&quot;,<br>                  &quot;template&quot;: &quot;FEI&quot;<br>                }<br>              },<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>            ],<br>            &quot;<strong>interestRateSwaps</strong>&quot;: [<br>              {<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EURAB3E14Y=TWEB&quot;,<br>                  &quot;template&quot;: &quot;EUR_AB3E&quot;,<br>                  &quot;tenor&quot;: &quot;14Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;3M&quot;<br>                ]<br>              },<br>              {<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EURAB6E8Y=TWEB&quot;,<br>                  &quot;template&quot;: &quot;EUR_AB6E&quot;,<br>                  &quot;tenor&quot;: &quot;8Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;6M&quot;<br>                ]<br>              },<br>              {<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EURAB3E3Y=TWEB&quot;,<br>                  &quot;template&quot;: &quot;EUR_AB3E&quot;,<br>                  &quot;tenor&quot;: &quot;3Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;3M&quot;<br>                ]<br>              },<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>            ],<br>            &quot;<strong>overnightIndexSwaps</strong>&quot;: [<br>              {<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUREON11Y=ICAP&quot;,<br>                  &quot;template&quot;: &quot;OIS_EONIA&quot;,<br>                  &quot;tenor&quot;: &quot;11Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;OIS&quot;<br>                ]<br>              },<br>              {<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUREON9M=ICAP&quot;,<br>                  &quot;template&quot;: &quot;OIS_EONIA&quot;,<br>                  &quot;tenor&quot;: &quot;9M&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;OIS&quot;<br>                ]<br>              },<br><br>            ],<br>            &quot;<strong>tenorBasisSwaps</strong>&quot;: [<br>              {<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR6E12E5Y=ICAP&quot;,<br>                  &quot;template&quot;: &quot;LBOTH CROSS:EUR CLDR:EMU SETTLE:2WD LRECEIVED LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:1 PDELAY:0 LPAID LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:2 PDELAY:0&quot;,<br>                  &quot;tenor&quot;: &quot;5Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1Y&quot;<br>                ]<br>              },<br>              {<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR6E12E12Y=ICAP&quot;,<br>                  &quot;template&quot;: &quot;LBOTH CROSS:EUR CLDR:EMU SETTLE:2WD LRECEIVED LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:1 PDELAY:0 LPAID LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:2 PDELAY:0&quot;,<br>                  &quot;tenor&quot;: &quot;12Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1Y&quot;<br>                ]<br>              },<br>              {<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR1E3E2Y=ICAP&quot;,<br>                  &quot;template&quot;: &quot;LBOTH CROSS:EUR CLDR:EMU SETTLE:2WD LRECEIVED LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:4 PDELAY:0 LPAID LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:12 PDELAY:0&quot;,<br>                  &quot;tenor&quot;: &quot;2Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1M&quot;<br>                ]<br>              },<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>              {<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR1E3E3Y=ICAP&quot;,<br>                  &quot;template&quot;: &quot;LBOTH CROSS:EUR CLDR:EMU SETTLE:2WD LRECEIVED LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:4 PDELAY:0 LPAID LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:12 PDELAY:0&quot;,<br>                  &quot;tenor&quot;: &quot;3Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1M&quot;<br>                ]<br>              }<br>            ]<br>          }<br>        }<br>      }<br>    }<br>  ],<br>  &quot;outputs&quot;: [<br>    &quot;DetailedCurvePoint&quot;,<br>    &quot;Constituents&quot;<br>  ]<br>}<br><br><br>user_defined_zc_response = zcCurve_endpoint.send_request(<br>    method = rdp.Endpoint.RequestMethod.POST,<br>    body_parameters = user_defined_zc_request_body<br>)<br><br>print(json.dumps(user_defined_zc_response.data.raw, indent=2))</pre><p>Will generate the following custom curve response:</p><pre>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;<strong>curveParameters</strong>&quot;: {<br>        &quot;extrapolationMode&quot;: &quot;None&quot;,<br>        &quot;interpolationMode&quot;: &quot;CubicDiscount&quot;,<br>        &quot;interestCalculationMethod&quot;: &quot;Dcb_Actual_Actual&quot;,<br>        &quot;priceSide&quot;: &quot;Mid&quot;,<br>        &quot;calendarAdjustment&quot;: &quot;Calendar&quot;,<br>        &quot;calendars&quot;: [<br>          &quot;EMU_FI&quot;<br>        ],<br>        &quot;compoundingType&quot;: &quot;Compounded&quot;,<br>        &quot;useMultiDimensionalSolver&quot;: true,<br>        &quot;useConvexityAdjustment&quot;: true,<br>        &quot;useSteps&quot;: false,<br>        &quot;convexityAdjustment&quot;: {<br>          &quot;meanReversionPercent&quot;: -1.6963,<br>          &quot;volatilityPercent&quot;: 0.443<br>        },<br>        &quot;valuationDate&quot;: &quot;2021-02-23&quot;,<br>        &quot;ignoreExistingDefinition&quot;: true<br>      },<br>      &quot;<strong>curveDefinition</strong>&quot;: {<br>        &quot;availableTenors&quot;: [<br>          &quot;OIS&quot;,<br>          &quot;1M&quot;,<br>          &quot;3M&quot;,<br>          &quot;6M&quot;,<br>          &quot;1Y&quot;<br>        ],<br>        &quot;currency&quot;: &quot;EUR&quot;,<br>        &quot;discountingTenor&quot;: &quot;OIS&quot;,<br>        &quot;indexTenors&quot;: [<br>          &quot;OIS&quot;,<br>          &quot;1M&quot;,<br>          &quot;3M&quot;,<br>          &quot;6M&quot;,<br>          &quot;1Y&quot;<br>        ]<br>      },<br>      &quot;<strong>curves</strong>&quot;: {<br>        &quot;<strong>OIS</strong>&quot;: {<br>          &quot;<strong>curvePoints</strong>&quot;: [<br>            {<br>              &quot;discountFactor&quot;: 1.0,<br>              &quot;endDate&quot;: &quot;2021-02-23&quot;,<br>              &quot;ratePercent&quot;: -0.5576104873114995,<br>              &quot;startDate&quot;: &quot;2021-02-23&quot;,<br>              &quot;tenor&quot;: &quot;0D&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 1.0000152780111917,<br>              &quot;endDate&quot;: &quot;2021-02-24&quot;,<br>              &quot;ratePercent&quot;: -0.5576104873114995,<br>              &quot;startDate&quot;: &quot;2021-02-23&quot;,<br>              &quot;tenor&quot;: &quot;ON&quot;,<br>              &quot;instruments&quot;: [<br>                {<br>                  &quot;instrumentCode&quot;: &quot;EUROND=&quot;,<br>                  &quot;value&quot;: -0.55<br>                }<br>              ]<br>            },<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>          ],<br>          &quot;isDiscountCurve&quot;: true<br>        },<br>        &quot;<strong>1M</strong>&quot;: {<br>          &quot;curvePoints&quot;: [<br>            {<br>              &quot;discountFactor&quot;: 1.0,<br>              &quot;endDate&quot;: &quot;2021-02-23&quot;,<br>              &quot;ratePercent&quot;: -0.5576104873114995,<br>              &quot;startDate&quot;: &quot;2021-02-23&quot;,<br>              &quot;tenor&quot;: &quot;0D&quot;<br>            },<br>            {<br>              &quot;discountFactor&quot;: 1.0000152780111917,<br>              &quot;endDate&quot;: &quot;2021-02-24&quot;,<br>              &quot;ratePercent&quot;: -0.5576104873114995,<br>              &quot;startDate&quot;: &quot;2021-02-23&quot;,<br>              &quot;tenor&quot;: &quot;ON&quot;,<br>              &quot;instruments&quot;: [<br>                {<br>                  &quot;instrumentCode&quot;: &quot;EUROND=&quot;,<br>                  &quot;value&quot;: -0.55<br>                }<br>              ]<br>            },<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>          ],<br>          &quot;isDiscountCurve&quot;: false<br>        },<br>        &quot;<strong>3M</strong>&quot;: {<br>          &quot;curvePoints&quot;: [<br>            {<br>              &quot;discountFactor&quot;: 1.0,<br>              &quot;endDate&quot;: &quot;2021-02-23&quot;,<br>              &quot;ratePercent&quot;: -0.5576104873114995,<br>              &quot;startDate&quot;: &quot;2021-02-23&quot;,<br>              &quot;tenor&quot;: &quot;0D&quot;<br>            },<br>.....<br><strong><em>Truncated</em></strong><br>.....     ],<br>          &quot;isDiscountCurve&quot;: false<br>        }<br>      },<br>      &quot;<strong>constituents</strong>&quot;: {<br>        &quot;<strong>interestRateInstruments</strong>&quot;: {<br>          &quot;EUR&quot;: {<br>            &quot;deposits&quot;: [<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.6<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: -0.5<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUROND=&quot;,<br>                  &quot;template&quot;: &quot;EUR&quot;,<br>                  &quot;tenor&quot;: &quot;ON&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;6M&quot;,<br>                  &quot;1Y&quot;,<br>                  &quot;3M&quot;,<br>                  &quot;OIS&quot;,<br>                  &quot;1M&quot;<br>                ]<br>              },<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.6<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: -0.5<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EURTND=&quot;,<br>                  &quot;template&quot;: &quot;EUR&quot;,<br>                  &quot;tenor&quot;: &quot;TN&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;6M&quot;,<br>                  &quot;1Y&quot;,<br>                  &quot;3M&quot;,<br>                  &quot;OIS&quot;,<br>                  &quot;1M&quot;<br>                ]<br>              },<br>.....<br><strong><em>Truncated</em></strong><br>.....       ],<br>            &quot;<strong>fras</strong>&quot;: [<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.501<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: -0.481<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR4X10F=SMKR&quot;,<br>                  &quot;template&quot;: &quot;EURFRA&quot;,<br>                  &quot;tenor&quot;: &quot;4X10&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;6M&quot;<br>                ]<br>              },<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.56<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: -0.54<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR0X1F=SMKR&quot;,<br>                  &quot;template&quot;: &quot;EURFRA&quot;,<br>                  &quot;tenor&quot;: &quot;0X1&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1M&quot;<br>                ]<br>              },<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>            ],<br>            &quot;<strong>futures</strong>&quot;: [<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: 100.505<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: 100.51<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;FEIcm8&quot;,<br>                  &quot;template&quot;: &quot;FEI&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;3M&quot;<br>                ]<br>              },<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: 100.53<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: 100.535<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;FEIcm1&quot;,<br>                  &quot;template&quot;: &quot;FEI&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;3M&quot;<br>                ]<br>              },<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>            ],<br>            &quot;<strong>interestRateSwaps</strong>&quot;: [<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: 0.166<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: 0.172<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EURAB3E14Y=TWEB&quot;,<br>                  &quot;template&quot;: &quot;EUR_AB3E&quot;,<br>                  &quot;tenor&quot;: &quot;14Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;3M&quot;<br>                ]<br>              },<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.136<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: -0.131<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EURAB6E8Y=TWEB&quot;,<br>                  &quot;template&quot;: &quot;EUR_AB6E&quot;,<br>                  &quot;tenor&quot;: &quot;8Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;6M&quot;<br>                ]<br>              },<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>            ],<br>            &quot;<strong>overnightIndexSwaps</strong>&quot;: [<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.019<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: 0.031<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUREON11Y=ICAP&quot;,<br>                  &quot;template&quot;: &quot;OIS_EONIA&quot;,<br>                  &quot;tenor&quot;: &quot;11Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;OIS&quot;<br>                ]<br>              },<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: -0.509<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: -0.459<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUREON9M=ICAP&quot;,<br>                  &quot;template&quot;: &quot;OIS_EONIA&quot;,<br>                  &quot;tenor&quot;: &quot;9M&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;OIS&quot;<br>                ]<br>              },<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>            ],<br>            &quot;<strong>tenorBasisSwaps</strong>&quot;: [<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: 5.8<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: 5.8<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR6E12E5Y=ICAP&quot;,<br>                  &quot;template&quot;: &quot;LBOTH CROSS:EUR CLDR:EMU SETTLE:2WD LRECEIVED LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:1 PDELAY:0 LPAID LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:2 PDELAY:0&quot;,<br>                  &quot;tenor&quot;: &quot;5Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1Y&quot;<br>                ]<br>              },<br>.....<br><strong><em>Truncated</em></strong><br>.....<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR6E12E15Y=ICAP&quot;,<br>                  &quot;template&quot;: &quot;LBOTH CROSS:EUR CLDR:EMU SETTLE:2WD LRECEIVED LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:1 PDELAY:0 LPAID LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:2 PDELAY:0&quot;,<br>                  &quot;tenor&quot;: &quot;15Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1Y&quot;<br>                ]<br>              },<br>              {<br>                &quot;fields&quot;: {<br>                  &quot;bid&quot;: {<br>                    &quot;value&quot;: 2.2<br>                  },<br>                  &quot;ask&quot;: {<br>                    &quot;value&quot;: 2.2<br>                  }<br>                },<br>                &quot;instrumentDefinition&quot;: {<br>                  &quot;instrumentCode&quot;: &quot;EUR1E3E3Y=ICAP&quot;,<br>                  &quot;template&quot;: &quot;LBOTH CROSS:EUR CLDR:EMU SETTLE:2WD LRECEIVED LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:4 PDELAY:0 LPAID LTYPE:FLOAT CUR:EUR CFADJ:Y CCM:MMA0 DMC:M EMC:S FRQ:12 PDELAY:0&quot;,<br>                  &quot;tenor&quot;: &quot;3Y&quot;<br>                },<br>                &quot;basis&quot;: [<br>                  &quot;1M&quot;<br>                ]<br>              }<br>            ]<br>          }<br>        }<br>      }<br>    }<br>  ]<br>}</pre><pre>curves = user_defined_zc_response.data.raw[&#39;data&#39;][0][&quot;curves&quot;][&quot;3M&quot;][&quot;curvePoints&quot;]<br>pd.DataFrame(data=curves)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*ZC_-5AJbiVxxHMNATzMQeQ.png" /></figure><h4>Financial Contracts API</h4><p>Whilst the main focus of this article is Zero Coupon, I felt it would be remiss of me to not to briefly mention the related IPA <strong>Financial Contracts API</strong> — which may also of be some interest.</p><p>As with the ZC Curves API, we need to know the endpoint URL:</p><pre>financial_contract_endpoint = rdp.Endpoint(session, <br>            &#39;https://api.refinitiv.com/data/quantitative-analytics/v1/financial-contracts&#39;)</pre><h4>Interest Rate swap examples</h4><p>With the above ZC examples, I showed how you could request a particular curve and use the data in your own application.<br> However, by using the Financial Contracts API, you can describe an instrument and the apppropriate curves will be fetched behind the scenes.<br> So, for example, if I want to request a vanilla AUD Interest Rate Swap based on the BBSW index, I need to:</p><ul><li>specify the fields that I want calculated</li><li>define the instrument to be calculated in terms of the <a href="https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis/documentation#ipa-financial-contracts-getting-started">available documented parameters</a></li></ul><pre>request_body = {<br>    <br>    &quot;fields&quot; : [&quot;InstrumentTag&quot;,&quot;MarketValueInDealCcy&quot;,&quot;DirtyPricePercent&quot;,&quot;FixedRatePercent&quot;,\<br>                &quot;DiscountCurveName&quot;,&quot;ForwardCurveName&quot;,&quot;ErrorCode&quot;,&quot;ErrorMessage&quot;],<br>    <br>    &quot;universe&quot; : [<br>        {<br>            &quot;instrumentType&quot;:&quot;Swap&quot;,<br>            &quot;instrumentDefinition&quot;: {<br>                &quot;instrumentTag&quot;:&quot;IRS-EUR EURIBOR 6M - 5Y&quot;,<br>                &quot;startDate&quot;:&quot;2020-07-29&quot;,<br>                &quot;tenor&quot;:&quot;5Y&quot;,<br>                &quot;legs&quot;:[<br>                {<br>                    &quot;direction&quot;:&quot;Paid&quot;,<br>                    &quot;interestType&quot;:&quot;Fixed&quot;,<br>                    &quot;notionalCcy&quot;:&quot;EUR&quot;,<br>                    &quot;interestPaymentFrequency&quot;:&quot;Annual&quot;,<br>                    &quot;interestCalculationMethod&quot;:&quot;Dcb_Actual_365&quot;,<br>                },<br>                {<br>                    &quot;direction&quot;:&quot;Received&quot;,<br>                    &quot;interestType&quot;:&quot;Float&quot;,<br>                    &quot;interestPaymentFrequency&quot;:&quot;SemiAnnual&quot;,<br>                    &quot;interestCalculationMethod&quot;:&quot;Dcb_Actual_365&quot;,<br>                    &quot;notionalCcy&quot;:&quot;EUR&quot;,<br>                    &quot;indexName&quot;:&quot;EURIBOR&quot;,<br>                    &quot;indexTenor&quot;:&quot;6M&quot;,<br>                }]<br>            }<br>        }],<br>    <br>    &quot;pricingParameters&quot;: {<br>        &quot;valuationDate&quot;: &quot;2020-7-27T00:00:00Z&quot;,<br>    },<br>        <br>    &quot;outputs&quot; : [&quot;Data&quot;,&quot;Headers&quot;],<br><br>}<br><br>response = financial_contract_endpoint.send_request(<br>    method = rdp.Endpoint.RequestMethod.POST,<br>    body_parameters = request_body)<br><br>print(json.dumps(response.data.raw, indent=2))</pre><pre>{<br>  &quot;headers&quot;: [<br>    {<br>      &quot;type&quot;: &quot;String&quot;,<br>      &quot;name&quot;: &quot;InstrumentTag&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;Float&quot;,<br>      &quot;name&quot;: &quot;MarketValueInDealCcy&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;Float&quot;,<br>      &quot;name&quot;: &quot;DirtyPricePercent&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;Float&quot;,<br>      &quot;name&quot;: &quot;FixedRatePercent&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;String&quot;,<br>      &quot;name&quot;: &quot;DiscountCurveName&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;String&quot;,<br>      &quot;name&quot;: &quot;ForwardCurveName&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;String&quot;,<br>      &quot;name&quot;: &quot;ErrorCode&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;String&quot;,<br>      &quot;name&quot;: &quot;ErrorMessage&quot;<br>    }<br>  ],<br>  &quot;data&quot;: [<br>    [<br>      &quot;IRS-EUR EURIBOR 6M - 5Y&quot;,<br>      -18956.4458024112,<br>      -1.89564458024112,<br>      -0.374483171441853,<br>      &quot;EUR - Swap vs 6M Euribor&quot;,<br>      null,<br>      &quot;&quot;,<br>      &quot;&quot;<br>    ],<br>    [<br>      &quot;IRS-EUR EURIBOR 6M - 5Y&quot;,<br>      -18956.4458024112,<br>      -1.89564458024112,<br>      null,<br>      &quot;EUR - Swap vs 6M Euribor&quot;,<br>      &quot;EUR - Swap vs 6M Euribor&quot;,<br>      &quot;&quot;,<br>      &quot;&quot;<br>    ]<br>  ]<br>}</pre><pre>pd.DataFrame(data=response.data.raw[&#39;data&#39;], columns=[h[&#39;name&#39;] for h in response.data.raw[&#39;headers&#39;]])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TA8RS4_C383vEiJkaTmQKA.png" /></figure><p>As you will note from the 5th &amp; 6th columns, the response provided details of the underlying curves used to calculate the requested Interest Rate Swap.</p><h3>Closing</h3><p>I hope the above has provided a useful insight into the power of the Zero Coupon Curve APIs that form part of the broader Instrument Pricing Analytics APIs umbrella.</p><h3>References</h3><p><a href="https://developers.refinitiv.com/en/article-catalog/article/discover-our-refinitiv-data-platform-library-part-1">Discover our new upcoming Refinitiv Data Platform Library — Part 1</a> of my RDP Library Introduction article</p><p><a href="https://api.refinitiv.com/">API Playground</a> — Interactive Documentation for Refinitiv Data Platform APIs.</p><p><a href="https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis">Refinitiv Data Platform APIs</a> — our existing REST-based interface to the cloud Platform.</p><p><a href="https://community.developers.refinitiv.com/spaces/231/index.html"><strong>Q&amp;A Forum</strong> for the Refinitiv Data Platform APIs</a></p><p>The full <strong>Source Code </strong>(including the complete JSON Request and Response payloads) is available as a <a href="https://github.com/Refinitiv-API-Samples/Article.RDPLibrary.Python.ZeroCouponCurves"><strong>Jupyter Notebook file on GitHub</strong></a><strong>.</strong></p><p><em>Originally published at </em><a href="https://developers.refinitiv.com/article/instrument-pricing-analytics-volatility-surfaces-and-curves"><em>https://developers.refinitiv.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=379fd1b396bb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lseg-developer-community/instrument-pricing-analytics-zero-coupon-curves-379fd1b396bb">Instrument Pricing Analytics — Zero Coupon Curves</a> was originally published in <a href="https://medium.com/lseg-developer-community">LSEG Developer Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Risk-Free Rates and the LIBOR Transition — A Realised Rate Calculator]]></title>
            <link>https://medium.com/lseg-developer-community/risk-free-rates-and-the-libor-transition-a-realised-rate-calculator-5209044d04f4?source=rss-b172232f4cfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/5209044d04f4</guid>
            <category><![CDATA[libor]]></category>
            <category><![CDATA[risk-free-rate]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[libor-transition]]></category>
            <dc:creator><![CDATA[Umer Nalla]]></dc:creator>
            <pubDate>Mon, 05 Oct 2020 13:41:43 GMT</pubDate>
            <atom:updated>2021-05-10T09:24:53.730Z</atom:updated>
            <content:encoded><![CDATA[<h3>Risk-Free Rates and the LIBOR Transition — A Realised Rate Calculator</h3><p>As you will be aware, the FCA is phasing out the LIBOR rate for various reasons and it is expected to cease in the near future. Market participants are expected to transition away from LIBOR to adopt alternatives — Risk-Free Rates (RFR).</p><p>In the UK, for example. a reformed version of the Sterling Overnight Index (SONIA) is the recommended replacement as the preferred RFR for sterling Markets after the end of 2021. Other jurisdictions have alternative rates being proposed or developed — such as Secured Overnight Rate (SOFR) in the USA.</p><p>No doubt there are considerable resources and tools on the internet that can help in the migration plan. One such example is a dedicated IBOR Transition App in the <a href="https://www.refinitiv.com/en/products/refinitiv-workspace">Refinitiv Workspace</a> desktop application or the <a href="https://realisedrate.com/SONIA">NatWest Realised Rate Calculator</a> website.</p><p>From a developer’s perspective, the <a href="https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis">Refinitiv Data Platform APIs</a> can also help in the migration process.</p><p>In this article, I will explore one way in which the RDP APIs and the higher level RDP Library can be used by developers to assist in this migration effort.</p><p>Firstly, I will look at how you can use the <strong>Financial Contracts API</strong> offered by Refinitiv’s <a href="https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis">Instrument Pricing Analytics</a> to calculate Realised Risk-Free Rates. I will be focusing on SONIA — no doubt a similar technique could be applied to calculate other rates.</p><p>In a future article, I also hope to look at how you could plot Zero-Coupon Curves based on an RFR rather than LIBOR.</p><h3>Calculating Risk-Free Rates</h3><p>So, how can the Refinitiv Data Platform help you migrate to RFR?</p><p>The Data Platform offers a <strong>Financial Contracts API</strong> which we can use to create an Interest Rate Swap instrument. For example, I could define an IR Swap instrument to calculate the Accrued of its float leg — and use it to replicate the NatWest Reference rate specification I mentioned earlier.</p><p>To demonstrate this, I am going to implement a basic <strong>Realised Rate Calculator </strong>using the Financial Contracts API.</p><p>The Financial Contracts API can be accessed using our <a href="https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis">REST API interface</a> at <a href="https://api.refinitiv.com/data/quantitative-analytics/v1/financial-contracts">https://api.refinitiv.com/data/quantitative-analytics/v1/financial-contracts</a></p><p>However, to make things as easy as possible, I will be using the Python version of our <a href="https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-libraries">Refinitiv Data Platform Library</a> — which provides an ease of use wrapper around the REST APIs.</p><p>I have previously written some articles around the RDP Library so I won’t go into much detail on how to use the library itself. If you have not already done so, I recommend you <a href="https://developers.refinitiv.com/en/article-catalog/article/discover-our-refinitiv-data-platform-library-part-1">read the articles</a> for an overview.</p><h3>Financial Contracts API</h3><p>The Financial Contracts API is an incredibly flexible one — which you can explore in more detail on the <a href="https://apidocs.refinitiv.com/Apps/ApiDocs#/details/L2RhdGEvcXVhbnRpdGF0aXZlLWFuYWx5dGljcy92MQ==/L2ZpbmFuY2lhbC1jb250cmFjdHM=/POST/PLAYGROUND">API Playground</a> (you will need a Refinitiv account) or via the <a href="https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis/documentation">RDP API Documentation pages</a>.</p><p>In addition to Interest Rate Swaps, the Financial Contracts API supports FX Spots, FX Forwards, FX Swaps, Credit Default Swaps, Bonds, Equity options as well as several other types of financial contracts.</p><p>To use the <strong>Financial Contracts API</strong> via the RDP Library, I need to create a session and an Endpoint object referencing the Financial Contracts API:</p><pre><strong>import refinitiv.dataplatform as rdp</strong><br>session = rdp.DesktopSession(app_key)<br>session.open()<br> <br>endpoint = rdp.Endpoint(session,  <br>    &#39;<a href="https://api.refinitiv.com/data/quantitative-analytics/v1/financial-contracts&#39;"><strong>https://api.refinitiv.com/data/quantitative-analytics/v1/financial-contracts</strong>&#39;</a>)</pre><p>I can now use the Endpoint object to submit an IR Swap definition to the platform and receive the response data back from the Platform. So, I will define a Swap request to provide an Accrued Percentage value replicating the NatWest Reference Rate.</p><p>To submit my IR Swap Request I need to provide the following inputs:</p><ul><li><strong>Start date</strong> of the Interest Rate Swap matching the start date of the realised rate period</li><li>The <strong>Maturity date</strong> of the Interest Rate Swap matching the end date of the realised rate period</li><li><strong>Amount </strong>used to compute the interest paid over the realised rate period</li><li>The <strong>Currency </strong>of the amount</li><li><strong>Spread</strong> in Basis points that is added to the realised rate</li><li><strong>Day count basis</strong> used to compute each daily year fraction</li><li><strong>Name of the reference index</strong> used to compute the realised rate (e.g. SONIA, SOFR)</li><li><strong>Look back period</strong> i.e. number of days between the daily interest period and the reference index publication( where 0 means the interest period uses the fixing of the previous day)</li></ul><h4>Define my IR Swap</h4><p>Below is my <strong>create_swap </strong>function to generate the JSON for my Swap definition — a straightforward ‘<em>fixed for floating</em>’ swap — utilising the above inputs:</p><pre>def create_swap(start_date, end_date, amount, spread_bp, <br>    day_count, currency, index_name, look_back):</pre><pre> <strong>swap_definition </strong>= {<br>      &quot;instrumentType&quot;:&quot;<strong>Swap</strong>&quot;, <br>      &quot;instrumentDefinition&quot;: {<br>          &quot;instrumentTag&quot;:&quot;<strong>Compounding-Rate</strong>&quot;,<br>          &quot;startDate&quot;:start_date,<br>          &quot;tenor&quot;:&quot;1Y&quot;,<br>          &quot;legs&quot;:[<br>          {<br>              &quot;legTag&quot;: &quot;Fixed&quot;,<br>              &quot;interestType&quot;: &quot;<strong>Fixed</strong>&quot;,<br>              &quot;notionalCcy&quot;: currency,<br>              &quot;notionalAmount&quot;: amount,<br>              &quot;interestCalculationMethod&quot;: day_count,<br>              &quot;direction&quot;:&quot;Paid&quot;,<br>              &quot;interestType&quot;:&quot;Fixed&quot;,<br>              &quot;interestPaymentFrequency&quot;: &quot;Zero&quot;,<br>              &quot;fixedRatePercent&quot;:1.0,<br>          },<br>          {<br>              &quot;legTag&quot;: &quot;Float&quot;,<br>              &quot;direction&quot;:&quot;Received&quot;,<br>              &quot;interestType&quot;:&quot;<strong>Float</strong>&quot;,<br>              &quot;notionalCcy&quot;: currency,<br>              &quot;notionalAmount&quot;: amount,<br>              &quot;spreadBp&quot;: spread_bp,<br>              &quot;interestPaymentFrequency&quot;: &quot;Zero&quot;,<br>              &quot;interestCalculationMethod&quot;: day_count,<br>              &quot;indexTenor&quot;: &quot;ON&quot;,<br>              &quot;indexName&quot;: index_name,<br>              &quot;indexFixingLag&quot;: look_back,<br>              &quot;indexCompoundingMethod&quot;: &quot;Compounded&quot;,<br>          }]<br>      },<br>      <br>      &quot;pricingParameters&quot;: {<br>          &quot;valuationDate&quot;: end_date,<br>      },<br>   }<br>return swap_definition</pre><p>Note the two legs for my swap; the <strong>fixed </strong>leg, followed by the <strong>float</strong> — using the supplied parameters to generate a JSON payload — which I can then send as part of the request to the API endpoint.</p><h4>Submit my request to the API Endpoint</h4><p>I use the JSON returned by the above <strong>create_swap</strong> function as part of my fuller request payload:</p><pre><strong>request_body </strong>= {<br>    &quot;<strong>fields</strong>&quot; :           [&quot;InstrumentTag&quot;,&quot;LegTag&quot;,&quot;MarketValueInDealCcy&quot;,<br>    &quot;AccruedPercent&quot;, &quot;AccruedAmountInDealCcy&quot;,    &quot;ErrorCode&quot;,&quot;ErrorMessage&quot;],<br>    &quot;<strong>universe</strong>&quot; : <br>    [ <strong>create_swap</strong>(start_date, end_date, amount, spread_bp,<br>       day_count, currency, index_name, look_back)],<br>    &quot;outputs&quot; : [&quot;<strong>Data</strong>&quot;,&quot;<strong>Headers</strong>&quot;],<br>}<br> <br>swap = endpoint.<strong>send_request</strong>(<br>    method = rdp.Endpoint.RequestMethod.POST,<br>    body_parameters = <strong>request_body</strong>)</pre><p>In the above request, the input is the Swap Definition JSON and the expected output consists of a selection of data fields and headers. I am requesting the headers so I can display the response in a user-friendly dataframe — as well as the ability to access the response fields by name.</p><pre>headers_name = [h[&#39;name&#39;] for h in swap.data.raw[&#39;headers&#39;]]<br>df = pd.DataFrame(data=swap.data.raw[&#39;data&#39;], columns=headers_name)display(df)</pre><p>Which should generate something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*RD1cisc8QwlksvYJ.png" /></figure><p>From the list of fields I received, I am interested in the <strong>AccruedPercent </strong>for the Floating rate:</p><pre>return df[&#39;<strong>AccruedPercent</strong>&#39;][1]</pre><h3>Calculate the Year Fraction of the Realised Rate Period</h3><p>I now have an Accrued Percentage, however, to get our actual <strong>annualised</strong> Realised Rate value — I also need to work out the year fraction based on my start and end dates.</p><p>Rather than computing this myself, I can use another RDP API — the <strong>Quantitative Analytics Dates &amp; Calendar API</strong>. This offers various endpoints such as daily schedules, holidays as well as <strong>count-periods</strong> — to get the period of time between a start date and an end date using one or more calendars.</p><pre>cp_endpoint = rdp.Endpoint(session, &quot;<a href="https://api.refinitiv.com/data/quantitative-analytics-dates-and-calendars/beta1/count-periods"><strong>https://api.refinitiv.com/data/quantitative-analytics-dates-and-calendars/beta1/count-periods</strong></a>&quot;)<br> <br>    <strong>cp_request_body</strong>=[<br>        {<br>        &quot;tag&quot;: &quot;my request 1&quot;,<br>        &quot;startDate&quot;: start_date,<br>        &quot;endDate&quot;: end_date,<br>        &quot;DayCountBasis&quot;:day_count_basis,<br>        &quot;periodType&quot;: period_type,<br>        &quot;calendars&quot;: [calendars]<br>        }<br>    ]<br> <br>    period_of_time = cp_endpoint.<strong>send_request</strong>(<br>        method = rdp.Endpoint.RequestMethod.POST,<br>        body_parameters = <strong>cp_request_body</strong>)<br>        <br>    df = pd.json_normalize(period_of_time.data.raw)<br>    display(df)<br>    <br>    return period_of_time.data.raw[0][&#39;count&#39;]</pre><p>I will use the same day count basis as the Swap and GBP Calendar. The response gives me something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/0*js7eciRl-st-VFxq.png" /></figure><p>from which <strong>count</strong> is the value I am interested in.</p><p>Using the Accrued Percent and the above Period of Time value, I can now calculate the Realised Rate:</p><pre>return round<strong>(accrued_percent / period_of_time,4)</strong></pre><p>In the accompanying <a href="https://github.com/Refinitiv-API-Samples/Article.RDPLibrary.Python.RealisedRateCalculator">source code</a> I have created a simple UI to make it easier to calculate the Realised Rate with input values of my choice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/0*ZO-Khuu0UIs3kAbG.png" /></figure><p>Given the input values of 24/02/2020 to 24/03/2020 for £10,000 GBP (therefore SONIA) on a 365-day count basis, I get a realised rate of <strong>0.4669</strong> — which is the same as the value generated by NatWest Reference rate generator using the same input values.</p><h3>Summary</h3><p>Just to recap, I calculated our Annualised Risk-Free rate with the Refinitiv Data Platform using the:</p><ul><li>Financial Contract API to submit an IR Swap with user-defined parameters to obtain the Accrued of its float leg</li><li>Quantitative Analytics API to calculate the Year Fraction of the RFR Period</li></ul><p>This was just one example of how the Financial Contracts API can assist you as part of the LIBOR transition or other workflows. As I mentioned at the start, it also provides coverage for various other asset classes such as</p><ul><li>FX Spots, FX Forwards, FX Swaps</li><li>CDS, Bonds, Bonds Futures</li><li>Options, Term Deposits and so on..</li></ul><p>However, the Financial Contracts API is just one of the Instrument Pricing Analytics APIs which also offers Volatility Surfaces and Curves. I have written about Volatility Surfaces in<a href="https://medium.com/swlh/instrument-pricing-analytics-volatility-surfaces-and-curves-developer-community-8b70b01cd277"> a previous article</a>, so hopefully in a future article, I will focus on Curves — specifically Zero-Coupon Curves.</p><p>In closing, I am sure you agree that it did not take much effort at all to calculate my Annualised Realised RFR — by using the Refinitiv Data Platform and the Financial Contracts API.</p><h3>Additional Resources</h3><p><a href="https://github.com/Refinitiv-API-Samples/Article.RDPLibrary.Python.RealisedRateCalculator">Source Code on GitHub</a><br><a href="https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis">Refinitiv Data Platform APIs</a><br><a href="https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-libraries">Refinitiv Data Platform Library</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5209044d04f4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lseg-developer-community/risk-free-rates-and-the-libor-transition-a-realised-rate-calculator-5209044d04f4">Risk-Free Rates and the LIBOR Transition — A Realised Rate Calculator</a> was originally published in <a href="https://medium.com/lseg-developer-community">LSEG Developer Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Technical Analysis indicators to send Buy or Sell trading signals to a Chatroom]]></title>
            <link>https://medium.com/lseg-developer-community/create-technical-analysis-triggers-and-signals-using-the-eikon-data-api-1429eafaaf2c?source=rss-b172232f4cfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/1429eafaaf2c</guid>
            <category><![CDATA[stochastics]]></category>
            <category><![CDATA[eikon]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[technical-analysis]]></category>
            <category><![CDATA[market-data]]></category>
            <dc:creator><![CDATA[Umer Nalla]]></dc:creator>
            <pubDate>Wed, 22 Apr 2020 11:49:36 GMT</pubDate>
            <atom:updated>2021-05-10T09:25:07.750Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will look at how I can use Technical Analysis indicators to send Buy or Sell trading signals to a chatroom on an ongoing basis — as and when they are generated.</p><p>According to Investopedia<em> ‘Technical Analysis is a trading discipline employed to evaluate investments and identify trading opportunities by analyzing statistical trends gathered from trading activity, such as price movement and volume’</em>. It further states <em>‘technical analysts focus on patterns of price movements, trading signals … to evaluate a security’s strength or weakness’</em>.</p><p>According to the various articles etc that I read, three of the more commonly used TA indicators are</p><ul><li>Simple Moving Averages</li><li>Relative Strength Index</li><li>Stochastic Oscillator</li></ul><p>Investors and traders who use Technical Analysis as part of their trading strategy may refer to TA charts on a regular basis to help determine their investment choices.</p><p>In this workflow, I am going to experiment with how I can use these indicators to generate Buy or Sell trading signals. There are several articles on the internet which attempt the same thing — often focusing on a single indicator — and most of these run the analysis on historical data, present the historical results and stop there.</p><p>However, for this workflow I want to take this a step further by continuing to run the analysis on an ongoing basis at a configured interval — e.g. every minute, hour, day (I did look at using realtime tick data as well but it was pointed out that this does not make much sense from a technical analysis perspective — as the ticks do not occur at regular interval).</p><p>Furthermore, when a trading signal is generated I will use a chat BOT to post the signal details into a chat room notifying the users — saving the effort of frequently interrogating the charts.</p><p>I have access to the Refinitiv Eikon desktop application so I will be using its Data API which can access historical, reference and real-time streaming data. I will also use symbology conversion functions to convert from ISINs to RIC (Reuters Instrument Codes) for requesting the various data. In addition, I will use the <a href="http://developers.refinitiv.com/messenger-api">Refinitiv Messenger BOT API</a> to post a message to a Refinitiv (Eikon) Messenger Chatroom — no doubt this could easily be replaced with some other form of messaging such as WhatsApp, email, SMS etc.</p><p>Before we go any further I should mention that I am relatively new to the Eikon Data API and to Python itself — so you may come across some ‘not very Pythonic’ ways of doing things. If you find some instances which border on sacrilege (in the Python world) please let me know and I will try and amend the offending code (I am working on the lower_case_with_underscores naming convention - but as a long time Java/C++ developer, not there yet!).</p><h4>TA-Lib: Technical Analysis Library</h4><p>When I started on this, I was using various Python scripts/snippets I found online for calculating my indicators and then wondering just how accurate they may truly be. After spending (wasting?) some considerable time testing and fretting about the veracity of these snippets, a colleague mentioned that there already existed a Python wrapper — <a href="https://github.com/mrjbq7/ta-lib">ta-lib</a> — for the <em>well known</em> Technical Analysis Library — <a href="https://ta-lib.org/hdr_doc.html">TA-Lib</a>. Off course — this being Python there would have to be a library for it (remember — I am a Python noob)!</p><h4>Import our libraries</h4><p>I think I should mention the versions of some of the key libraries I have installed — just in case you have any issues:</p><ul><li>eikon — 1.1.3<strong>a0</strong></li><li>pandas — 1.0.0</li><li>numpy — 1.18.1</li><li>talib — 0.4.17</li><li>matplotlib — 3.1.3</li></ul><p>I have used an alpha version of the eikon library because I wanted to test it &amp; also because I wanted to eliminate the pandas.np deprecation warnings . <br>If you are an Eikon user and have the official v1.1.2 (at the time of writing) installed it should still work fine and you could just import warnings library and use warnings.filterwarnings(&quot;ignore&quot;) to suppress them.</p><p>If you decide to build the TA-Lib binaries (rather than download the prebuilt ones) pay attention to the instructions on moving the folder — otherwise you may be left scratching your head (like I did) as to why it won&#39;t build properly!</p><p>To post messages to the RM Chatroom I am using the existing <em>Messenger BOT API</em> example <a href="https://github.com/Refinitiv-API-Samples/Example.MessengerChatBot.Python">MessengerChatBot.Python</a> from Github — full details are provided on the site.</p><h3>Key Code Snippets</h3><p>As there is a considerable amount of code involved, I will be omitting much of the code here and mostly showing only key code snippets — please refer to the <a href="https://github.com/Refinitiv-API-Samples/Workflow.EikonAPI.Python.TechnicalAnalysis">Github repository</a> for the full source code.</p><p>So, let me crack on with the code — in the following order:</p><ul><li>various helper functions for the Technical Analysis, timing &amp; chart plotting</li><li>the main control section</li><li>finishing with the ongoing analysis loop.</li></ul><h4>Simple Moving Averages</h4><p>This function uses the TA-Lib SMA function to calculate the Simple Moving Average using the Close price for two periods — which you will note later are 14 for the short period and 200 for the long period. As you will see later, the period interval itself can vary e.g minute, daily, monthly, hourly — so for example, calculate SMA for 14 days and 200 days.</p><p>With the calculated SMAs, it then uses the following logic to generate Buy and Sell signals:</p><ul><li>If the short period SMA crosses up through the long period SMA then this is a buy signal</li><li>If the short period SMA crosses down through the long period SMA then this is a sell signal</li></ul><pre>def SMA(close,sPeriod,lPeriod):<br>    shortSMA = ta.SMA(close,sPeriod)<br>    longSMA = ta.SMA(close,lPeriod)<br>    smaSell = ((shortSMA &lt;= longSMA) &amp; (shortSMA.shift(1) &gt;= longSMA.shift(1)))<br>    smaBuy = ((shortSMA &gt;= longSMA) &amp; (shortSMA.shift(1) &lt;= longSMA.shift(1)))<br>    return smaSell,smaBuy,shortSMA,longSMA</pre><p>The resultant <em>smaSell </em>and <em>smaBuy </em>Series will contain the date/time and a flag to indicate a signal e.g. for a daily interval</p><pre>Date<br>2018-02-15    False<br>2018-02-16    False<br>2018-02-19    True<br>2018-02-20    False</pre><h4>Relative Strength Index</h4><p>RSI calculation is usually done for a 14 day period — so once again I feed in the Close price for the instrument to the TA-Lib RSI function. The common methodology is to set high and low thresholds of the RSI at 70 and 30. The idea is that if the lower threshold is crossed, the asset is becoming oversold and we should buy. Conversely, if the upper threshold is crossed then the asset is becoming overbought and we should sell.</p><pre>def RSI(close,timePeriod):    <br>    rsi = ta.RSI(close,timePeriod)<br>    rsiSell = (rsi&gt;70) &amp; (rsi.shift(1)&lt;=70)<br>    rsiBuy = (rsi&lt;30) &amp; (rsi.shift(1)&gt;=30)<br>    return rsiSell,rsiBuy, rsi</pre><p>As per my SMA function, my RSI function also returns a Series containing date/time and a flag to indicate buy/sell signals</p><h4>Stochastics</h4><p>The TA-Lib Stoch function returns two lines <em>slowk </em>and <em>slowd </em>which can then be used to generate the buy/sell indicators. A crossover signal occurs when the two lines cross in the overbought region (commonly above 80) or oversold region (commonly below 20). When a slowk line crosses below the slowd line in the overbought region it is considered a sell indicator. Conversely, when an increasing slowk line crosses above the slowd line in the oversold region it is considered a buy indicator.</p><pre>def Stoch(close,high,low):    <br>    slowk, slowd = ta.STOCH(high, low, close)</pre><pre>    stochSell = ((slowk &lt; slowd) &amp; <br>        (slowk.shift(1) &gt; slowd.shift(1))) &amp; (slowd &gt; 80)<br>    stochBuy = ((slowk &gt; slowd) &amp; <br>        (slowk.shift(1) &lt; slowd.shift(1))) &amp; (slowd &lt; 20)</pre><pre>    return stochSell,stochBuy,slowk,slowd</pre><h3>Sending a Trade Signal to the Chat Room.</h3><p>I need a way of letting users know that a Trade signal has been generated by the Technical Analysis. So, I am going to use the Messenger BOT API to send messages to other Refinitiv Messenger users. I am re-purposing the existing <a href="https://github.com/Refinitiv-API-Samples/Example.MessengerChatBot.Python">MessengerChatBot.Python</a> example from GitHub.<br>FYI: the acronym ‘RIC’ stands for Reuters Instrument Code — so for example the code ‘VOD.L’ represents Vodafone from LSE.</p><pre># Key code snippets - see Github for full source<br>def sendSignaltoChatBot(myRIC, signalTime, indicators):<br>    indicatorList = &#39;,&#39;.join(indicators.values)<br>    message = f&quot;TA signal(s) Generated : {indicatorList} <br>      at {signalTime} for {myRIC}&quot;<br>    <br>    # Connect, login and send message to chatbot<br>    rdp_token = RDPTokenManagement( bot_username, <br>        bot_password, app_key)<br>    access_token = cdr.authen_rdp(rdp_token)<br>    <br>    if access_token:<br>        # Join associated Chatroom<br>        joined_rooms = cdr.join_chatroom(access_token, <br>           chatroom_id)<br>        if joined_rooms:<br>            cdr.post_message_to_chatroom(access_token, <br>                joined_rooms, chatroom_id, message)</pre><h3>Run the Technical Analysis</h3><p>Initially, I will do a historical TA run, after which I will use this function to run the above 3 TA methodologies on the data I get as part of the ongoing Technical Analysis.</p><p>I am going to repeat some of this code later in the main historical TA run loop — purely for ease of reading.</p><pre>def runAllTA(myRIC, data):<br>    <br>    price = data[&#39;CLOSE&#39;]<br>    high = data[&#39;HIGH&#39;]<br>    low = data[&#39;LOW&#39;]<br>        <br>    # Simple Moving Average calcs<br>    smaSell,smaBuy,shortSMA,longSMA <br>        = SMA(price,shortPeriod,longPeriod)<br>    # Do the RSI calcs<br>    rsiSell,rsiBuy,rsi = RSI(price,shortPeriod)<br>    # and now the stochastics <br>    stochSell,stochBuy,slowk,slowd = Stoch(price, high, low)</pre><pre>    # Now collect buy and sell Signal timestamps into a single df<br>    sigTimeStamps = pd.concat([smaSell, smaBuy, stochSell, <br>        stochBuy, rsiSell, rsiBuy],axis=1)<br>    sigTimeStamps.columns=[&#39;SMA Sell&#39;,&#39;SMA Buy&#39;,&#39;Stoch Sell&#39;,<br>        &#39;Stoch Buy&#39;,&#39;RSI Sell&#39;,&#39;RSI Buy&#39;]<br>    signals = sigTimeStamps.loc[sigTimeStamps[&#39;SMA Sell&#39;] | <br>        sigTimeStamps[&#39;Stoch Sell&#39;] |sigTimeStamps[&#39;RSI Sell&#39;] | <br>        sigTimeStamps[&#39;SMA Buy&#39;] | sigTimeStamps[&#39;Stoch Buy&#39;] | <br>        sigTimeStamps[&#39;RSI Buy&#39;]]<br>    <br>    # Compare final signal Timestamp with latest data TimeStamp<br>    if (data.index[-1]==signals.index[-1]):<br>        final = signals.iloc[-1]<br>        # filter out the signals set to True and send to ChatBot<br>        signal = final.loc[final]<br>        signalTime = signal.name.strftime(&quot;%Y-%m-%dT%H:%M:%S&quot;)<br>        indicators = signal.loc[signal].index<br>        sendSignaltoChatBot(myRIC, signalTime, indicators)</pre><p>If the timestamp of the final TA signal, matches the timestamp of the most recent data point — then we have one or more new trade signal(s) — so inform the Chatroom users via the Chat BOT.</p><h4>Timing Helper functions</h4><p>I also need a few helper functions to calculate some time values based on the selected interval — the main one is…</p><pre># Calculate Start &amp; End time for our historical data request window</pre><pre>def startEnd(interval):<br>    end = datetime.now()<br>    start = {<br>      &#39;minute&#39;: lambda end: end - relativedelta(days=5),<br>      &#39;hour&#39;: lambda end: end - relativedelta(months=2),<br>      &#39;daily&#39;: lambda end: end - relativedelta(years=2),<br>      &#39;weekly&#39;: lambda end: end - relativedelta(years=5),<br>      &#39;monthly&#39;: lambda end: end - relativedelta(years=10),<br>    }[interval](end)<br>    return start.strftime(&quot;%Y-%m-%dT%H:%M:%S&quot;),<br>        end.strftime(&quot;%Y-%m-%dT%H:%M:%S&quot;)</pre><h3>Plotting functions</h3><p>Whilst not essential to the workflow, I wanted to plot a few charts to provide a visual representation of the various TA indicators — so we can try and visually tie-up instances where a price rises or drops in line with a TA trade signal — so for example when the short SMA crosses up through the long SMA, do we see an upward trend in the price after that point in time?</p><pre># As per before, key code snips only...</pre><pre># Use a formatter to remove weekends from date axis <br># to smooth out the line.<br>class MyFormatter(Formatter):<br>    def __init__(self, dates, fmt=&#39;%Y-%m-%d&#39;):<br>        self.dates = dates<br>        self.fmt = fmt<br>    def __call__(self, x, pos=0):<br>        &#39;Return the label for time x at position pos&#39;<br>        ind = int(round(x))<br>        if ind&gt;=len(self.dates) or ind&lt;0: return &#39;&#39;<br>        return self.dates[ind].strftime(self.fmt)</pre><pre># Plot the Close price and short and long Simple Moving Averages<br>def plotSMAs(ric,close,sma14,sma200,sell,buy):<br>    x = close.index<br>    plt.rcParams[&quot;figure.figsize&quot;] = (28,8)<br>    fig, ax = plt.subplots(facecolor=&#39;0.25&#39;)<br>    ax.plot(np.arange(len(x)),close, label=&#39;Close&#39;,color=&#39;y&#39;)<br>    ax.plot(np.arange(len(x)),sma14,label=&quot;SMA 14&quot;, color=&#39;g&#39;)<br>    ax.plot(np.arange(len(x)),sma200,label=&quot;SMA 200&quot;,  <br>        color=&#39;tab:purple&#39;)<br>    plt.show()</pre><pre># Plot the Close price in the top chart and RSI in the lower chart<br>def plotRSI(ric,close,rsi):<br>    plt.rcParams[&quot;figure.figsize&quot;] = (28,12)<br>    fig = plt.figure(facecolor=&#39;0.25&#39;)<br>    gs1 = gridspec.GridSpec(2, 1)<br>    # RSI chart<br>    ax = fig.add_subplot(gs1[1])<br>    ax.xaxis.set_major_formatter(formatter)<br>    ax.plot(np.arange(len(rsi.index)), rsi.values,color=&#39;b&#39;)<br>    plt.axhline(y=70, color=&#39;w&#39;,linestyle=&#39;--&#39;)<br>    plt.axhline(y=30, color=&#39;w&#39;,linestyle=&#39;--&#39;)<br>    # Close Price chart<br>    axc = fig.add_subplot(gs1[0])<br>    axc.plot(np.arange(len(rsi.index)), close, color=&#39;y&#39;)<br>    plt.show()</pre><pre># Plot Close price in top chart and in the slowk + slowd lines in lower chart<br>def plotStoch(ric,close,slowK,slowD):<br>    plt.rcParams[&quot;figure.figsize&quot;] = (28,12)<br>    fig = plt.figure(facecolor=&#39;0.25&#39;)<br>    gs1 = gridspec.GridSpec(2, 1)<br>    ax = fig.add_subplot(gs1[1])<br>    # Stochastic lines chart<br>    ax.plot(np.arange(len(slowk.index)), slowk.values,<br>        label=&quot;Slow K&quot;,color=&#39;m&#39;)<br>    ax.plot(np.arange(len(slowk.index)), slowd.values,<br>        label=&quot;Slow D&quot;,color=&#39;g&#39;)<br>    plt.axhline(y=80, color=&#39;w&#39;,linestyle=&#39;--&#39;)<br>    plt.axhline(y=20, color=&#39;w&#39;,linestyle=&#39;--&#39;)<br>    # Closing price chart<br>    axc = fig.add_subplot(gs1[0])<br>    axc.plot(np.arange(len(close.index)), close, color=&#39;y&#39;)<br>    plt.show()</pre><p>So, that’s the helper functions out of the way — let’s move on the main control section</p><h3>Connecting to the Eikon application</h3><p>To connect to my running instance of Eikon (or Workspace) I need to provide my Application Key (which can be generated within Eikon using the AppKey Generator app).</p><pre>ek.__version__ ek.set_app_key(&#39;&lt;your app key&gt;&#39;)</pre><h3>Some initialisation code</h3><p>I need to calculate the start and end date for my price query — based on the chosen periodicity/interval, as well as specify the periods for moving averages.</p><p>Also, as I will be requesting the price of each instrument individually, I create a container to hold all the price data for the full basket of instruments.</p><p>Finally, I set some display properties for the Pandas dataframe.</p><pre>myInterval = &#39;daily&#39;    # &#39;minute&#39;, &#39;hour&#39;, &#39;daily&#39;, &#39;weekly&#39;, &#39;monthly&#39;<br>myStart, myEnd  = startEnd(myInterval)<br>timestampLen = timeStampLength(myInterval)<br>print(f&#39;Interval {myInterval} from {myStart} to {myEnd} : Timestamp Length {timestampLen}&#39;)<br>shortPeriod = 14<br>longPeriod = 200<br>basket={}<br># Do we want to plot charts?<br>plotCharts = True<br># Dataframe display setting<br>pd.set_option(&quot;display.max_rows&quot;, 999)<br>pd.set_option(&#39;precision&#39;, 3)</pre><h4>TA Analysis summary output</h4><p>Once the initial historical TA has been run, I want to present a summary table of the signal over that period.<br> For this, I am going to use a Dataframe to output the results in a readable format.<br> I am also creating some blank columns which I will use for padding the dataframe later.</p><pre>outputDF = pd.DataFrame(columns=  <br>    [&#39;RIC&#39;,&#39;Name&#39;,&#39;ISIN&#39;,&#39;Close&#39;,&#39;Periodicity&#39;,&#39;Intervals Up&#39;,<br>     &#39;Intervals Down&#39;,&#39;Unchanged&#39;,&#39;1wk %ch&#39;,&#39;1M %ch&#39;,&#39;YTD %ch&#39;,<br>     &#39;6M %ch&#39;, &#39;1yr %ch&#39;,&#39;SMA Sell&#39;,&#39;SMA Buy&#39;,&#39;Stoch Sell&#39;,<br>     &#39;Stoch Buy&#39;,&#39;RSI Sell&#39;, &#39;RSI Buy&#39; ])</pre><pre>blankSignalCols = [&#39;N/A&#39;]*6<br>blankNonSignalCols = [&#39; &#39;]*13</pre><h4>Convert my ISIN symbols to RICs</h4><p>Whilst Eikon can accept various Symbology types for certain interactions, I need to specify RICs (Reuters Instrument Code) for much of the data I intend to access.</p><p>Therefore, I could just start with a bunch of RICs — but not everyone works with RICs — so here is an example of symbology conversion at work.</p><pre>myISINs = [ &#39;GB0002634946&#39;, &#39;GB00B1YW4409&#39; ] <br>myRICs = ek.get_symbology(myISINs, <br>            from_symbol_type=&#39;ISIN&#39;,    <br>            to_symbol_type=&#39;RIC&#39;)</pre><p>Just for your reference, the get_symbology function can accept <em>from</em> and <em>to</em> symbol types of</p><ul><li>CUSIP</li><li>ISIN</li><li>SEDOL</li><li>RIC</li><li>ticker</li><li>lipperID</li><li>IMO</li></ul><p>In addition, you can also convert to the ‘OAPermID’ type.</p><h4>Snapshot some summary data values</h4><p>Once I have run the TA I want to present a summary table reflecting the price changes for each instrument over various periods such as a week, month, year etc — along with the TA results.</p><p>So, for this, I am using the get_data method to obtain various Percent price change values as well the name of the corporate entity and the most recent Closing price</p><pre>listRICs = list(myRICs.RIC) </pre><pre>pcts, err = ek.get_data( instruments = listRICs, <br>    fields = [  <br>    &#39;TR.CommonName&#39;, &#39;TR.CLOSEPRICE&#39;, &#39;TR.PricePctChgWTD&#39;, <br>    &#39;TR.PricePctChgMTD&#39;, &#39;TR.PricePctChgYTD&#39;, &#39;TR.PricePctChg6M&#39;, <br>    &#39;TR.PricePctChg1Y&#39;, ] <br>) </pre><pre>pcts.set_index(&#39;Instrument&#39;,inplace=True)</pre><p>In the above call, I am requesting each instrument’s per cent Price change for Week, Month and Year to Date — and the 6m and 1yr period as well.</p><h3>Putting it all together for our initial ‘historical’ analysis run</h3><p>I can now go ahead and request my historical data and perform the Technical Analysis.</p><p>As well as interval data at the minute, hour, daily etc Eikon product can also provide tick data — i.e. individual trades as well as Bid//Ask changes. However, there are some differences in the data set for tick data compared to the other intervals:</p><ul><li>Historical tick data will be indexed on the date+time of every tick — and therefore the index can vary across instruments</li><li>Intervalised data will be indexed according to the interval e.g. every minute, hour etc and therefore use the same index values across multiple instruments</li><li>I can get high, low prices for interval data (which is needed for the Stochastic TA) but not for tick data</li></ul><p>As you can see, since the tick data is not interval based, it does not make sense from a TA point of view. For interval data, I can specify multiple RICs in the get_timeseries call and get back a single dataframe with the prices for all the RICs. However, to make the code easier to read, I will loop through the RICs and request each one individually rather than slightly increased subsequent complication involved if I have to use a single dataframe containing all the data.</p><p>I have split the following section of code into smaller chunks for ease of reading and annotations.</p><p>For each RIC code in our list, the first thing I do is use the get_timeseries function to request a subset of fields at the specified Interval for the previously calculated time period.</p><pre>for ISIN, symb in myRICs.iterrows():<br>    myRIC=symb[&#39;RIC&#39;]<br>    data = ek.get_timeseries(myRIC,  <br>        fields = [&#39;CLOSE&#39;,&#39;HIGH&#39;,&#39;LOW&#39;],<br>        start_date=myStart,  <br>        end_date=myEnd,<br>        interval = myInterval)</pre><pre>price = data[&#39;CLOSE&#39;]<br>    high = data[&#39;HIGH&#39;]<br>    low = data[&#39;LOW&#39;]</pre><pre>basket[myRIC]=data # Save each instrument&#39;s raw data for later use</pre><p>Next, I calculate values for Price Up, Down and no change movements for the analysis period. Then I call the various TA functions to calculate the indicators and generate the signals (&amp; plot charts if enabled).</p><pre># Count Price Up, Down and No change<br>    upCnt = (price &lt; price.shift(1)).value_counts().loc[True]<br>    downCnt = (price &gt; price.shift(1)).value_counts().loc[True]<br>    <br>    try:<br>        ncCnt = (price == price.shift(1)).value_counts().loc[True]<br>    except KeyError as e:<br>        ncCnt = 0<br>    <br>    # Do the Simple Moving Average calcs<br>    smaSell,smaBuy,shortSMA,longSMA = <br>        SMA(price,shortPeriod,longPeriod)<br>    if plotCharts:<br>        plotSMAs(myRIC,price,shortSMA,longSMA,smaSell,smaBuy)<br>            <br>    # Do the RSI calcs<br>    rsiSell,rsiBuy,rsi = RSI(price,shortPeriod)<br>    if plotCharts:<br>        plotRSI(myRIC,price,rsi)</pre><pre># Stochastic calcs<br>    stochSell,stochBuy,slowk,slowd = Stoch(price, high, low)<br>    if plotCharts:<br>        plotStoch(myRIC,price,slowk,slowd)<br>    <br>    # Get the Percent Change data for thisRIC<br>    pct = pcts.loc[myRIC]</pre><p>Finally, I use the data and signals etc to generate a dataframe displaying a Summary Table of the various stats + any signals generated for our configured TA time period and interval.</p><pre># Now we build the summary table<br>    # starting with the non-trade signal related stuff<br>    nonSignalData = [myRIC,<br>                         pct[&#39;Company Common Name&#39;],<br>                         ISIN,<br>                         pct[&#39;Close Price&#39;],<br>                         myInterval,<br>                         upCnt,downCnt,ncCnt,<br>                         pct[&#39;WTD Price PCT Change&#39;],<br>                         pct[&#39;MTD Price PCT Change&#39;],<br>                         pct[&#39;YTD Price PCT Change&#39;],<br>                         pct[&#39;6-month Price PCT Change&#39;],<br>                         pct[&#39;1-year Price PCT Change&#39;]]<br>    <br>    # Now build the Signal buy &amp; sell columns for each TA indicator<br>    sigTimeStamps = pd.concat([smaSell, smaBuy, stochSell, <br>        stochBuy, rsiSell, rsiBuy],axis=1)<br>    sigTimeStamps.columns=[&#39;SMA Sell&#39;,&#39;SMA Buy&#39;,&#39;Stoch Sell&#39;,<br>        &#39;Stoch Buy&#39;,&#39;RSI Sell&#39;,&#39;RSI Buy&#39;]<br>    signals = sigTimeStamps.loc[<br>        sigTimeStamps[&#39;SMA Sell&#39;] | sigTimeStamps[&#39;Stoch Sell&#39;] |<br>        sigTimeStamps[&#39;RSI Sell&#39;] | sigTimeStamps[&#39;SMA Buy&#39;] | <br>        sigTimeStamps[&#39;Stoch Buy&#39;] | sigTimeStamps[&#39;RSI Buy&#39;]<br>       ]</pre><pre># If any trade signals were generated for our time period<br>    # add them to the summary table<br>    signalCnt = len(signals)<br>    if (signalCnt):<br>        first = True<br>        for index,row in signals.iterrows():<br>            sigDate = str(index)[0:timestampLen]<br>            signalList = [sigDate if item else &quot;&quot; for item in row]<br>            # First row to contain non-signal stuff, <br>            # subsequent rows only trade signals<br>            tempRow = nonSignalData.copy() <br>                if first else blankNonSignalCols.copy()<br>            tempRow.extend(signalList)<br>            s = pd.Series(tempRow, index=outputDF.columns)<br>            outputDF = outputDF.append(s,ignore_index=True)<br>            first=False<br>    else:  # No signals so just the non-signal related stuff<br>        tempRow = nonSignalData.copy()<br>        tempRow.extend(blankSignalCols)<br>        outputDF = outputDF.append(tempRow)</pre><pre>outputDF.head(5)<br>outputDF.tail(5)</pre><p>Once that is done, I simply display the head and tail of the Summary Table.</p><p>Before we get to the table, let us have a quick look at the charts I plotted and compare them to the subset of TA signals in the table displayed further down.</p><p>Here I have included</p><ul><li>the SMA, RSI and Stochastic charts for the final RIC — III.L</li><li>the head of the outputDF dataframe - showing the first few trading signals for BAE Systems (BAES.L)</li><li>the tail of the outputDF dataframe which represents the final few signals for 3I Group (III.L).</li></ul><h4>Simple Moving Average chart for 3I Group PLC — III.L</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ojHLtL9OoP4Zsin7.png" /></figure><p>Towards the end of the Simple Moving Average chart, you can see that the SMA14 crosses down through the SMA200 line which is a sell indicator — and if you refer to the tail end of the Summary table below you will see an SMA Sell indicator for the 5th of March 2020.</p><h4>Relative Strength Index chart for 3I Group PLC — III.L</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9Usx-NQOapCQu7wp.png" /></figure><p>Here I am plotting the Close price in the upper chart and the RSI value in the lower chart. Just at the tail end, you can see that the RSI value crosses below the lower threshold twice around the end of Feb / start of March — which corresponds to the RSI Buy indicator on 2020–03–05 in the Summary table below</p><h4>Stochastics chart for 3I Group PLC — III.L</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bStAYqpI4BRnW1zkJRfYhg.png" /></figure><p>Once again I am plotting the Close price on top and the Stochastics <strong>slowk </strong>and <strong>slowd </strong>lines in the lower chart. You can see that the <strong>slowk </strong>line crosses above the <strong>slowd </strong>line in the oversold region (below 20) on three occasions — i.e. buy indicators reflected in the summary table below with Stochastic Buy entries for <strong>2020–02–28,</strong> <strong>2020–03–03 </strong>and <strong>2020–03–13</strong>. <br>Finally, just before the end of the chart, we see the <strong>slowk</strong> and <strong>slowd</strong> lines cross in the overbought region (above 80). This is reflected in the table below as a Stochastic Sell entry at <strong>2020–03–27</strong>.</p><h3>Historical Summary table</h3><p>After the initial Technical Analysis run using the historical data, I output a historical Summary table with some basic stats as well as the history of the Trade signals for the configured Interval and Time Period.</p><p>For the basic stats, I display the Percent change for various periods such as Week to Day, Month to Day, 6 months — to provide an indication of just how the particular stock has been trading over those periods. I also display the number of intervals where the price has gone up, down or no change as potentially useful reference points.</p><p>The rightmost columns of the table contain the Buy and Sell signals occurrences for the 3 TA methodologies — one row for each date/time that triggered a signal — you may occasionally see more than one signal in a single row. For example, whilst I was testing both RSI and Stoch indicated Buy signals on 11th October 2018 for the 3i Group (III.L) — concerning this, you may find the Reuters <a href="https://www.reuters.com/companies/III.L/charts">3 yr chart for III</a> interesting…</p><h4>Head of the Summary table — showing the first few trading signals for BAE Systems (BAES.L)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECDuxKv8GCxmQZmS5XCxTQ.png" /><figcaption>Head of my output summary table for BAES.L</figcaption></figure><h4>The tail of the Summary table — showing the most recent trading signals for 3I Group (III.L)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5l9MoV6va_ID20Zvv0Pbg.png" /><figcaption>Recent trading signals for 3I group.</figcaption></figure><p>Note how the final few signals for 3I group compare with the crossover points on the corresponding charts.</p><h3>Ongoing Technical Analysis</h3><p>Now that I have the historical analysis out of the way, I will move onto the ongoing <em>‘real-time’</em> analysis. In other words, the code that I can keep running to perform the TA on an ongoing basis at the configured interval.</p><pre>while True:<br>    gotoSleep(myInterval)<br>    for myRIC in listRICs:<br>        historical = basket[myRIC]<br>        latest = ek.get_timeseries(myRIC,fields = <br>            [&#39;CLOSE&#39;,&#39;HIGH&#39;,&#39;LOW&#39;],<br>            count = 1, interval = myInterval)  <br>        # Delete earliest data point<br>        historical.drop(historical.index[0])<br>        # Append latest data point<br>        historical = historical.append(latest)<br>        runAllTA(myRIC, historical)<br>        # Udpate basket with latest values<br>        basket[myRIC] = historical</pre><p>I put the script to sleep for our configured interval, and when it wakes I request the latest data points for each RIC.</p><p>The simplest approach would be to just make the above get_timeseries calls with a revised start_date and end_date parameters. However, this would be quite wasteful of resources and so I will request just the latest data point for my configured interval.</p><p>To do this, I make the call with count=1 (rather than Start/End times) to get just the latest data point. I then drop the earliest data point from our historical data points and append the latest one.</p><p>I can then invoke the Technical Analysis functions with the most recent data included.</p><h3>Closing Summary</h3><p>I could now leave this script running with my preferred interval and it will send messages to the chatroom, each time the Technical Analysis yields a Buy or Sell signal, like the ones shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/0*5BweOuWf0Gt4kVCR.png" /><figcaption>Example Buy and Sell Signal in the Chatroom</figcaption></figure><p>Note: For the purpose of the above screen capture, I did a run with the interval set to ‘<em>minute</em>’ — in an attempt to generate signals sooner rather than later.</p><p>For a trader who uses Simple Moving Average, Relative Strength Indices and/or Stochastic charts to help inform their trading decisions — this could mean they don’t need to actively sit there eyeballing charts all day long.</p><p>I hope you found this exercise useful and no doubt there are many possible improvements/refinements that could be made to both the code and the simple TA methodology I have used. A few examples to consider are:</p><ul><li>In the Summary table extract above I can see that on 2020–03–05, SMA based TA is indicating a Sell whereas the RSI based TA is indicating a Buy — which suggests that further refinements are required</li><li>An RSI related article I read, suggested that once the line crosses a threshold it may be better to wait till it crosses back in the opposite direction before generating a signal — so for example, if the crosses below %30, wait till it crosses back up above 30% before generating a Buy signal.</li><li>In my summary output table, I show the ‘% change’ for a week, month, year etc — which could be relevant for my ‘<em>daily</em>’ interval-based TA — but not so much if say I used an ‘<em>hourly’</em> interval. It was suggested that a better approach could be to show ‘% change’ values for say, Hour t, Hour t+1, t+5, t+10 etc according to my chosen interval.</li><li>Another improvement could be to show up/down markers on the plot lines highlighting the crossover points.</li></ul><p>As you can expect, there is no shortage of material on Technical Analysis to be found on <a href="https://medium.com/tag/technical-analysis">Medium.com</a> and the internet itself.</p><p><strong>NOTE:</strong> I do <strong>not </strong>endorse the above workflow as something that should be used for active trading — it is purely an educational example.</p><h3>References</h3><p><a href="https://developers.refinitiv.com/eikon-apis/eikon-data-api">Eikon Data API</a> <br><a href="https://developers.refinitiv.com/messenger-api">Refinitiv Messenger API</a><br><a href="https://ta-lib.org/hdr_doc.html">TA-Lib</a> — Open Source Technical Analysis Library<br><a href="https://github.com/mrjbq7/ta-lib">ta-lib</a> — Python wrapper for above TA-Lib</p><h3>DOWNLOADS</h3><p>Source for <a href="https://github.com/Refinitiv-API-Samples/Workflow.EikonAPI.Python.TechnicalAnalysis">this workflow</a> on GitHub<br>Source for <a href="https://github.com/Refinitiv-API-Samples/Example.MessengerChatBot.Python">Messenger Chat Bot</a> example on GitHub</p><p><em>Originally published at </em><a href="https://developers.refinitiv.com/article/create-technical-analysis-triggers-and-signals-using-eikon-data-api"><em>https://developers.refinitiv.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1429eafaaf2c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lseg-developer-community/create-technical-analysis-triggers-and-signals-using-the-eikon-data-api-1429eafaaf2c">Using Technical Analysis indicators to send Buy or Sell trading signals to a Chatroom</a> was originally published in <a href="https://medium.com/lseg-developer-community">LSEG Developer Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Instrument Pricing Analytics — Volatility Surfaces and Curves]]></title>
            <link>https://medium.com/lseg-developer-community/instrument-pricing-analytics-volatility-surfaces-and-curves-developer-community-8b70b01cd277?source=rss-b172232f4cfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b70b01cd277</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[volatility]]></category>
            <category><![CDATA[curves]]></category>
            <dc:creator><![CDATA[Umer Nalla]]></dc:creator>
            <pubDate>Tue, 21 Apr 2020 13:09:58 GMT</pubDate>
            <atom:updated>2021-05-20T15:24:40.299Z</atom:updated>
            <content:encoded><![CDATA[<h3>Volatility Surfaces and Curves from the Refinitiv Data Platform</h3><h3>Instrument Pricing Analytics — Volatility Surfaces</h3><p>In this article, I will demonstrate how easily you can access Volatility Surface data from the Refinitiv Data Platform.</p><p>Volatility Surfaces, like other pricing data (ZC Curves, Inflation Curves), are used to model risk factors and can be used to power risk management or valuation systems. The Volatility Surface can also be analysed across Tenors or Strikes (as per the examples below) to get a sense of how the risk is distributed along these axes.</p><p>The Refinitiv Data Platform is a next-generation platform for accessing the broadest range of Financial, Risk, Research, Reference and Analytics data, using one single product and one easy to use API.</p><p>One such data set is the Instrument Pricing Analytics — which includes Volatility Surfaces in a relatively easy to access format.</p><p>I think the best way to highlight just how easily you can access and use the Volatility Surface data is via some code and some colourful graphs — so let me dive straight into the code….</p><h3>Initialisation</h3><p>First thing I need to do is import my libraries and then run my scripts to define my helper functions. As you will note I am importing the Refinitiv Data Platform library which will be my main interface to the Platform — as well as few of the most commonly used Python libraries.</p><p>You can read more about the Refinitiv Data Platform Library in my <a href="https://developers.refinitiv.com/article/discover-our-refinitiv-data-platform-library-part-2">previous article</a>.</p><pre>import pandas as pd <br>import requests <br>import numpy as np <br>import json <br>import refinitiv.dataplatform as rdp <br>%run -i ../credentials.ipynb <br>%run ./plotting_helper.ipynb</pre><p>As the names would suggest, the credentials file contains my login credentials and the plotting_helper contains the full plotting code. For brevity, I will only share some of the key plotting code snippets in this article - for the rest please refer to the full file (link at the end).</p><h3>Connect to the Refintiv Data Platform</h3><p>I am using my helper functions to establish a connection to the Platform by requesting a session and opening it.</p><pre>APP_KEY = get_app_key() <br>RDP_LOGIN = get_rdp_login() <br>RDP_PASSWORD = get_rdp_password() </pre><pre>session = rdp.PlatformSession( <br>    APP_KEY, <br>    rdp.GrantPassword( <br>        username = RDP_LOGIN, <br>        password = RDP_PASSWORD <br>    ) <br>) <br>session.open()</pre><h3>Endpoint Interface</h3><p>In my <a href="https://developers.refinitiv.com/en/article-catalog/article/discover-our-refinitiv-data-platform-library-part-2">previous article</a> I mentioned how the Refinitiv Data Platform library consists of three layers as follows:</p><ol><li>Function: Highest level — single function call to get data</li><li>Content: High level — Fuller response and Level 1 Streaming data too</li><li>Delivery: For Level 2 Streaming data and data / content sets not (yet) supported by above Layers</li></ol><p>Whilst there are plans to offer some Content layer support for IPA data, at present it is limited to the Delivery layer. Each unique content set on the Platform has its own Endpoint and we can use the Delivery Layers Endpoint interface to access that content.</p><p>Using the Endpoint interface to request IPA content is fairly straightforward</p><ol><li>Identify the required IPA Endpoint (URL)</li><li>Use the Endpoint Interface to send a request to the Endpoint</li><li>Decode the response and extract the IPA data</li></ol><h3>Identifying the Surfaces Endpoint</h3><p>To ascertain the Endpoint, we can use the Refinitiv Data Platform’s <a href="http://api.refinitiv.com/">API Playground</a> — an interactive documentation site you can access once you have a valid Refinitiv Data Platform account.</p><p>So, firstly I can search for <em>‘surfaces’</em> to narrow down the list of Endpoints and then select the relevant Endpoint from the list. At present there is only one Endpoint for surfaces so that keeps it simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XwK2IXyr3b8aaDFz.png" /></figure><p>I copy the Endpoint URL — <strong><em>/data/quantitative-analytics-curves-and-surfaces/v1/surfaces</em></strong> — to use with the library’s Endpoint interface as follows:</p><pre>vs_endpoint = rdp.Endpoint(session,        &quot;https://api.refinitiv.com/data/quantitative-analytics-curves-and-surfaces/v1/surfaces&quot;)</pre><h4>Build our JSON Request</h4><p>Using the reference documentation or by referring to the example queries shown on the above API playground page, I can build up my Request.</p><p>Currently there are two Underlying Types of Volatility Surface supported:</p><ul><li>Eti : exchange-traded instruments like equities, equity indices, and futures.</li><li>Fx : Fx instruments.</li></ul><p>For example, the JSON request below, will allow me to generate an <em>ETI</em> Volatility Surface:</p><ul><li>for Renault, Peugeot, BMW and VW</li><li>from the Option Settle prices using an SSVI model</li><li>express the axes in Dates and Moneyness</li><li>and return the data in a matrix format</li></ul><p>The request is configurable and the various parameters &amp; options are listed on the API playground. For example, for ETI, the options are :</p><ul><li>Volatility Model : SVI or SSVI (Surface SVI)</li><li>Axes : Tenor / Date and Moneyness / Strike</li><li>Input : Settle or Implied</li><li>Data format : Matrix or List</li></ul><p>Another parameter worth mentioning is <strong><em>calculationDate</em></strong> which defaults to today — however, you can select up to 2 years in the past.</p><p>Note from the request below, how I can obtain data for multiple entities in a single request.</p><pre>eti_request_body={<br>    &quot;universe&quot;: [<br>        {<br>            &quot;surfaceTag&quot;: &quot;RENAULT&quot;,<br>            &quot;underlyingType&quot;: &quot;Eti&quot;,<br>            &quot;underlyingDefinition&quot;: {<br>                &quot;instrumentCode&quot;: &quot;RENA.PA&quot;<br>            },<br>            &quot;surfaceParameters&quot;: {<br>                &quot;inputVolatilityType&quot;: &quot;settle&quot;,<br>                &quot;volatilityModel&quot;: &quot;SSVI&quot;,<br>                &quot;xAxis&quot;: &quot;Date&quot;,<br>                &quot;yAxis&quot;: &quot;Moneyness&quot;<br>            },<br>            &quot;surfaceLayout&quot;: {<br>                &quot;format&quot;: &quot;Matrix&quot;,<br>            }<br>        },<br>        {<br>            &quot;surfaceTag&quot;: &quot;PEUGEOT&quot;,<br>            &quot;underlyingType&quot;: &quot;Eti&quot;,<br>            &quot;underlyingDefinition&quot;: {<br>                &quot;instrumentCode&quot;: &quot;PEUP.PA&quot;<br>            },<br>            &quot;surfaceParameters&quot;: {<br>                &quot;inputVolatilityType&quot;: &quot;settle&quot;,<br>                &quot;volatilityModel&quot;: &quot;SSVI&quot;,<br>                &quot;xAxis&quot;: &quot;Date&quot;,<br>                &quot;yAxis&quot;: &quot;Moneyness&quot;<br>            },<br>            &quot;surfaceLayout&quot;: {<br>                &quot;format&quot;: &quot;Matrix&quot;<br>            }<br>        },<br>        {<br>            &quot;surfaceTag&quot;: &quot;BMW&quot;,<br>            &quot;underlyingType&quot;: &quot;Eti&quot;,<br>            &quot;underlyingDefinition&quot;: {<br>                &quot;instrumentCode&quot;: &quot;BMWG.DE&quot;<br>            },<br>            &quot;surfaceParameters&quot;: {<br>                &quot;inputVolatilityType&quot;: &quot;settle&quot;,<br>                &quot;volatilityModel&quot;: &quot;SSVI&quot;,<br>                &quot;xAxis&quot;: &quot;Date&quot;,<br>                &quot;yAxis&quot;: &quot;Moneyness&quot;<br>            },<br>            &quot;surfaceLayout&quot;: {<br>                &quot;format&quot;: &quot;Matrix&quot;<br>            }<br>        },<br>        {<br>            &quot;surfaceTag&quot;: &quot;VW&quot;,<br>            &quot;underlyingType&quot;: &quot;Eti&quot;,<br>            &quot;underlyingDefinition&quot;: {<br>                &quot;instrumentCode&quot;: &quot;VOWG.DE&quot;<br>            },<br>            &quot;surfaceParameters&quot;: {<br>                &quot;inputVolatilityType&quot;: &quot;settle&quot;,<br>                &quot;volatilityModel&quot;: &quot;SSVI&quot;,<br>                &quot;xAxis&quot;: &quot;Date&quot;,<br>                &quot;yAxis&quot;: &quot;Moneyness&quot;<br>            },<br>            &quot;surfaceLayout&quot;: {<br>                &quot;format&quot;: &quot;Matrix&quot;<br>            }<br>        }],<br>    <br>    &quot;outputs&quot;:[&quot;ForwardCurve&quot;]<br>}</pre><p>I then send the request to the Platform using the instance of the Endpoint interface I created:</p><pre>eti_response = vs_endpoint.send_request(<br>    method = rdp.Endpoint.RequestMethod.POST,<br>    body_parameters = eti_request_body<br>)<br>print(json.dumps(eti_response.data.raw, indent=2))</pre><p>which returns (truncated output):</p><pre>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;surfaceTag&quot;: &quot;RENAULT&quot;,<br>      &quot;surface&quot;: [<br>        [<br>          null,<br>          &quot;0.5&quot;,<br>          &quot;0.6&quot;,<br>          &quot;0.7&quot;,<br>          &quot;0.75&quot;,<br>          &quot;0.8&quot;,<br>          &quot;0.85&quot;,<br>          &quot;0.9&quot;,<br>          &quot;0.95&quot;,<br>          &quot;0.975&quot;,<br>          &quot;1&quot;,<br>          &quot;1.025&quot;,<br>          &quot;1.05&quot;,<br>          &quot;1.1&quot;,<br>          &quot;1.15&quot;,<br>          &quot;1.2&quot;,<br>          &quot;1.25&quot;,<br>          &quot;1.3&quot;,<br>          &quot;1.4&quot;,<br>          &quot;1.5&quot;<br>        ],<br>        [<br>          &quot;2020-04-17&quot;,<br>          151.228406673774,<br>          135.920125078469,<br>          122.86790691327201,<br>          117.18354651815399,<br>          112.08385230536699,<br>          107.591702421095,<br>          103.72583979987999,<br>          100.49424156186599,<br>          99.1145748247136,<br>          97.8892006729819,<br>          96.8143663895993,<br>          95.88526180851889,<br>          94.4403961628731,<br>          93.4998284796127,<br>          93.0012573553598,<br>          92.8801138006228,<br>          93.07388242770041,<br>          94.1827555098251,<br>          95.9498515789429<br>        ],<br>...<br>[data removed for brevity]<br>...<br>      ],<br>      &quot;forwardCurve&quot;: {<br>        &quot;curveStructure&quot;: &quot;&quot;,<br>        &quot;dataPoints&quot;: {<br>          &quot;2020-04-17&quot;: 118.6756670207883,<br>          &quot;2020-05-15&quot;: 118.64156571404946,<br>          &quot;2020-06-19&quot;: 118.62192936542067,<br>          &quot;2020-09-18&quot;: 118.58953003063407,<br>          &quot;2020-12-18&quot;: 118.58964173796703,<br>          &quot;2021-03-19&quot;: 118.4610847286232,<br>          &quot;2021-06-18&quot;: 118.33652361354125,<br>          &quot;2021-12-17&quot;: 118.09769479650208<br>        }<br>      }<br>    }<br>  ]<br>}</pre><p>Once I get the response back, I extract the payload and use the Matplotlib library to plot my surface. For example, below I extract and plot the Volatility Surface data for ‘VW’.</p><pre>surfaces = eti_response.data.raw[&#39;data&#39;]<br>plot_surface(surfaces, &#39;VW&#39;)</pre><p>which plots the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*BjgqUARL5XERLHvD.png" /></figure><p>Where the key bits of code for plot_surface are :</p><pre># The Full code is in the plotting_helper file<br>def plot_surface_snip(surfaces, surfaceTag):<br>    surfaces = pd.DataFrame(data=surfaces)<br>    surfaces.set_index(&#39;surfaceTag&#39;, inplace=True)<br>    surface = surfaces[surfaces.index == surfaceTag][&#39;surface&#39;][0]<br>    <br>    strike_axis = surface[0][1:]<br>    surface = surface[1:]<br>    time_axis = []<br>    surface_grid = []<br>    for line in surface:<br>        time_axis.append(line[0])<br>        surface_grid_line = line[1:]<br>        surface_grid.append(surface_grid_line)</pre><pre>    time_axis = convert_yyyymmdd_to_float(time_axis)<br>    <br>    x = np.array(strike_axis, dtype=float)<br>    y = np.array(time_axis, dtype=float)<br>    Z = np.array(surface_grid, dtype=float)<br>    <br>    X,Y = np.meshgrid(x,y)<br>    <br>    ax.w_yaxis.set_major_formatter(ticker.FuncFormatter<br>        (format_date))<br>    <br>    surf = ax.plot_surface(X,Y,Z, cmap=cm.coolwarm, <br>        linewidth=0, antialiased=False)    <br>    plt.show()</pre><p>Note that I have used a formatter for the yAxis label in order to show the dates rather than the floating point date format required by matplotlib (see the <em>plotting_helper</em> notebook for the full code).</p><h3>Smile Curve</h3><p>I can also use the same surfaces response data to plot a Smile Curve.</p><p>For example, to compare the volatility smiles of the 4 equities at the chosen expiry time (where the maturity value of 1 is the first expiry):</p><pre>plot_smile(surfaces, 1)</pre><p>Produces the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eGyou386skyQdKMc.png" /></figure><p>Where the key bits of code for plot_smile are :</p><pre># The full code is in the plotting_helper file<br>def plot_smile_snip(surfaces, maturity):</pre><pre>    surfaces = pd.DataFrame(data=surfaces)</pre><pre>    for i in range(0,surfaces.shape[0]):<br>        label = surfaces.loc[i,[&#39;surfaceTag&#39;]][&#39;surfaceTag&#39;]<br>        surface = surfaces.loc[i,[&#39;surface&#39;]][&#39;surface&#39;]<br>        error = surfaces.loc[i,[&#39;error&#39;]][&#39;error&#39;] <br>            if &#39;error&#39; in surfaces else 0.0</pre><pre>    x=[]<br>    y=[]<br>    if (type(error) is float):<br>        x = surface[0][1:]<br>        y = surface[maturity][1:]<br>        title = &#39;Smile &#39; + str(surface[maturity][0])<br>        ax.plot(x,y,label=label)<br>            <br>    plt.show()Volatility Terms</pre><p>We can also use the same surfaces response data to plot the Term Structure (the full code for all the plots can be found in the plotting_helper file)</p><p>Let the user choose the Moneyness index — <strong>integer value</strong> — to use for the chart:</p><pre>moneyness=int(input(&quot;Moneyness:&quot;)) <br>plot_term_volatility(surfaces, moneyness)</pre><p>which gives me the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9h4YjZj9ELJD5l3M.png" /></figure><h3>Forward Curve</h3><p>Finally, observe that I can also use the same data to plot a Forward Curve e.g. for Renault:</p><pre>plot_forward_curve(surfaces, &#39;RENAULT&#39;)</pre><p>and I get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/0*lE595yscOPhAl1lr.png" /></figure><h3>FX Volatility Surface</h3><p>I can also use the same IPA Endpoint to request FX Volatility Surfaces</p><p>For example, the request below will allow me to generate an FX Volatility Surface:</p><ul><li>for EURUSD, GBPUSD and CFHUSD cross rates,</li><li>express the axes in Dates and Delta,</li><li>and return the data in a matrix format</li></ul><p>As I mentioned earlier, the request is configurable and the parameters &amp; options are listed on the API playground. For example, for the 4 parameters I used, the options are :</p><ul><li>Volatility Model : SVI (the default and only option)</li><li>Axes : Delta/Strike and Tenor/Date</li><li>Input : Implied (the default and only option)</li><li>Data format : Matrix or List</li></ul><p>With the previous ETI request, I explained that the <strong><em>calculationDate</em></strong> defaults to today’s date and can be overridden — as I have done below:</p><pre>fx_request_body={<br>    &quot;universe&quot;: [<br>        {<br>              &quot;underlyingType&quot;: &quot;Fx&quot;,<br>              &quot;surfaceTag&quot;: &quot;FxVol-GBPUSD&quot;,<br>              &quot;underlyingDefinition&quot;: {<br>                &quot;fxCrossCode&quot;: &quot;GBPUSD&quot;<br>              },<br>              &quot;surfaceLayout&quot;: {<br>                &quot;format&quot;: &quot;Matrix&quot;<br>              },<br>              &quot;surfaceParameters&quot;: {<br>                &quot;xAxis&quot;: &quot;Date&quot;,<br>                &quot;yAxis&quot;: &quot;Delta&quot;,<br>                &quot;calculationDate&quot;: &quot;2018-08-20T00:00:00Z&quot;,<br>                &quot;returnAtm&quot;: &quot;True&quot;<br>              }<br>        },<br>        {<br>              &quot;underlyingType&quot;: &quot;Fx&quot;,<br>              &quot;surfaceTag&quot;: &quot;FxVol-EURUSD&quot;,<br>              &quot;underlyingDefinition&quot;: {<br>                &quot;fxCrossCode&quot;: &quot;EURUSD&quot;<br>              },<br>              &quot;surfaceLayout&quot;: {<br>                &quot;format&quot;: &quot;Matrix&quot;<br>              },<br>              &quot;surfaceParameters&quot;: {<br>                &quot;xAxis&quot;: &quot;Date&quot;,<br>                &quot;yAxis&quot;: &quot;Delta&quot;,<br>                &quot;calculationDate&quot;: &quot;2018-08-20T00:00:00Z&quot;,<br>                &quot;returnAtm&quot;: &quot;True&quot;<br>              }<br>        },<br>        {<br>              &quot;underlyingType&quot;: &quot;Fx&quot;,<br>              &quot;surfaceTag&quot;: &quot;FxVol-CHFUSD&quot;,<br>              &quot;underlyingDefinition&quot;: {<br>                &quot;fxCrossCode&quot;: &quot;CHFUSD&quot;<br>              },<br>              &quot;surfaceLayout&quot;: {<br>                &quot;format&quot;: &quot;Matrix&quot;<br>              },<br>              &quot;surfaceParameters&quot;: {<br>                &quot;xAxis&quot;: &quot;Date&quot;,<br>                &quot;yAxis&quot;: &quot;Delta&quot;,<br>                &quot;calculationDate&quot;: &quot;2018-08-20T00:00:00Z&quot;,<br>                &quot;returnAtm&quot;: &quot;True&quot;<br>              }<br>        }<br>    ]<br>}</pre><pre>fx_response = vs_endpoint.send_request(<br>    method = rdp.Endpoint.RequestMethod.POST,<br>    body_parameters = fx_request_body<br>)</pre><pre>print(json.dumps(fx_response.data.raw, indent=2))</pre><p>returns something like the following:</p><pre>{<br>  &quot;data&quot;: [<br>    {<br>      &quot;surfaceTag&quot;: &quot;FxVol-GBPUSD&quot;,<br>      &quot;surface&quot;: [<br>        [<br>          null,<br>          -0.1,<br>          -0.15,<br>          -0.2,<br>          -0.25,<br>          -0.3,<br>          -0.35,<br>          -0.4,<br>          -0.45,<br>          0.0,<br>          0.45,<br>          0.4,<br>          0.35,<br>          0.3,<br>          0.25,<br>          0.2,<br>          0.15,<br>          0.1<br>        ],<br>        [<br>          &quot;2018-08-21T00:00:00Z&quot;,<br>          8.474304079340165,<br>          8.28725273729482,<br>          8.150419367003044,<br>          8.042395602302943,<br>          7.953593335183968,<br>          7.878996963438836,<br>          7.81580173425316,<br>          7.762474980925678,<br>          7.718366253495301,<br>          7.683547886830561,<br>          7.658891314968792,<br>          7.6463251372674845,<br>          7.649400323506564,<br>          7.674568043116656,<br>          7.734123792587141,<br>          7.853998599009499,<br>          8.099355202033308<br>        ],<br>...<br>[data removed for brevity]<br>...<br>      ]<br>    }<br>  ]<br>}</pre><p>Once again, I extract the payload and plot my surface — below I extract and plot the Volatility Surface for ‘Swiss Franc / US Dollar’.</p><pre>fx_surfaces = fx_response.data.raw[&#39;data&#39;] <br>plot_surface(fx_surfaces, &#39;FxVol-CHFUSD&#39;, True)</pre><p>produces the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*qjI53xMorsvGB4Kh.png" /></figure><h3>Plot other Curves with same data</h3><p>As with the ETI Surface Curve data, I can also use the FX data to plot other curves i.e. Smile curve and also a Volatility Term curve.</p><p>I have used the 3rd strike to plot the 3rd maturity term below:</p><pre>plot_term_volatility(fx_surfaces, 3)</pre><p>which creates something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IaSW7qdOJtbjMn1Z.png" /></figure><p>Currently, the date format for ETI and FX data differs — the ETI returns a Date only and the FX returns Date &amp; Time. As a consequence, if you refer to the plot_term_volatility code, you can see that I am stripping the time to make the x axis label look neater.</p><p>Also, since I am specifying <em>‘Delta’</em> rather than <em>‘Strike’</em> for yAxis value in my JSON request above - I can also plot a Smile curve with the same data.</p><pre>plot_smile(fx_surfaces, 3, True)</pre><p>which gives me the:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sCtmS4_H_0MZkhKT.png" /></figure><h3>Closing Summary</h3><p>I hope I have demonstrated just how straightforward it is to consume Surface Volatility data from the Refinitiv Data platform — and thereby allowing the generation of Volatility Surfaces for both Exchange-traded and FX instruments as well as other curves such as Smile, Volatility Term, and Forward curves — with relative ease.</p><p>If you found this useful, keep an eye out for my next article on the <strong>Zero Coupon Curves Endpoint</strong> where I hope to cover Bi-curves, Currency Basis Swap Adjusted curves and Collateral Currency Adjustment.</p><h3>References</h3><p><a href="https://developers.refinitiv.com/en/article-catalog/article/discover-our-refinitiv-data-platform-library-part-1">Discover our new upcoming Refinitiv Data Platform Library — Part 1</a> of my RDP Library Introduction article</p><p><a href="https://api.refinitiv.com/">API Playground</a> — Interactive Documentation for Refinitiv Data Platform APIs.</p><p><a href="https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis">Refinitiv Data Platform APIs</a> — our existing REST-based interface to the cloud Platform.</p><p><a href="https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis/documentation#ipa-volatility-surfaces-eti">IPA Volatility Surfaces — ETI Documentation <br></a><a href="https://developers.refinitiv.com/en/api-catalog/refinitiv-data-platform/refinitiv-data-platform-apis/documentation#ipa-volatility-surfaces-fx">IPA Volatility Surfaces — FX Documentation</a></p><p><a href="https://community.developers.refinitiv.com/spaces/231/index.html"><strong>Q&amp;A Forum</strong> for the Refinitiv Data Platform APIs</a></p><p><em>Originally published at </em><a href="https://developers.refinitiv.com/article/instrument-pricing-analytics-volatility-surfaces-and-curves"><em>https://developers.refinitiv.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b70b01cd277" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lseg-developer-community/instrument-pricing-analytics-volatility-surfaces-and-curves-developer-community-8b70b01cd277">Instrument Pricing Analytics — Volatility Surfaces and Curves</a> was originally published in <a href="https://medium.com/lseg-developer-community">LSEG Developer Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Newbie challenges with Matplotlib]]></title>
            <link>https://medium.com/lseg-developer-community/my-newbie-challenges-with-matplotlib-4d7ae04fcef9?source=rss-b172232f4cfa------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d7ae04fcef9</guid>
            <category><![CDATA[technical-analysis]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[risk]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Umer Nalla]]></dc:creator>
            <pubDate>Thu, 16 Apr 2020 14:54:24 GMT</pubDate>
            <atom:updated>2021-05-10T09:25:39.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*qY2ReGyvp9kirvKbY2SBxQ.png" /></figure><p>In this article I would like to share the challenges I faced (and the solutions!) as a Python newbie using Matplotlib in anger for the first time…</p><p>Recently I was tasked with developing a Python-based workflow as well as an article for my employer. The workflow involved generating some Technical Analysis related charts and the article involved plotting some Volatility Surfaces and various Curves.</p><p>As someone quite new to Python and never really used Matplotlib previously, this presented quite a challenge.</p><p>Sure I had read a few articles/tutorials on Matplotlib — but quite often these were very ‘atomic’ — each focusing on individual bits of functionality but not how you could combine multiple features into one presentable chart. Or they used different approaches/interfaces to achieve a similar end objective — making it harder to combine the snips of code. And none of these covered all the different features I wanted to apply — so I had to glean hints and guidance from multiple sources — just to make one chart look pretty.</p><p>Each chart I had to create presented a slightly different challenge — which meant more googling and more testing out snippets. So, I promised myself to document all the challenges and solutions to help others in a similar situation — and this article is the result of that promise. I hope you find it interesting as well as useful….</p><h3><strong>Aesthetics First</strong></h3><p>Believe it or not, most of my challenges were around the aesthetics of my charts. For my Technical Analysis workflow, I needed to replicate some charts that are available in my employer’s desktop Eikon/Workspace application and they look much better than the ‘<em>black axes on white background</em>’ stuff that Matplotlib generates by default.</p><p>The Eikon/Workspace applications generate some very contemporary looking charts with black/charcoal backgrounds and contrasting colour line plots:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HpFOjo-dx7hZhUgG7skp_A.png" /></figure><p>Now, clearly, I was not going to be able to replicate the hours of work and polish that had gone into those — but I did want to replicate the look to some degree at least. So, the first challenge was to make the default Matplotlib stuff look something like the above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*U_4yWWzOk4qVRgDh995q5A.png" /><figcaption>Simple Moving Averages — the default Matplotlib look</figcaption></figure><p>The above was generated using the following code:</p><pre>x = close.index<br>plt.plot(x,close, label=&#39;Close&#39;)<br>plt.plot(x,sma14,label=&quot;SMA 14&quot;)<br>plt.plot(x,sma200,label=&quot;SMA 200&quot;)<br>plt.show()</pre><p>Where <em>close</em> is my Closing Price data and <em>sma14</em> and <em>sma200</em> represent my short and long period Moving Averages data.</p><p>A few immediately obvious things that needed fixing:</p><ul><li>Change the background and foreground colours</li><li>Make the chart bigger</li><li>Label my line plots</li><li>Title the chart</li></ul><p>I assumed I would be able to call something like the following to change the background colour — but it seems it is not that simple..</p><pre>plt.set_facecolor(&#39;black&#39;)</pre><p>Instead, I had to do set the figure and axes colours individually (where ‘0.25’ is a grey shade I quite liked):</p><pre>plt.rcParams[&quot;figure.facecolor&quot;] = &#39;0.25&#39;<br>plt.rcParams[&quot;axes.facecolor&quot;] = &#39;0.25&#39;</pre><p>I then found that I needed to access the <em>figure</em> and the <em>axes </em>individually using the <em>subplots</em> call (in order to change colour of tick markers). In doing so I discovered I could roll the <em>figsize</em> and <em>facecolor</em> into the same <em>subplots</em> access call - saving a couple of lines of code:</p><pre>x = close.index<br>fig, ax = plt.subplots(facecolor=&#39;0.25&#39;,figsize=(28,8))<br>ax.set_facecolor(&#39;0.25&#39;)</pre><pre>ax.plot(x,close, label=&#39;Close&#39;,color=&#39;y&#39;)<br>ax.plot(x,sma14,label=&quot;SMA 14&quot;, color=&#39;g&#39;)<br>ax.plot(x,sma200,label=&quot;SMA 200&quot;,color=&#39;tab:purple&#39;)</pre><pre>ax.tick_params(axis=&#39;both&#39;, colors=&#39;w&#39;, labelsize=20)<br>plt.ylabel(&#39;Close&#39;,color=&#39;y&#39;)<br>plt.legend(loc=&#39;upper center&#39;,fontsize=&#39;x-large&#39;)<br>plt.title(f&quot;Simple Moving Average : {ric}&quot;,color=&#39;w&#39;)<br>plt.show()</pre><p>The <em>plt.subplots()</em> call returns the enclosing figure (container) and the axes so I can interact with each individually — and whilst doing so I was able to set the size and colour of the figure.</p><p>In addition, I did the following</p><ul><li>call <em>ax.set_facecolor()</em> to set the axes (plot area) colour</li><li>colour each line plot by adding the ‘<em>color</em>’ parameter where y=yellow, g=green and ‘tab:purple’ (which is from the Tableau palette)</li><li><em>ax.tick_params()</em> to change the colour of the tick values on both axes from the default black to a more legible white, and make the font a bit bigger</li><li><em>plt.legend()</em> to show the actual line plot labels in a nice little panel</li><li><em>plt.title()</em> for the chart title</li></ul><p>All that brought me much closer to the prettier chart I was looking for:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDA4YdFYCi3V-QafICL6ng.png" /><figcaption>My improved look Simple Moving Averages chart</figcaption></figure><p>At this point, I had been testing with a <strong>daily</strong> data interval and was thinking things were looking pretty good. I then tested with an <strong>hourly</strong> data interval and was not impressed with what I saw:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2kr2TbpIdGSPY9d9wvY1A.png" /><figcaption>The uneven, spiky plot when using hourly interval data</figcaption></figure><p>I soon realised this was because I was missing periods of hourly data for the weekend — resulting in the spikes. So, I needed to smooth out the plot and remove the periods with no data.</p><p>Much googling later I worked out that I could use the <em>numpy.arange</em> function to produce some evenly spaced data — which worked well , but my x-axis no longer showed the date. So I added the following custom <em>Formatter </em>to restore the dates to the x-axis.</p><pre>class MyFormatter(Formatter):<br>    def __init__(self, dates, fmt=&#39;%Y-%m-%d&#39;):<br>        self.dates = dates<br>        self.fmt = fmt</pre><pre>def __call__(self, x, pos=0):<br>        &#39;return date x at position pos&#39;<br>        ind = int(round(x))<br>        if ind&gt;=len(self.dates) or ind&lt;0: return &#39;&#39;<br>        return self.dates[ind].strftime(self.fmt)</pre><p>I then reference <em>MyFormatter </em>as part my final plot code as follows:</p><pre>x = close.index<br>fig, ax = plt.subplots(facecolor=&#39;0.25&#39;,figsize=(28,8))<br>ax.set_facecolor(&#39;0.25&#39;)<br>formatter = MyFormatter(x)<br>ax.xaxis.set_major_formatter(formatter)<br>ax.plot(np.arange(len(x)),close, label=&#39;Close&#39;,color=&#39;y&#39;)<br>ax.plot(np.arange(len(x)),sma14,label=&quot;SMA 14&quot;, color=&#39;g&#39;)<br>ax.plot(np.arange(len(x)),sma200,label=&quot;SMA 200&quot;, color=&#39;tab:purple&#39;)<br>ax.tick_params(axis=&#39;both&#39;, colors=&#39;w&#39;, labelsize=20)<br>fig.autofmt_xdate()<br>plt.ylabel(&#39;Close&#39;,color=&#39;y&#39;)<br>plt.legend(loc=&#39;upper center&#39;,fontsize=&#39;x-large&#39;)<br>plt.title(f&quot;Simple Moving Average : {ric}&quot;,color=&#39;w&#39;)<br>plt.show()</pre><p>I also added the <em>fig.autofmat_xdate()</em> to rotate the x-axis labels and avoid overlap. The final result being a much smoother plot with evenly spaced date labels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6R_RuXkwptCs2GRicaMrUw.png" /><figcaption>Hourly chart with smoothed out plot and evenly spaced x-axis date labels</figcaption></figure><h3>Stacked Charts</h3><p>For the Simple Moving averages chart, it made sense to show the Closing price line on the same plot as the short and long Moving Average lines — to contrast the Moving Averages with the Close price.</p><p>However, for my next two charts, this would not be ideal — I really need to show the lines as separate plots — albeit sharing the same x-axis. In other words, I wanted to ‘stack’ the two charts on top of each other.</p><p>First, I tried to create two charts and position them on top of each other — but the gap between the charts was too large and the x-axis was repeated unnecessarily.</p><p>I then came across the GridSpec class which allows the user to ‘Specify the geometry of the grid where a subplot will be placed ‘— sounded perfect!</p><p>Using GridSpec I created a grid of 2 rows and a single column and then added a subplot to each row. I then plotted my Closing Price chart in the first row and my other chart in the 2nd one:</p><pre># Create a 2(rows) x 1(col) Grid<br>gs1 = gridspec.GridSpec(2, 1)</pre><pre># Closing price chart at row 0<br>axc = fig.add_subplot(gs1[0])<br>axc.plot(np.arange(len(close.index)), close)</pre><pre># RSI chart at row 1<br>axr = fig.add_subplot(gs1[1])<br>axr.plot(np.arange(len(rsi.index)), rsi.values,color=&#39;b&#39;)</pre><pre># minimise the gap between the rows<br>gs1.update(wspace=0.025, hspace=0.0)</pre><pre>plt.show()</pre><p>Once I added in the additional stuff for labels, tick params, axis formatting etc I ended up with the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g4_ThBiMsg2ymws605G5Zg.png" /><figcaption>Close price ‘stacked’ on top of the RSI chart</figcaption></figure><p>Note the dashed ‘RSI threshold’ lines at 70 and 30 — which I added with the following code:</p><pre>plt.axhline(y=70, color=&#39;w&#39;,linestyle=&#39;--&#39;)<br>plt.axhline(y=30, color=&#39;w&#39;,linestyle=&#39;--&#39;)</pre><p>I then used all the above techniques to create a Stochastic chart that you can see below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v44Gw0aX7Gc63Oj66rl4JA.png" /><figcaption>‘Stacked’ charts showing Closed Price and Stochastic ‘slowk’ and ‘slowd’ lines</figcaption></figure><p>I have not included the full code for the above charts here to keep the article as short as possible, so I will provide a link to the full source at the end.</p><h3>Volatility Surfaces and Curves</h3><p>My 2nd piece of work required me to include some Volatility Surfaces and a few Curves in the article I was writing. Somebody else has already created some basic plots of the types I needed — however, I did not want the default Matplotlib look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*-pUyugeZtco9g-mgCeIPnQ.png" /><figcaption>Volatility Surface with the default Matplotlib look</figcaption></figure><p>I didn’t like the colours, the position of the axes labels nor the Y-axis tick labels. I already knew how to do the colours which just left the tick labels and axes label positioning.</p><p>So, why were the Y-axis of ‘<em>time to expiry</em>’ ticks labelled with numeric values? Because, for this plot type, the Matplotlib library requires the date to be expressed in ‘<em>number of days since UTC’ — </em>e.g. 737600 =<em> </em>25 June 2020.</p><p>I initially tried to find a way of passing in the date in two formats, one for the tick labels and one for the plot — when calling the plot function. However, I soon realised I could just use a custom <em>Formatter </em>again:</p><pre># Convert float date back to Y-m-d for the y axis tick labels<br>def format_date(x, pos=None):<br>    import matplotlib.dates as dates</pre><pre>    return dates.num2date(x).strftime(&#39;%Y-%m-%d&#39;) </pre><p>And the axes label spacing/position could be improved via the <em>labelpad</em> attribute. So, the following code snippet:</p><pre>ax = plt.axes(projection=&#39;3d&#39;)<br>ax.set_facecolor(&#39;0.25&#39;)<br>ax.set_title(&#39;Vol Surface for : VW&#39;,color=&#39;w&#39;)<br>ax.set_xlabel(&#39;Moneyness&#39;,color=&#39;y&#39;,labelpad=10)<br>ax.set_ylabel(&#39;Expiry&#39;,color=&#39;y&#39;,labelpad=15)<br>ax.set_zlabel(&#39;Volatilities&#39;,color=&#39;y&#39;)<br>ax.tick_params(axis=&#39;both&#39;, colors=&#39;w&#39;)</pre><pre>ax.w_yaxis.set_major_formatter(ticker.FuncFormatter(format_date))<br>       <br>surf = ax.plot_surface(X,Y,Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)</pre><pre>plt.show()</pre><p>produces the following — which I hope you will agree, looks more appealing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*PNrs8_ET4_jR02XEO94Dfg.png" /><figcaption>Improved Volatility Surface with dates for Y-axis ticks and neater axes labels</figcaption></figure><h4>A bit of a cheat!</h4><p>This final one, I have to admit is a bit of a cheat— there is probably a correct way of doing it — but my ‘<em>fix</em>’ worked!</p><p>I had to plot a chart with data for three instruments over a given period. Should be simple enough — but for some reason, the chart looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67JfwbEAr4OTYznebtUZ6Q.png" /><figcaption>A slightly off looking Term Structure chart for GBP, EUR and CHF</figcaption></figure><p>After a bit of digging, it turned out that the GBP data had an extra data point for 2022 (which the EUR and CHF data did not). However, because I was plotting the EUR data before the GBP data, Matplotlib created the mess you see above.</p><p>So, how did I ‘<em>fix’ </em>this? I just plotted the GBP data first — giving me the following neater output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zVm_rKE0H5YVWJmONQAhJg.png" /><figcaption>My ‘fixed’ Term Structure chart (colours have been swapped GBP is now Blue)</figcaption></figure><p>The takeaway from this is that the sequence of a multi-line plot does seem to matter when dealing with non-identical x-axis values. I suppose that if each of the currencies had different dates, I would have to pad/fill the dates out somehow.</p><h4>Closing words</h4><p>I did have several other issues around creating and formatting these charts — but these were more to do with the data format not being quite how I needed/wanted it to be — rather than Matplotlib issues.</p><p>So, thanks for reading and I hope you found it interesting if not entirely useful!</p><p><strong>Full Source code:<br></strong>As promised, here are the links for the full source code behind the snippets I used above. You will need various licences/accounts to run them — however, I am hopeful that you can lift the relevant charting snippets and re-use them with your data.</p><ul><li><a href="https://github.com/Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves">Refinitiv-API-Samples/Article.RDPLibrary.Python.VolatilitySurfaces_Curves</a></li><li><a href="https://github.com/Refinitiv-API-Samples/Workflow.EikonAPI.Python.TechnicalAnalysis">Refinitiv-API-Samples/Workflow.EikonAPI.Python.TechnicalAnalysis</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d7ae04fcef9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lseg-developer-community/my-newbie-challenges-with-matplotlib-4d7ae04fcef9">My Newbie challenges with Matplotlib</a> was originally published in <a href="https://medium.com/lseg-developer-community">LSEG Developer Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>