<?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 Gustave Ilunga  on Medium]]></title>
        <description><![CDATA[Stories by Gustave Ilunga  on Medium]]></description>
        <link>https://medium.com/@ilunga.gus?source=rss-7a94ae578149------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bnJAmjCu7ASUoRVfSsgtQQ.jpeg</url>
            <title>Stories by Gustave Ilunga  on Medium</title>
            <link>https://medium.com/@ilunga.gus?source=rss-7a94ae578149------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:42:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ilunga.gus/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[Building a Saxo Bank Portfolio Analytics Tool with Python and Saxo OpenAPI — Conclusion]]></title>
            <link>https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-conclusion-0e4d67c4be24?source=rss-7a94ae578149------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e4d67c4be24</guid>
            <dc:creator><![CDATA[Gustave Ilunga ]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 19:46:34 GMT</pubDate>
            <atom:updated>2026-10-14T19:46:34.786Z</atom:updated>
            <content:encoded><![CDATA[<h4>Conclusion and way forward</h4><p>This article is the conclusion of the series “Building a Saxo Bank Portfolio Analytics Tool with Python and Saxo OpenAPI”. The series contains the following article:</p><ul><li><a href="https://medium.com/@ilunga.gus/how-to-build-a-saxobank-portfolio-analytics-with-python-part-1-why-this-project-d4650c52d2a5">Part 1: Why this project?</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxobank-portfolio-analytics-with-python-part-2-1e4c25adea34">Part 2: Setting up an account on the Saxo Developer Portal</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxobank-portfolio-analytics-with-python-part-3-95dfe8f86931">Part 3: Authenticating with Saxo OpenAPI</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-part-4-358284ea8a2e?sharedUserId=ilunga.gus">Part 4: Retrieving portfolio composition</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-part-5-40f39eb8b2bb?sharedUserId=ilunga.gus">Part 5: Analysing Sector and Geographic Exposure</a></li><li><strong>Conclusion</strong></li></ul><p>The purpose of this project was to analyse the sectoral and geographical allocation of my Saxo Bank portfolio. The idea came after realising that the Saxo platform offered limited insight into portfolio exposure, particularly when it comes to ETFs.</p><p>I hope this project was helpful in some way, whether as a practical example of portfolio analysis or as inspiration for your own Python projects. Don’t hesitate to share your thoughts, questions, or suggestions in the comments.</p><p><a href="https://github.com/g-ilunga/saxo_bank_portfolio_analysis/tree/main"><strong>The complete project is available in this GitHub repository</strong></a><strong>.</strong></p><p>Stay tuned so you don’t miss the upcoming projects and articles. And if you found this project useful, you can support my work on <a href="https://buymeacoffee.com/gustave"><strong>Buy Me a Coffee</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e4d67c4be24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Saxo Bank Portfolio Analytics Tool with Python and Saxo OpenAPI — Part 5]]></title>
            <link>https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-part-5-40f39eb8b2bb?source=rss-7a94ae578149------2</link>
            <guid isPermaLink="false">https://medium.com/p/40f39eb8b2bb</guid>
            <dc:creator><![CDATA[Gustave Ilunga ]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 18:31:47 GMT</pubDate>
            <atom:updated>2026-10-21T19:15:43.771Z</atom:updated>
            <content:encoded><![CDATA[<h4>Analysing Sector and Geographic Exposure</h4><p>This article is the part 5 of the series “Building a Saxo Bank Portfolio Analytics Tool with Python and Saxo OpenAPI”. The series contains the following article:</p><ul><li><a href="https://medium.com/@ilunga.gus/how-to-build-a-saxobank-portfolio-analytics-with-python-part-1-why-this-project-d4650c52d2a5">Part 1: Why this project?</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxobank-portfolio-analytics-with-python-part-2-1e4c25adea34">Part 2: Setting up an account on the Saxo Developer Portal</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxobank-portfolio-analytics-with-python-part-3-95dfe8f86931">Part 3: Authenticating with Saxo OpenAPI</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-part-4-358284ea8a2e?sharedUserId=ilunga.gus">Part 4: Retrieving portfolio composition</a></li><li><strong>Part 5: Analysing Sector and Geographic Exposure</strong></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-conclusion-0e4d67c4be24?sharedUserId=ilunga.gus">Conclusion</a></li></ul><p>In the previous article, I presented the steps to retrieve the portfolio composition. This article gets to the core of the project: assessing the geographic and sectoral exposure of the portfolio. As my SaxoBank portfolio is made of ETFs, I developped this script for an ETF based porfolio. But it can be adapted to portfolio that also contains individual stocks.</p><h3>Step 1: Retrieval of geographic and sectoral allocation of individual ETFs</h3><p>One popular website that provides that information is justetf.com. Unfortunately, the website does not have an API that can be exploited. I tried some Python libraries that scrap justetf.com but they did not fully respond to my needs. On the other hand, some websites do have exploitable API but they are only accessible behind a paywall.</p><p>As a result, I decided to build my own database. To achieve that, I retrieved the ETF information from the respective ETF issuer. I saved these informations in .json files that I named: <strong><em>sector_allocation.json</em></strong> and <strong><em>geographic_exposure.json</em></strong></p><h3>Step 2: Creating a spreadsheet that contains the name of world countries and their respective continent</h3><p>In my script I also wanted to determine the weight of each continent (as part of the geographic allocation) in my portfolio. As a result, I created a spreadsheet that contains the name of world countries and their respective continents. I named that file <strong><em>countries.xlsx</em></strong>. I insured that the names spellings are identical to those in my <strong><em>geographic_exposure.json</em></strong>. Below is a screenshot of the spreadsheet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*SsQh4opKHRiGruzULjaMBQ.png" /><figcaption>Screenshot of the spreadsheet</figcaption></figure><h3>Step 3: Completing the existing main.py file</h3><p>As with previous articles, the file is further enriched. Here the file is completed with codes that first compute the geographic and sectoral allocation; then produce a basic visualisation graph.</p><pre>#========================================================================================<br># LIBRARIES<br>#========================================================================================<br>import json<br>import urllib.parse<br>import webbrowser<br>import requests<br>import pandas as pd<br>import plotly.express as px<br><br># Importing local modules that were created for authentication (&quot;functions.&quot; is the folder where the modules are located)<br>from authentication_functions import build_saxo_login_url, exchange_code_for_tokens<br>from accessing_portfolio_functions import retrieving_keys, getting_open_positions<br><br>#========================================================================================<br># LOADING NECESSARY FILES<br>#========================================================================================<br><br># Loading the info related to the liveapp created on Saxo developer portal<br>with open(&#39;./configuration/app_details.json&#39;, &#39;r&#39;) as f: # This is the json file where the liveApp info were stored<br>    configuration = json.load(f)<br><br>app_key = configuration[&quot;app_key&quot;] <br>authorization_endpoint = configuration[&quot;authorization_endpoint&quot;]<br>token_endpoint = configuration[&quot;token_endpoint&quot;]<br>app_secret = configuration[&quot;app_secrets1&quot;] # Saxo provides 2 App Secrets. You can use either one.<br>redirect_url = configuration[&quot;redirect_url&quot;]<br>scopes = configuration[&quot;scopes&quot;]<br><br>&quot;&quot;&quot;<br>Notes:<br>===========================<br>The &quot;scopes&quot; parameter is not part of the liveapp info on Saxo Developer Portal. <br>I included it in my configuration file to specify that I want my app to have the permission &quot;read&quot; and &quot;offline_access&quot;<br>&quot;&quot;&quot;<br><br># Spreadsheet with ISIN information<br>isin_database = pd.read_excel(&quot;./etf_data/isin_database.xlsx&quot;)<br><br># Importing the spreadsheet containing world countries and their respective continents<br>df_world_countries = pd.read_excel(&quot;./etf_data/countries.xlsx&quot;)<br><br># Loading the file containing the geographic distribution of each etf and building a table out of it<br>with open(&#39;./etf_data/geographic_exposure.json&#39;, &#39;r&#39;) as f: <br>    geography = json.load(f) <br><br>list_geography = []<br>for etf_isin in geography:<br>    etf_geography = list(geography[etf_isin][0].keys())<br>    list_geography.extend(etf_geography)<br><br>list_geography_final = list(set(list_geography)) # Removing duplicate<br>df_geography = pd.DataFrame(list_geography_final, columns=[&quot;Countries&quot;])<br><br><br># Loading the file containing the sector distribution of each etf and building a table out of it<br>with open(&#39;./etf_data/sector_allocation.json&#39;, &#39;r&#39;) as f: <br>    sector = json.load(f)<br><br>list_sector = []<br>for etf_isin in sector:<br>    etf_sector = list(sector[etf_isin][0].keys())<br>    list_sector.extend(etf_sector)<br><br>list_sector_final = list(set(list_sector)) # Removing duplicate<br>df_sector = pd.DataFrame(list_sector_final, columns=[&quot;Sectors&quot;])<br><br>#==========================================================================================<br># 1. AUTHENTICATING<br>#==========================================================================================<br><br># Retrieving the authorisation code<br>login_url = build_saxo_login_url(https://medium.com/app_key,%20authorization_endpoint,%20redirect_url,%20scopes) # Constructing the url that will be used to log in to your Saxo account<br>webbrowser.open(login_url) # Opening the url to enter the Saxo account credential<br><br># Extracting the authorisation code from  the redirect url<br>auth_url = str(input(&quot;Paste the redirect url here: &quot;)) # Prompting the user to paste the redirect url<br>parsed = urllib.parse.urlparse(auth_url)<br>params = urllib.parse.parse_qs(parsed.query)<br>auth_code = params.get(&quot;code&quot;, [None])[0]<br><br># Retrieving the access token using the authorisation code<br>tokens = exchange_code_for_tokens(token_endpoint, app_key, app_secret, redirect_url, auth_code)<br>access_token = tokens[&quot;access_token&quot;]<br>refresh_token = tokens.get(&quot;refresh_token&quot;) # In case Saxo doesn&#39;t return a refresh token, the program will not crash<br>token_expiration = tokens[&quot;expires_in&quot;]<br><br>print (&quot;Access token succesfully retrieved.&quot;)<br><br># Retrieving client key and account key<br>keys = retrieving_keys(access_token, app_key)<br>client_key = keys[0][&quot;client_key&quot;]<br>account_key = keys[1]<br><br>#==================================================================================================<br># 2. GETTING OPEN POSITIONS IN A GIVEN ACCOUNT<br>#==================================================================================================<br><br># Selecting the desired account. I hardcoded two options since my Saxo portfolio has 2 accounts<br>option1 = list(account_key.keys())[0] # Returns the name of the fist account<br>option2 = list(account_key.keys())[1] # Returns the name of the second account<br><br>while True:<br>    account_selection = int(input(f&quot;Enter 1 for {option1} or 2 for {option2}: &quot;))<br>    <br>    if account_selection == 1:<br>        print (f&quot;You selected {option1}&quot;)<br>        account_key = account_key[option1]<br>        break<br><br>    elif account_selection == 2:<br>        print(f&quot;You selected {option2}&quot;)<br>        account_key = account_key[option2]<br>        break<br><br>    else:<br>        print(&quot;Invalid choice. Please enter 1 or 2.&quot;)<br><br># Getting open position<br>positions = getting_open_positions(account_key, client_key, access_token, app_key)<br>positions[&quot;ISIN&quot;] = positions[&quot;Symbol&quot;].map(isin_database.set_index(&quot;Symbol&quot;)[&quot;ISIN&quot;]) # Retrieving ISIN from our database<br><br><br>#==============================================================<br># 3. COMPUTING GEOGRAPHY AND SECTOR ALLOCATION<br>#==============================================================<br><br>positions[&quot;Proportion in %&quot;] = (positions[&quot;Invested_amount&quot;] / positions[&quot;Invested_amount&quot;].sum() * 100).round(1) # Proportion of each etf in the portfolio<br><br># Extracting sectoral allocation of each etf<br>for etf_isin in list(positions[&quot;ISIN&quot;]):<br>    df = pd.DataFrame(list(sector[etf_isin][0].items()), columns=[&quot;Sectors&quot;, &quot;Allocation in ETF&quot;]) #Turn the dictionnary of etf composition into table<br>    proportion = positions.loc[positions[&quot;ISIN&quot;] == etf_isin, &quot;Proportion in %&quot;].iloc[0] # proportion in % of each etf<br>    df[etf_isin] = (df[&quot;Allocation in ETF&quot;] * proportion/100).round(1) # Find the actual allocation using the proportion the etf occupies in the porfolio<br>    df = df.drop(columns=&quot;Allocation in ETF&quot;)<br>    df_sector = df_sector.merge(df, on=&quot;Sectors&quot;, how=&quot;left&quot;)<br>    df_sector = df_sector.fillna(0)<br>df_sector[&quot;Total&quot;] = df_sector.select_dtypes(include=&quot;number&quot;).sum(axis=1)<br>df_sector_final = df_sector[[&quot;Sectors&quot;, &quot;Total&quot;]]<br><br># Extracting geography allocation of each etf<br>for etf_isin in list(positions[&quot;ISIN&quot;]):<br>    df = pd.DataFrame(list(geography[etf_isin][0].items()), columns=[&quot;Countries&quot;, &quot;Allocation in ETF&quot;]) #Turn the dictionnary into table<br>    proportion = positions.loc[positions[&quot;ISIN&quot;] == etf_isin, &quot;Proportion in %&quot;].iloc[0] # proportion in % of each etf<br>    df[etf_isin] = (df[&quot;Allocation in ETF&quot;] * proportion/100).round(1) # Find the actual allocation using the proportion the etf occupies in the porfolio<br>    df = df.drop(columns=&quot;Allocation in ETF&quot;)<br>    df_geography = df_geography.merge(df, on=&quot;Countries&quot;, how=&quot;left&quot;)<br>    df_geography = df_geography.fillna(0)<br>df_geography[&quot;Total&quot;] = df_geography.select_dtypes(include=&quot;number&quot;).sum(axis=1)<br>df_geography_final = df_geography[[&quot;Countries&quot;,&quot;Total&quot;]]<br>df_geography_final = df_geography_final[df_geography_final[&quot;Countries&quot;] != &quot;Precious metal&quot;] # Removing precious metal from the list of countries<br><br># Adding the continents on the dataframe for easier analysis<br>df_geography_final = df_geography_final.merge(df_world_countries[[&quot;Countries&quot;, &quot;Continent&quot;]],<br>                                              on=&quot;Countries&quot;, how=&quot;left&quot;, validate=&quot;many_to_one&quot;)<br><br>#=====================================================================================================<br># 4. PLOTTING THE ALLOCATION<br>#=====================================================================================================<br><br># Plotting the geographic allocation<br>#--------------------------------------------<br><br># Aggregate values by continent<br>pie_data = (df_geography_final.groupby(&quot;Continent&quot;, as_index=False)[&quot;Total&quot;].sum())<br><br># Create the pie chart<br>fig = px.pie(<br>    pie_data,<br>    names=&quot;Continent&quot;,<br>    values=&quot;Total&quot;,<br>    title=&quot;Geographic allocation in percentage&quot;,<br>    hole=0 <br>)<br><br># Configure labels shown inside/on hover<br>fig.update_traces(<br>    textposition=&quot;inside&quot;,<br>    textinfo=&quot;value+label&quot;,<br>    hovertemplate=(<br>        &quot;&lt;b&gt;%{label}&lt;/b&gt;&lt;br&gt;&quot;<br>        &quot;Proportion: %{value:,.0f}%&lt;br&gt;&quot;<br>        &quot;&lt;extra&gt;&lt;/extra&gt;&quot;<br>    )<br>)<br><br>fig.update_layout(template=&quot;plotly_white&quot;)<br><br>fig.show()<br><br># Plotting the sector allocation<br>#--------------------------------------------<br><br>pie_data = df_sector_final<br><br># Create the pie chart<br>fig = px.pie(<br>    pie_data,<br>    names=&quot;Sectors&quot;,<br>    values=&quot;Total&quot;,<br>    title=&quot;Sector allocation in percentage&quot;,<br>    hole=0 <br>)<br><br># Configure labels shown inside/on hover<br>fig.update_traces(<br>    textposition=&quot;inside&quot;,<br>    textinfo=&quot;value+label&quot;,<br>    hovertemplate=(<br>        &quot;&lt;b&gt;%{label}&lt;/b&gt;&lt;br&gt;&quot;<br>        &quot;Proportion: %{value:,.0f}%&lt;br&gt;&quot;<br>        &quot;&lt;extra&gt;&lt;/extra&gt;&quot;<br>    )<br>)<br><br>fig.update_layout(template=&quot;plotly_white&quot;)<br><br>fig.show()</pre><h3>What’s next?</h3><p>This was the last building block of the portfolio analytics tool. The next article is the conclusion.</p><p>Stay tuned so you don’t miss the upcoming articles.</p><p>If you find this project useful, you can support my work on <strong>B</strong><a href="https://buymeacoffee.com/gustave"><strong>uy Me a Coffee</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40f39eb8b2bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Saxo Bank Portfolio Analytics Tool with Python and Saxo OpenAPI — Part 4]]></title>
            <link>https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-part-4-358284ea8a2e?source=rss-7a94ae578149------2</link>
            <guid isPermaLink="false">https://medium.com/p/358284ea8a2e</guid>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[saxo-openapi]]></category>
            <category><![CDATA[saxo]]></category>
            <dc:creator><![CDATA[Gustave Ilunga ]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 20:56:58 GMT</pubDate>
            <atom:updated>2026-10-20T19:52:12.070Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 4: Retrieving portfolio composition</h4><p>This is the 4th articles of the series “Building a Saxo Bank Portfolio Analytics Tool with Python and Saxo OpenAPI”. The series contains the following article:</p><ul><li><a href="https://medium.com/@ilunga.gus/how-to-build-a-saxobank-portfolio-analytics-with-python-part-1-why-this-project-d4650c52d2a5">Part 1: Why this project?</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxobank-portfolio-analytics-with-python-part-2-1e4c25adea34">Part 2: Setting up an account on the Saxo Developer Portal</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxobank-portfolio-analytics-with-python-part-3-95dfe8f86931">Part 3: Authenticating with Saxo OpenAPI</a></li><li><strong>Part 4: Retrieving portfolio composition</strong></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-part-5-40f39eb8b2bb?sharedUserId=ilunga.gus">Part 5: Analysing Sector and Geographic Exposure</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-conclusion-0e4d67c4be24?sharedUserId=ilunga.gus">Conclusion</a></li></ul><p>In this article, I show how to retrieve the composition of the portfolio. Before moving forward, it is essential to clarify some vocabulary to align with Saxo OpenAPI terminology:</p><ul><li>Customer area: refers to the SaxoInvestor or SaxoTrader account.</li><li>Account: refers to the investment account(s) available in the customer area.</li><li>Open positions: refer to the investment instruments currently held in the account (i.e., positions that are still open).</li></ul><h3>Step 1: Creating our ISIN database</h3><p>Due to licensing restrictions, Saxo does not provide ISIN identifiers through its OpenAPI. Further details are available on their dedicated page: <a href="https://openapi.help.saxo/hc/en-us/articles/4416972708625-Can-I-retrieve-ISINs-through-the-OpenAPI.">https://openapi.help.saxo/hc/en-us/articles/4416972708625-Can-I-retrieve-ISINs-through-the-OpenAPI.</a></p><p>As a result, ISINs are not included when retrieving portfolio composition via the API. To address this limitation, I created my own ISIN reference database.</p><p>ISINs for open positions held in the portfolio can be manually retrieved from the SaxoInvestor or SaxoTrader platforms. I stored these identifiers in an Excel file named <strong><em>isin_database.xlsx</em></strong>, following the structure illustrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*gw3LuHQhjpn1_6dkSlxEhg.png" /><figcaption>Structure of the ISIN database</figcaption></figure><h3>Step 2 : Creating a script that will only contain the reusable functions needed for the portfolio retrieval workflow</h3><p>This script is saved in .py file that I will call<em> </em><strong><em>accessing_portfolio_function.py</em></strong></p><pre>#========================================================================================<br># LIBRARIES<br>#========================================================================================<br>import json<br>import requests<br>import pandas as pd<br><br>#===========================================================================<br># RETRIEVING CLIENT KEY AND ACCOUNTS KEYS<br>#===========================================================================<br><br>def retrieving_keys(access_token, app_key):<br>    <br>    # API calls<br>    #--------------------------------------------------------------------------------<br>    accounts_endpoint = &quot;https://gateway.saxobank.com/openapi/port/v1/accounts/me&quot;<br>    headers = {<br>        &quot;Authorization&quot;: f&quot;Bearer {access_token}&quot;,<br>        &quot;X-OpenAPI-AppKey&quot;: app_key<br>    }<br>    response = requests.get(accounts_endpoint, headers=headers)<br><br>    # Retrieving client key<br>    #--------------------------------------------------<br>    client_key = response.json()[&quot;Data&quot;][0][&quot;ClientKey&quot;] # no matter the number of accounts you have, client key is the same. No need to put it in a loop<br>    client_key_dict = {&quot;client_key&quot;: client_key} <br><br>    # Retrieving account display name and keys<br>    #-----------------------------------------------------<br>    account_display_name_list = [] # Names of accounts as they appear on the saxoinvestor or trader platform<br>    account_key_list = []<br>    number_of_accounts = len(response.json()[&quot;Data&quot;])<br><br>    for x in list(range(number_of_accounts)):<br>        account_display_name = response.json()[&quot;Data&quot;][x][&quot;DisplayName&quot;]<br>        account_key = response.json()[&quot;Data&quot;][x][&quot;AccountKey&quot;]<br><br>        account_display_name_list.append(account_display_name)<br>        account_key_list.append(account_key)<br><br>    accounts_details = dict(zip(account_display_name_list, account_key_list))<br><br>    print(&quot;Client keys and account key successfully retrieved.&quot;)<br>    <br>    return client_key_dict, accounts_details<br><br><br>#====================================================<br># GETTING OPEN POSITIONS IN A GIVEN ACCOUNT<br>#====================================================<br><br>def getting_open_positions(account_key, client_key, access_token, app_key):<br><br>    # Retrieving positions UIC, invested amount and asset type<br>    #-----------------------------------------------------------<br>    position_endpoint = f&quot;https://gateway.saxobank.com/openapi/port/v1/netpositions?AccountKey={account_key}&amp;ClientKey={client_key}&quot; # position in a given account. But it doesn&#39;t give names of products<br>    headers = {<br>        &quot;Authorization&quot;: f&quot;Bearer {access_token}&quot;,<br>        &quot;X-OpenAPI-AppKey&quot;: app_key<br>    }<br>    response = requests.get(position_endpoint, headers=headers)<br><br>    number_of_positions = response.json()[&#39;__count&#39;]<br>    uic_list = [] # UIC are unique identifiers that Saxo assigns to each instruments available<br>    asset_type_list = []<br>    invested_amount_list = []<br><br>    for x in list(range(number_of_positions)):<br>        uic = response.json()[&quot;Data&quot;][x][&quot;NetPositionBase&quot;][&quot;Uic&quot;]<br>        asset_type = response.json()[&quot;Data&quot;][x][&quot;NetPositionBase&quot;][&quot;AssetType&quot;]<br>        market_value = response.json()[&quot;Data&quot;][x][&quot;NetPositionView&quot;][&quot;MarketValueOpenInBaseCurrency&quot;]<br>        profit_loss = response.json()[&quot;Data&quot;][x][&quot;NetPositionView&quot;][&quot;ProfitLossOnTradeInBaseCurrency&quot;]<br>        invested_amount = (market_value - profit_loss) * (-1)<br><br>        uic_list.append(uic)<br>        asset_type_list.append(asset_type)<br>        invested_amount_list.append(invested_amount)<br><br>    # Retrieving symbols of open positions to match with our ISIN database<br>    #-----------------------------------------------------------------------<br>    symbol_list = []<br>    asset_name_list = []<br><br>    headers = {<br>        &quot;Authorization&quot;: f&quot;Bearer {access_token}&quot;,<br>        &quot;X-OpenAPI-AppKey&quot;: app_key<br>    }<br><br>    for uic,  asset_type in zip(uic_list, asset_type_list):<br>        instruments_endpoint = f&quot;https://gateway.saxobank.com/openapi/ref/v1/instruments?AccountKey={account_key}&amp;ClientKey={client_key}&amp;Uics={uic}&amp;AssetType={asset_type}&quot; # to retrieve names of products from UIC (universal instruments code)<br><br>        response = requests.get(instruments_endpoint, headers=headers)<br>        symbol = response.json()[&quot;Data&quot;][0][&quot;Symbol&quot;]<br>        symbol_list.append(symbol)<br><br>        asset_name = response.json()[&quot;Data&quot;][0][&quot;Description&quot;]<br>        asset_name_list.append(asset_name)<br><br>    # Creating a dataframe of our open positions<br>    df_positions = pd.DataFrame({<br>        &quot;Name&quot;: asset_name_list,<br>        &quot;UIC&quot;: uic_list,<br>        &quot;Type&quot;: asset_type_list,<br>        &quot;Symbol&quot;: symbol_list,<br>        &quot;Invested_amount&quot;: invested_amount_list<br>    })<br><br>    return df_positions</pre><p>At this level I now have two module files: <strong><em>authentication_function.py </em></strong>(created in the previous article)<strong><em> and accessing_portfolio_function.py </em></strong>(created in this article)</p><h3>Step 3: Completing the existing main.py file</h3><p>The <strong><em>main.py </em></strong>created in the previous article will be further enriched.</p><p>After the authentication process complete, the portfolio composition retrieval process works as follows:</p><ol><li><strong>Retrieving the client key and account key</strong>: These are the keys that will be required in the API endpoint.</li><li><strong>Prompting the user to select which account to access</strong>.</li><li><strong>Retrieving open positions and their associated details</strong> (UIC, invested amount, type, symbol, name).</li><li><strong>Building a final open positions table</strong> by pulling ISIN from our own ISIN database.</li></ol><pre>#========================================================================================<br># LIBRARIES<br>#========================================================================================<br>import json<br>import urllib.parse<br>import webbrowser<br>import requests<br>import pandas as pd<br><br># Importing local modules that were created for authentication (&quot;functions.&quot; is the folder where the modules are located)<br>from authentication_functions import build_saxo_login_url, exchange_code_for_tokens<br>from accessing_portfolio_functions import retrieving_keys, getting_open_positions<br><br>#========================================================================================<br># LOADING NECESSARY FILES<br>#========================================================================================<br><br># Loading the info related to the liveapp created on Saxo developer portal<br>with open(&#39;./configuration/app_details.json&#39;, &#39;r&#39;) as f: # This is the json file where the liveApp info were stored<br>    configuration = json.load(f)<br><br>app_key = configuration[&quot;app_key&quot;] <br>authorization_endpoint = configuration[&quot;authorization_endpoint&quot;]<br>token_endpoint = configuration[&quot;token_endpoint&quot;]<br>app_secret = configuration[&quot;app_secrets1&quot;] # Saxo provides 2 App Secrets. You can use either one.<br>redirect_url = configuration[&quot;redirect_url&quot;]<br>scopes = configuration[&quot;scopes&quot;]<br><br>&quot;&quot;&quot;<br>Notes:<br>===========================<br>The &quot;scopes&quot; parameter is not part of the liveapp info on Saxo Developer Portal. <br>I included it in my configuration file to specify that I want my app to have the permission &quot;read&quot; and &quot;offline_access&quot;<br>&quot;&quot;&quot;<br><br># Spreadsheet with ISIN information<br>isin_database = pd.read_excel(&quot;./etf_data/isin_database.xlsx&quot;)<br><br>#==========================================================================================<br># 1. AUTHENTICATING<br>#==========================================================================================<br><br># Retrieving the authorisation code<br>login_url = build_saxo_login_url(https://medium.com/app_key,%20authorization_endpoint,%20redirect_url,%20scopes) # Constructing the url that will be used to log in to your Saxo account<br>webbrowser.open(login_url) # Opening the url to enter the Saxo account credential<br><br># Extracting the authorisation code from  the redirect url<br>auth_url = str(input(&quot;Paste the redirect url here: &quot;)) # Prompting the user to paste the redirect url<br>parsed = urllib.parse.urlparse(auth_url)<br>params = urllib.parse.parse_qs(parsed.query)<br>auth_code = params.get(&quot;code&quot;, [None])[0]<br><br># Retrieving the access token using the authorisation code<br>tokens = exchange_code_for_tokens(token_endpoint, app_key, app_secret, redirect_url, auth_code)<br>access_token = tokens[&quot;access_token&quot;]<br>refresh_token = tokens.get(&quot;refresh_token&quot;) # In case Saxo doesn&#39;t return a refresh token, the program will not crash<br>token_expiration = tokens[&quot;expires_in&quot;]<br><br>print (&quot;Access token succesfully retrieved.&quot;)<br><br># Retrieving client key and account key<br>keys = retrieving_keys(access_token, app_key)<br>client_key = keys[0][&quot;client_key&quot;]<br>account_key = keys[1]<br><br>#==================================================================================================<br># 2. GETTING OPEN POSITIONS IN A GIVEN ACCOUNT<br>#==================================================================================================<br><br># Selecting the desired account. I hardcoded two options since my Saxo portfolio has 2 accounts<br>option1 = list(account_key.keys())[0] # Returns the name of the fist account<br>option2 = list(account_key.keys())[1] # Returns the name of the second account<br><br>while True:<br>    account_selection = int(input(f&quot;Enter 1 for {option1} or 2 for {option2}: &quot;))<br>    <br>    if account_selection == 1:<br>        print (f&quot;You selected {option1}&quot;)<br>        account_key = account_key[option1]<br>        break<br><br>    elif account_selection == 2:<br>        print(f&quot;You selected {option2}&quot;)<br>        account_key = account_key[option2]<br>        break<br><br>    else:<br>        print(&quot;Invalid choice. Please enter 1 or 2.&quot;)<br><br># Getting open position<br>positions = getting_open_positions(account_key, client_key, access_token, app_key)<br>positions[&quot;ISIN&quot;] = positions[&quot;Symbol&quot;].map(isin_database.set_index(&quot;Symbol&quot;)[&quot;ISIN&quot;]) # Retrieving ISIN from our database</pre><h3>What’s next?</h3><p>Now that we have our portfolio composition, we can move on to one of the most interesting parts: portfolio analytics.</p><p>Stay tuned so you don’t miss the upcoming articles.</p><p>If you find this project useful, you can support my work on <strong>B</strong><a href="https://buymeacoffee.com/gustave"><strong>uy Me a Coffee</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=358284ea8a2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Saxo Bank Portfolio Analytics Tool with Python and Saxo OpenAPI — Part 3]]></title>
            <link>https://medium.com/@ilunga.gus/building-a-saxobank-portfolio-analytics-with-python-part-3-95dfe8f86931?source=rss-7a94ae578149------2</link>
            <guid isPermaLink="false">https://medium.com/p/95dfe8f86931</guid>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[saxo]]></category>
            <category><![CDATA[saxo-openapi]]></category>
            <dc:creator><![CDATA[Gustave Ilunga ]]></dc:creator>
            <pubDate>Wed, 03 Jun 2026 19:20:13 GMT</pubDate>
            <atom:updated>2026-10-20T19:32:43.709Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 3: Authenticating with Saxo OpenAPI</h4><p>This is the third article of the series “Building a Saxo Bank Portfolio Analytics Tool with Python and Saxo OpenAPI”. The series contains the following article:</p><ul><li><a href="https://medium.com/@ilunga.gus/how-to-build-a-saxobank-portfolio-analytics-with-python-part-1-why-this-project-d4650c52d2a5">Part 1: Why this project?</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxobank-portfolio-analytics-with-python-part-2-1e4c25adea34">Part 2: Setting up an account on the Saxo Developer Portal</a></li><li><strong>Part 3: Authenticating with Saxo OpenAPI</strong></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-part-4-358284ea8a2e">Part 4: Retrieving portfolio composition</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-part-5-40f39eb8b2bb?sharedUserId=ilunga.gus">Part 5: Analysing Sector and Geographic Exposure</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-conclusion-0e4d67c4be24?sharedUserId=ilunga.gus">Conclusion</a></li></ul><p>In this article, I dive into the development of the tool by focusing on one essential step: authenticating with the Saxo OpenAPI. Since the tool interacts with Saxo’s services through Python, I must first establish a secure connection to my Saxo account.</p><h3>Step 1 : Storing the live app credentials in a separate file</h3><p>By now I have a fully functioning live app as described in the second article of this series. I stored the live app credentials in a separate file instead of hard‑coding them directly into the script. This keeps the code cleaner, easier to maintain, and reduces the risk of exposing sensitive information.</p><p>The credentials are stored in a file that I will call <strong>“<em>app_details.json</em>” </strong>with the following structure:</p><pre>{<br>   &quot;app_key&quot;: &quot;YOUR APP KEY HERE&quot;,<br>   &quot;authorization_endpoint&quot;: &quot;https://live.logonvalidation.net/authorize&quot;,<br>   &quot;token_endpoint&quot;: &quot;https://live.logonvalidation.net/token&quot;,<br>   &quot;redirect_url&quot;: &quot;http://localhost:8000/callback&quot;,<br>   &quot;app_secrets1&quot;:&quot;YOUR APP SECRET 1 HERE&quot;,<br>   &quot;app_secrets2&quot;:&quot;YOUR APP SECRET 2 HERE&quot;,<br>   &quot;scopes&quot;: [&quot;read&quot;, &quot;offline_access&quot;]<br>}</pre><h3>Step 2: Creating a script that will only contain the reusable functions needed for the authentication workflow</h3><p>This script is saved in .py file that I will call<em> </em><strong><em>authentication_function.py</em></strong></p><pre>&quot;&quot;&quot;<br>This script contains functions developed for the authentication part of the tool<br>&quot;&quot;&quot;<br><br>#===========================================<br># Importing libraries<br>#===========================================<br><br>import urllib.parse<br>import requests<br><br>#==================================================================================<br># Constructing the login url to be used by the user to enter its Saxo credentials<br>#==================================================================================<br><br>def build_saxo_login_url(https://medium.com/app_key,%20authorization_endpoint,%20redirect_url,%20scopes):<br>    <br>    params = {<br>        &quot;response_type&quot;: &quot;code&quot;,<br>        &quot;client_id&quot;: app_key,<br>        &quot;redirect_uri&quot;: redirect_url,<br>        &quot;scope&quot;: &quot;&quot;.join(scopes)<br>    }<br><br>    query_string = urllib.parse.urlencode(params) # It converts a Python dictionary into a properly encoded URL query string.<br>    login_url = f&quot;{authorization_endpoint}?{query_string}&quot;<br>    return login_url<br><br>&quot;&quot;&quot;<br>Note:<br>This function will generate a url. When accessing the url, the user will be prompted to enter its Saxo Investor credentials.<br>Once successfully authenticated, Saxo will provide an authentication code that will be used to obtain an access token to be used to query the investment accounts.<br>&quot;&quot;&quot;<br><br>#=============================================================================================<br># Building a function that will use access code provided by Saxo after logging to get tokens<br>#=============================================================================================<br><br>def exchange_code_for_tokens(token_endpoint, app_key, app_secret, redirect_url, auth_code):<br>    data = {<br>        &quot;grant_type&quot;: &quot;authorization_code&quot;,<br>        &quot;code&quot;: auth_code,<br>        &quot;redirect_uri&quot;: redirect_url,<br>        &quot;client_id&quot;: app_key,<br>        &quot;client_secret&quot;: app_secret<br>    }<br><br>    response = requests.post(token_endpoint, data=data)<br>    response.raise_for_status()<br>    return response.json()<br><br>&quot;&quot;&quot;<br>Note:<br>The function will return:<br>- The access token: to be used to query the investment accounts<br>- The refresh token: since the access token expires after few minutes, Saxo provides this refresh token to avoid redoing the entire authentication process<br>- The validity of the access token. Usually in seconds<br>&quot;&quot;&quot;<br><br>#==============================================<br># Activating the Refresh token<br>#==============================================<br><br>def refresh_access_token(token_endpoint, app_key, app_secret, refresh_token):<br>    data = {<br>        &quot;grant_type&quot;: &quot;refresh_token&quot;,<br>        &quot;refresh_token&quot;: refresh_token,<br>        &quot;client_id&quot;: app_key,<br>        &quot;client_secret&quot;: app_secret<br>    }<br><br>    response = requests.post(token_endpoint, data=data)<br>    response.raise_for_status()<br>    return response.json()</pre><h3>Step 3: Creating the main.py file</h3><p>This is the file that contains the script that I will run to authenticate. I will name it <strong><em>main.py. </em></strong>It will be progressively developed throughout the upcoming articles to form the complete application.</p><p>When I run this script, it initiates Saxo’s OAuth2 login process. Here’s what happens step by step:</p><ol><li><strong>Browser login prompt. </strong>The script automatically opens your default web browser and redirects you to Saxo’s login page. You log in using your Customer ID, and the password you normally use for SaxoInvestor or SaxoTrader.</li><li><strong>Redirect to Local Callback URL. </strong>After a successful login, Saxo redirects you to a URL that looks like: “http://localhost:8000/callback/&lt;AUTHORIZATION_CODE&gt;”. This URL contains the authorization code the script needs.</li><li><strong>Paste the Redirect URL Back Into the Script. </strong>The script will prompt you to paste the full redirect URL. It then extracts the authorization code automatically.</li><li><strong>Exchange Authorization Code for Access Token. </strong>Using the extracted code, the script requests an access token from Saxo’s API. This token is what allows you to make authenticated API calls to your Saxo account.</li><li><strong>Token Storage. </strong>The access token is saved locally as a .json file.<br>This file is what the tool will read from when making future API requests.</li></ol><pre>#========================================================================================<br># LIBRARIES<br>#========================================================================================<br>import json<br>import urllib.parse<br>import webbrowser<br>import requests<br>import pandas as pd<br>import plotly.express as px<br><br># Importing local modules that were created for authentication (&quot;functions.&quot; is the folder where the modules are located)<br>from authentication_functions import build_saxo_login_url, exchange_code_for_tokens<br><br>#========================================================================================<br># LOADING NECESSARY FILES<br>#========================================================================================<br><br># Loading the info related to the liveapp created on Saxo developer portal<br>with open(&#39;app_details.json&#39;, &#39;r&#39;) as f: # This is the json file where the liveApp info were stored<br>    configuration = json.load(f)<br><br>app_key = configuration[&quot;app_key&quot;] <br>authorization_endpoint = configuration[&quot;authorization_endpoint&quot;]<br>token_endpoint = configuration[&quot;token_endpoint&quot;]<br>app_secret = configuration[&quot;app_secrets1&quot;] # Saxo provides 2 App Secrets. You can use either one.<br>redirect_url = configuration[&quot;redirect_url&quot;]<br>scopes = configuration[&quot;scopes&quot;]<br><br>&quot;&quot;&quot;<br>Notes:<br>===========================<br>The &quot;scopes&quot; parameter is not part of the liveapp info on Saxo Developer Portal. <br>I included it in my configuration file to specify that I want my app to have the permission &quot;read&quot; and &quot;offline_access&quot;<br>&quot;&quot;&quot;<br><br>#==========================================================================================<br># 1. AUTHENTICATING<br>#==========================================================================================<br><br># Retrieving the authorisation code<br>login_url = build_saxo_login_url(https://medium.com/app_key,%20authorization_endpoint,%20redirect_url,%20scopes) # Constructing the url that will be used to log in to your Saxo account<br>webbrowser.open(login_url) # Opening the url to enter the Saxo account credential<br><br># Extracting the authorisation code from  the redirect url<br>auth_url = str(input(&quot;Paste the redirect url here: &quot;)) # Prompting the user to paste the redirect url<br>parsed = urllib.parse.urlparse(auth_url)<br>params = urllib.parse.parse_qs(parsed.query)<br>auth_code = params.get(&quot;code&quot;, [None])[0]<br><br># Retrieving the access token using the authorisation code<br>tokens = exchange_code_for_tokens(token_endpoint, app_key, app_secret, redirect_url, auth_code)<br>access_token = tokens[&quot;access_token&quot;]<br>refresh_token = tokens.get(&quot;refresh_token&quot;) # In case Saxo doesn&#39;t return a refresh token, the program will not crash<br>token_expiration = tokens[&quot;expires_in&quot;]<br><br>print (&quot;Access token succesfully retrieved.&quot;)<br><br># Retrieving client key and account key<br>keys = retrieving_keys(access_token, app_key)<br>client_key = keys[0][&quot;client_key&quot;]<br>account_key = keys[1]</pre><h3>What’s next?</h3><p>With the authentication complete, we can now move on to the next stage: retrieving the portfolio composition.</p><p>Stay tuned so you don’t miss the upcoming articles.</p><p>If you find this project useful, you can support my work on <strong>B</strong><a href="https://buymeacoffee.com/gustave"><strong>uy Me a Coffee</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95dfe8f86931" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Saxo Bank Portfolio Analytics Tool with Python and Saxo OpenAPI — Part 2]]></title>
            <link>https://medium.com/@ilunga.gus/building-a-saxobank-portfolio-analytics-with-python-part-2-1e4c25adea34?source=rss-7a94ae578149------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e4c25adea34</guid>
            <category><![CDATA[saxo-openapi]]></category>
            <category><![CDATA[saxo]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[portfolio]]></category>
            <dc:creator><![CDATA[Gustave Ilunga ]]></dc:creator>
            <pubDate>Wed, 20 May 2026 20:11:22 GMT</pubDate>
            <atom:updated>2026-10-20T18:28:21.031Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2: Setting up an account on the Saxo Developer Portal</h4><p>This article is the second one of the series “Building a Saxo Bank Portfolio Analytics Tool with Python and Saxo OpenAPI”. The series contains the following article:</p><ul><li><a href="https://medium.com/@ilunga.gus/how-to-build-a-saxobank-portfolio-analytics-with-python-part-1-why-this-project-d4650c52d2a5">Part 1: Why this project?</a></li><li><strong>Part 2: Setting up an account on the Saxo Developer Portal</strong></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxobank-portfolio-analytics-with-python-part-3-95dfe8f86931">Part 3: Authenticating with Saxo OpenAPI</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-part-4-358284ea8a2e">Part 4: Retrieving portfolio composition</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-part-5-40f39eb8b2bb?sharedUserId=ilunga.gus">Part 5: Analysing Sector and Geographic Exposure</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-conclusion-0e4d67c4be24?sharedUserId=ilunga.gus">Conclusion</a></li></ul><p>In this article I explain how I set up a Saxo Developer Account.</p><h3>What is a Saxo Developer Portal and why do we need an account?</h3><p>A Saxo Developer Portal gives you access to Saxo OpenAPI, which exposes Saxo’s trading engine, market data, portfolio data, and client‑management services through modern REST and streaming APIs.<br>You need an account if you want to build applications, automate trading, retrieve market data, or integrate Saxo’s trading capabilities into your own systems.</p><p>Link to access Saxo Developer Portal: <a href="https://www.developer.saxo/"><strong>https://www.developer.saxo/</strong></a></p><p>Once you have an account on the Saxo Developer Portal, you will have the possibility to create simulation apps (or demo environment) and live Apps.</p><ul><li>The Simulation App is a demo environment that you can use to get familiar with the functionality of Saxo OpenAPI. It is for learning, testing and experimenting.</li><li>The Live App lets you connect your real Saxo investment portfolio in order to perform various activities (placing orders, accessing market data, etc.). This is the one we will use to build our portfolio analytics.</li></ul><p>Below are the steps to set up an account on the Saxo Developer Portal.</p><h3>Step 1: Creating an account</h3><p>Visit this page to create the account: <a href="https://www.developer.saxo/accounts/sim/signup">https://www.developer.saxo/accounts/sim/signup</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*ka35bn-T2qMcGJPs5NHseg.png" /><figcaption>Sign up page</figcaption></figure><p>When you sign up, you’ll be creating what Saxo calls a <strong>simulation account</strong>. It is important to note that this single account gives you access to <strong>both</strong> the Simulation App environment and the Live App environment. You don’t need to create separate accounts for each environment.</p><p>After signing up, you will receive an email with the credentials to access your account. <strong>Keep these informations safe.</strong></p><p>Once you receive the credentials, head to <a href="https://www.developer.saxo/">https://www.developer.saxo/</a> . Open the main menu panel and click on sign in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wFYekWuZH7zUqcvOf8bLg.png" /><figcaption>Saxo Developer Portal main page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLxBclPKkxxBD9KfAStQbg.png" /><figcaption>Main menu panel</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZljUJriUlCNr6maiFVvbQ.png" /><figcaption>Sign-in page of the Saxo Developer Portal</figcaption></figure><p>After signing in, you will redirected to the Saxo Developer Portal main page. Open the menu panel and click on “Apps”. You should have a page as the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPuUNZUN4APp_33NZOHy0g.png" /><figcaption>The account page/simulation app dashboard</figcaption></figure><h3>Step 2: Creating a Simulation App</h3><p>When you access your account, you will land on the Simulation App dashboard (see the above picture). Before we can create a Live App, we must first create a Simulation App.</p><p>Click on “create an application” and fill the form that appears (see picture below). For the redirect URL we can simply put: <a href="http://localhost:8000/callback">http://localhost:8000/callback</a>. As for the access control, you can tick “allow this app to be enabled for trading”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNg9MnPAXHEnX0kF9a_ngw.png" /><figcaption>Form to create a Simulation App</figcaption></figure><p>Once you create your Simulation App, it will appear on your account.</p><h3>Step 3: Creating a Live App</h3><p>When you are on your account, click on Live Apps as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V1qr6zB9Sz7Jbj3kFDdCxw.png" /><figcaption>Step to access the Live App</figcaption></figure><p>You will be redirected to a page to sign into your actual Saxo investment portfolio.</p><ul><li>User ID: Your customer ID number. You can find it in your SaxoInvestor or SaxoTrader account.</li><li>Password: The password you use to access your SaxoInvestor or SaxoTrader account.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*St1inoh8wGM_Y3iX236_Gw.png" /><figcaption>Sign-in page to access the live App environment</figcaption></figure><p>After signing in, you will be redirected to the Live App dashboard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2C9V6WXyHgLfX_W_Zi_tw.png" /><figcaption>Live App dashboard</figcaption></figure><p>Click on “request live App” and fill the form.</p><p>For the purpose of this project:</p><ul><li>Redirect URL: “<a href="http://localhost:8000/callback">http://localhost:8000/callback</a>”. Since we are building a tool to run on the pc.</li><li>Grant type: “Code”. Because we are building a Python based tool that will run on our personal pc.</li><li>Access control: I didn’t enable trading tick since I was only interested in doing portfolio analytics.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBHIdgk8Y02BEj5GyzAMkQ.png" /><figcaption>Form to request a live app</figcaption></figure><p>After requesting a live App, it can take a few minutes to few hours before seeing the Live App appearing in your account. Once the Live App appears in your account, click on it to have access to the application details (see picture below). We will use these details to build our portfolio analytics tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDGMp1HnapeGJLISHbtBHg.png" /><figcaption>Details of a Live App</figcaption></figure><h3>What’s next?</h3><p>If you have successfully completed all the steps described, you have an up and running live App. We are now ready to dive into the development of the portfolio analytics. The next article will be about authenticating with Saxo OpenAPI.</p><p>Stay tuned so you don’t miss the upcoming articles.</p><p>If you find this project useful, you can support my work on <strong>B</strong><a href="https://buymeacoffee.com/gustave"><strong>uy Me a Coffee</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e4c25adea34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Saxo Bank Portfolio Analytics Tool with Python and Saxo OpenAPI — Part 1]]></title>
            <link>https://medium.com/@ilunga.gus/how-to-build-a-saxobank-portfolio-analytics-with-python-part-1-why-this-project-d4650c52d2a5?source=rss-7a94ae578149------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4650c52d2a5</guid>
            <category><![CDATA[saxo]]></category>
            <category><![CDATA[saxo-openapi]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Gustave Ilunga ]]></dc:creator>
            <pubDate>Fri, 15 May 2026 14:10:22 GMT</pubDate>
            <atom:updated>2026-10-20T18:21:26.234Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1: Why this project?</h4><p>In this series, I show how I built a Python-based tool using Saxo OpenAPI to analyse sector and geographic exposure of my investment portfolio held at Saxo Bank.<br>This series is not only aimed at investors who use Saxo Bank (and who want to understand their portfolio’s sector and geographic exposure beyond what the platform provides), but is also aimed at anyone interested in the topics covered.</p><p>The series contains the following articles:</p><ul><li><strong>Part 1: Why this project?</strong></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxobank-portfolio-analytics-with-python-part-2-1e4c25adea34">Part 2: Setting up an account on the Saxo Developer Portal</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxobank-portfolio-analytics-with-python-part-3-95dfe8f86931">Part 3: Authenticating with Saxo OpenAPI</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-part-4-358284ea8a2e">Part 4: Retrieving portfolio composition</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-part-5-40f39eb8b2bb?sharedUserId=ilunga.gus">Part 5: Analysing Sector and Geographic Exposure</a></li><li><a href="https://medium.com/@ilunga.gus/building-a-saxo-bank-portfolio-analytics-tool-with-python-and-saxo-openapi-conclusion-0e4d67c4be24?sharedUserId=ilunga.gus">Conclusion</a></li></ul><h3>Why this project</h3><p>I’ve been investing in the stock market for quite some time now. To invest, you need a reliable broker. After some research and testing, I settled on <a href="https://www.home.saxo/fr-fr"><strong>Saxo Bank </strong></a>(commonly known as Saxo).</p><p>Founded in 1992, Saxo Bank is a Danish investment bank specializing in online trading and investment. It provides access to a broad range of financial instruments, including Forex, stocks, CFDs, futures, funds, bonds, and futures spreads, through its proprietary platforms SaxoInvestor and SaxoTrader.</p><p>I personally use SaxoInvestor. While I’m in general satisfied with the platform, I’ve noticed some frustrating limitations. When you own Exchange-Traded Funds (ETFs), the platform does not automatically show the geographic and sector allocation of your portfolio by aggregating across all your ETFs. It does this well for individual stocks, but not for ETF holdings.</p><p>That gap led me to embark on a journey to build a tool that does exactly that: compute and display the geographic and sectoral allocation of my entire portfolio.</p><p>To achieve this, I worked with <a href="https://www.developer.saxo/openapi/learn">Saxo OpenAPI</a> developped by Saxo.<strong> </strong>The Saxo API allows you to perform a number of operations, such as:</p><ul><li>Accessing your accounts,</li><li>Viewing your positions,</li><li>And even placing orders.</li></ul><p>Using this API, I built a Python-based portfolio analytics tool that pulls my Saxo holdings to analyse sector (e.g., technology, healthcare, energy) and geographic exposure (US, Europe, Asia, etc.) across all my ETFs and stocks.</p><h3>What’s next?</h3><p>In the next article, I will show how to set up a Saxo Developer Account which is necessary for the successful completion of the project.</p><p>Stay tuned so you don’t miss the upcoming articles.</p><p>If you find this project useful, you can support my work on <a href="https://buymeacoffee.com/gustave"><strong>Buy Me a Coffee</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4650c52d2a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web scraping with Python: Scraping booking.com using selenium]]></title>
            <link>https://medium.com/@ilunga.gus/web-scraping-with-python-scraping-booking-com-using-selenium-671529bdc258?source=rss-7a94ae578149------2</link>
            <guid isPermaLink="false">https://medium.com/p/671529bdc258</guid>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Gustave Ilunga ]]></dc:creator>
            <pubDate>Sun, 15 Dec 2024 01:16:04 GMT</pubDate>
            <atom:updated>2024-12-15T01:16:04.341Z</atom:updated>
            <content:encoded><![CDATA[<p>Booking.com is one of the largest travel agencies. It allows users to make lodging (hotels, motels, and resorts) and flight reservations.</p><p>Selenium is an open-source tool for automating web browsers, allowing for the testing of web applications across different browsers and platforms. It supports multiple programming languages like Python. Selenium is also widely used for web scraping. Here is an interesting page to learn more about the library: <a href="https://selenium-python.readthedocs.io/">https://selenium-python.readthedocs.io/</a></p><p>In this tutorial, we will use selenium to scrape booking.com to obtain information about hotels in selected cities. Without further due, let’s dive in.</p><p><strong>1. Importing the libraries</strong></p><p>It is important to ensure that selenium and pandas are installed in your environment.</p><pre>from selenium import webdriver <br>from selenium.webdriver.common.by import By <br>from selenium.webdriver.chrome.service import Service<br>from selenium.webdriver.support.ui import WebDriverWait<br>from selenium.webdriver.support import expected_conditions as EC<br>from selenium.webdriver.common.keys import Keys<br>import time<br>import pandas as pd</pre><p><strong>2. Understanding the pursued objectives</strong></p><p>Once our libraries are imported, let’s explain what is the pursued objectives and how the following block of codes will help us achieve that.</p><p>We have a list of selected cities. For each of these cities, we want to extract the information about the first 20 properties from our search on booking.com. The information we want are:<em> </em><strong><em>name, links to the property page, the location of the property, the rating and the description</em></strong>.</p><p><strong>3. Inspecting the structure of the website</strong></p><p>Let’s do a search for the city of Marseille (or any city of your choice). You can also just click on this link: <a href="https://www.booking.com/searchresults.html?ss=marseille">https://www.booking.com/searchresults.html?ss=marseille</a></p><p>We can notice that properties are organised as card. Each property card contains the information we want to scrape. This observation will be useful for the rest of the tutorial.</p><p>The next step is to identify the CSS selector of each item of the page that hold the information we are interested in. A CSS selector is a pattern used to select and style elements on a webpage. It helps us target specific HTML elements, like a button or a paragraph. Below are the CSS selector for each item that holds the information we want:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3V6K0115yGU13ZcUx2f8gw.png" /><figcaption><strong>Property card CSS selector: div[data-testid=”property-card”]</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wVcKTnC7Zcy8K9Eg-Gc_Gw.png" /><figcaption><strong>Name CSS selector: div[data-testid=”title”]</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8grMdlY--YxYtt2mKB_sAQ.png" /><figcaption><strong>Link CSS selector: a[data-testid=”title-link”]</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSd0uMHno78rmFjJ16NcNQ.png" /><figcaption><strong>Location CSS selector: span[data-testid=”address”]</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrK-ZYjfJyfedh7xudxJeA.png" /><figcaption><strong>Rating CSS selector: div[data-testid=”review-score”]</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DsCG_ER0O7-dcFUWA7I4w.png" /><figcaption><strong>Description CSS selector: div[class=”abf093bdfe”]</strong></figcaption></figure><p>Now that we have all the CSS selector, we can move the second part of our script.</p><p><strong>4. Writing our scraping script</strong></p><p>We will define a function for the scraping.</p><pre># Defining a function that will scrap booking.com<br>def get_hotel_info(city_url):<br>    driver = webdriver.Chrome() # Setting up the driver<br>    driver.get(city_url)<br>    time.sleep(10) # Putting the scrapping in pause to allpow page to load<br><br>    property_card = driver.find_elements(By.CSS_SELECTOR, &#39;div[data-testid=&quot;property-card&quot;]&#39;) # Properties are presented as card in the search result<br><br>    # Creating emmpty list where information will be stored<br>    name_list = []<br>    link_list = []<br>    location_list = []<br>    rating_list = []<br>    description_list = []<br><br>    first_20_properties = property_card[:20] # Slicing the list to only work with the first 20 properties<br>    <br>    # For each property, we extract the information of interest using the CSS selector<br>    for property in first_20_properties: <br>        name = property.find_elements(By.CSS_SELECTOR, &#39;div[data-testid=&quot;title&quot;]&#39;)<br>        link = property.find_elements(By.CSS_SELECTOR, &#39;a[data-testid=&quot;title-link&quot;]&#39;)<br>        location = property.find_elements(By.CSS_SELECTOR, &#39;span[data-testid=&quot;address&quot;]&#39;)<br>        rating = property.find_elements(By.CSS_SELECTOR, &#39;div[data-testid=&quot;review-score&quot;]&#39;)<br>        description = property.find_elements(By.CSS_SELECTOR, &#39;div[class=&quot;abf093bdfe&quot;]&#39;)<br><br>        # Result from the lines above are list composed of a single element. Here we proceed to the content extraction<br>        name_list.append(name[0].text.strip())<br>        link_list.append(link[0].get_attribute(&#39;href&#39;))<br>        location_list.append(location[0].text.strip())<br>        rating_list.append(rating[0].text.strip())<br>        description_list.append(description[0].text.strip())<br><br>    # Storing results into a dataframe to be exported as an excel spreadsheet<br>    df = pd.DataFrame({&quot;Name&quot;:name_list,<br>                    &quot;Page link&quot;: link_list,<br>                    &quot;Location&quot;: location_list,<br>                    &quot;Rating&quot; : rating_list,<br>                    &quot;Description&quot;: description_list})<br>    return df</pre><p>Launching the actual scraping</p><pre># List of cities for which we want hotels information<br>cities = [&quot;Mont Saint Michel&quot;, &quot;St Malo&quot;, &quot;Bayeux&quot;, &quot;Le Havre&quot;, &quot;Rouen&quot;, &quot;Paris&quot;, &quot;Amiens&quot;, &quot;Lille&quot;, &quot;Strasbourg&quot;, &quot;Chateau du Haut Koenigsbourg&quot;, &quot;Colmar&quot;, &quot;Eguisheim&quot;, &quot;Besancon&quot;, <br>          &quot;Dijon&quot;, &quot;Annecy&quot;, &quot;Grenoble&quot;, &quot;Lyon&quot;, &quot;Gorges du Verdon&quot;, &quot;Bormes les Mimosas&quot;, &quot;Cassis&quot;, &quot;Marseille&quot;, &quot;Aix en Provence&quot;, &quot;Avignon&quot;, &quot;Uzes&quot;, &quot;Nimes&quot;,<br>          &quot;Aigues Mortes&quot;, &quot;Saintes Maries de la mer&quot;, &quot;Collioure&quot;, &quot;Carcassonne&quot;, &quot;Foix&quot;, &quot;Toulouse&quot;, &quot;Montauban&quot;, &quot;Biarritz&quot;, &quot;Bayonne&quot;, &quot;La Rochelle&quot;]<br><br>for city in cities:<br>    # Generating links to be used for scraping<br>    url = f&quot;https://www.booking.com/searchresults.html?ss={city}&quot;<br><br>    # Initiating the scraping using the function we created<br>    try:<br>        hotel_df = get_hotel_info(url) # Using the url to scrap the info<br>        hotel_df.to_excel(f&quot;C:/Users/ilung/Documents/scraping_results/hotels_{city}.xlsx&quot;, index=False) # Saving the result<br>        print (f&quot;{city} completed&quot;)<br>    <br>    except Exception as e:<br>        print (f&quot;Process not compeleted for {city}. The error is {e}&quot;)</pre><p>That’s it. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=671529bdc258" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Georeferencing downloaded CMIP6 data and extracting an area of interest]]></title>
            <link>https://medium.com/@ilunga.gus/georeferencing-downloaded-cmip6-data-and-extracting-an-area-of-interest-9d8a56409f17?source=rss-7a94ae578149------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d8a56409f17</guid>
            <category><![CDATA[climate-data]]></category>
            <category><![CDATA[cmip6]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Gustave Ilunga ]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 13:19:44 GMT</pubDate>
            <atom:updated>2024-11-23T07:49:51.613Z</atom:updated>
            <content:encoded><![CDATA[<p>CMIP6 data is publicly available and accessible through various data repositories and portals, such as the Earth System Grid Federation (ESGF). This article completes the first one I wrote downloading CMIP6 data. You can access it <a href="https://medium.com/@ilunga.gus/searching-and-downloading-cmip6-climate-data-usingpython-8335b61fabaf">here</a>.</p><p>CMIP6 data are not typically georeferenced in the traditional sense for direct use in GIS application. CMIP6 data use a 0 to 360-degree longitude range because it aligns with the 360-degree system used in many global climate models. This system ensures that the longitudinal data wraps around the globe seamlessly, with 0 degrees (or 360 degrees) corresponding to the Prime Meridian (Greenwich Meridian) and 180 degrees representing the International Date Line. This convention is particularly useful for global climate simulations and model intercomparisons, as it simplifies the handling of data at the boundaries of the longitude range. It also helps in maintaining consistency across different models and datasets.</p><p>This georeferencing system, can be a barrier to work with CMIP6 data especially in GIS application. It is therefore, necessary to do some preprocessing. In this article, I will show you two important preprocessing steps:</p><ul><li>Georeferencing CMIP6 data: By georeferencing here I mean changing longitude from 0–360 degree system to -180 to 180 degree</li><li>Extract an area of interest (AOI) by providing a bounding box.</li></ul><p>The script associated with the article can be downloaded <a href="https://github.com/g-ilunga/cmip6_data-download">here</a>.</p><p>Without further due, below are the necessary steps.</p><ol><li><strong>Importing relevant libraries</strong></li></ol><pre>import xarray as xr<br>import numpy as np</pre><p>2. <strong>Creating a function for georeferencing and extracting the AOI</strong></p><pre><br>def georef_clip (input_file, aoi, output_file): <br>    dataset = xr.open_dataset(input_file) # Opening the CMIP6 dataset<br><br>    # Georeferencing step<br>    dataset[&quot;lon&quot;] = np.where(dataset[&quot;lon&quot;] &gt; 180, dataset[&quot;lon&quot;] - 360, dataset[&quot;lon&quot;]) # Changing the 0-360 longitude format to use the -180 to 180 format<br>    dataset = dataset.sortby(dataset.lon) # Sorting the data by longitude values<br><br>    # Extracting the area of interest (AOI)<br><br>        # Finding the coordinates in the dataset that is closest to the provided AOI. <br>    lat_max = np.argmin(np.abs(dataset[&quot;lat&quot;].values - aoi[0]))<br>    lat_min = np.argmin(np.abs(dataset[&quot;lat&quot;].values - aoi[1]))<br>    lon_max = np.argmin(np.abs(dataset[&quot;lon&quot;].values - aoi[2]))<br>    lon_min = np.argmin(np.abs(dataset[&quot;lon&quot;].values - aoi[3]))<br><br>        # Getting the id of the closest coordinates<br>    lon_min_id = dataset[&quot;lon&quot;].values[lon_min]<br>    lon_max_id = dataset[&quot;lon&quot;].values[lon_max]<br>    lat_min_id = dataset[&quot;lat&quot;].values[lat_min]<br>    lat_max_id = dataset[&quot;lat&quot;].values[lat_max]<br><br>        # Clipping the data using the identified coordinates in the dataset that close to the provided AOI<br>    clipped_data = dataset.sel(lon=slice(lon_min_id, lon_max_id), lat=slice(lat_min_id, lat_max_id))<br><br>    # Saving the result<br>    clipped_data.to_netcdf(output_file)<br><br>    print (f&quot;Process completed. Data saved here {output_file}&quot;)</pre><p><strong>3. Launching the georeferencing process and extracting the AOI</strong></p><pre># Setting the parameters to be used by the function<br>input_file = &quot;C:/Users/ilung/Documents/uas_day_IPSL-CM6A-LR_ssp245_r1i1p1f1_gr_20150101-21001231.nc&quot; # input CMIP6 file<br>aoi = [15, -3, 3, -14] # The AOI bounding box. Must use the following format [lat_max, lat_min, lon_max, lon_min]<br>output_file = &quot;C:/Users/ilung/Documents/uas_day_clip.nc&quot; # Output file<br><br># Launching the function to georeference and extract the AOI<br>georef_clip(input_file, aoi, output_file)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d8a56409f17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to convert climate data in .grib format to netCDF?]]></title>
            <link>https://medium.com/@ilunga.gus/how-to-convert-climate-data-in-grib-format-to-netcdf-2b59cd9df222?source=rss-7a94ae578149------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b59cd9df222</guid>
            <category><![CDATA[grib]]></category>
            <category><![CDATA[climate-data]]></category>
            <category><![CDATA[netcdf]]></category>
            <dc:creator><![CDATA[Gustave Ilunga ]]></dc:creator>
            <pubDate>Wed, 21 Aug 2024 20:50:11 GMT</pubDate>
            <atom:updated>2024-11-23T10:03:47.244Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to convert climate data in .grib format to netCDF?</h3><p>Sometimes climate data, such as those produced by Copernicus, are shipped in .grib format. This format is appreciated by some climate scientists for their efficiency. Nevertheless, not everyone is comfortable working with this data format. A lot of people are more familiar with netCDF as it is one of the widely used data format.</p><p>The purpose of this short tutorial is to show how to quickly convert a .grib climate data to netCDF.</p><p><strong>Step 1: Creating a virtual environment with the desired Python version</strong>. I always recommend creating a virtual environment to avoid packages conflict. For information, I developed this script using Python 3.9.</p><p><strong>Step 2: Install the packages listed below in the order they are displayed:</strong></p><ul><li>ecmwflibs (version 0.5.1)</li><li>eccodes (version 1.3.1)</li><li>cfgrib (version 0.9.10.4)</li><li>xarray</li></ul><p><strong>Step 3: Run the scrip below:</strong></p><pre>import xarray as xr<br><br># Creating a function that will execute the conversion<br>def grib_to_nc(grib_file, output_file):<br>    data = xr.open_dataset(grib_file, engine=&quot;cfgrib&quot;)<br>    data.to_netcdf(output_file, format=&quot;NETCDF4&quot;)<br><br># Defining the input parameters to execute the function<br>grib_file = &quot;C:/Users/public/documents/temperature.grib&quot; # This is the path to the grib file<br>output_file = &quot;C:/Users/public/documents/converted_temperature.nc&quot; # This is the path to save the netcdf file<br><br># Executing the function<br>grib_to_nc(grib_file, output_file)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b59cd9df222" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Searching and downloading CMIP6 climate data using Python]]></title>
            <link>https://medium.com/@ilunga.gus/searching-and-downloading-cmip6-climate-data-usingpython-8335b61fabaf?source=rss-7a94ae578149------2</link>
            <guid isPermaLink="false">https://medium.com/p/8335b61fabaf</guid>
            <category><![CDATA[esgf-pyclient]]></category>
            <category><![CDATA[climate-data]]></category>
            <category><![CDATA[cmip6]]></category>
            <dc:creator><![CDATA[Gustave Ilunga ]]></dc:creator>
            <pubDate>Fri, 05 Jul 2024 19:41:18 GMT</pubDate>
            <atom:updated>2024-12-14T00:52:41.604Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>CMIP6 data is publicly available and accessible through various data repositories and portals, such as the Earth System Grid Federation (ESGF).</p><p>The ESGF community developed the Python library “esgf-pyclient” to facilitate the interaction with the ESGF system. With the library you can search and download climate data available on the system. More information about the library can be found <a href="https://esgf-pyclient.readthedocs.io/en/latest/index.html#">here</a>.</p><p>I developed a script to download CMIP6 data using the “esgf-pyclient” library. The script can be downloaded <a href="https://github.com/g-ilunga/cmip6_data-download">here</a>.</p><p>Below is a step by step process to download CMIP6 data using Python.</p><p>I recommend that you create a virtual environment where you will install the following packages: <em>esgf-pyclient, pandas, xarray, requests</em></p><p><strong>1. Importing the necessary libraries</strong></p><pre>from pyesgf.search import SearchConnection<br>import os<br>import pandas as pd<br>import requests</pre><p><strong>2. Data search based on criteria</strong></p><p>Here we are defining criteria to be taken into account to obtain the desired dataset.</p><pre># This is to indicate that we want CMIP6 data<br>project = [&quot;CMIP6&quot;] <br><br># Specifying the models of interest<br>source_id = [&quot;TaiESM1&quot;] <br><br># Specifying if you we historical data or projection (ssp245, ssp585, etc.)<br>experiment_id = [&quot;historical&quot;, &quot;ssp245&quot;, &quot;ssp585&quot;] <br><br># Specifying the variant label<br>variant_label = [&quot;r1i1p1f1&quot;] <br><br># Specifying the frequency<br>frequency = [&quot;day&quot;] <br><br># Specifying the climate variable you are searching for<br>variable = [&quot;tas&quot;, &quot;tasmin&quot;, &quot;tasmax&quot;]</pre><p>The list below (“facets) must contain all the variables you intend to use to filter your search. The element “<em>latest</em>” is to specify whether or not you want the latest data. The element “<em>replica”</em> is to specify whether or not you want duplicate to be included in your search results. It is advised to always keep “<em>latest</em>” and “<em>replica</em>” in the list.</p><pre>facets = [&quot;project&quot;, &quot;source_id&quot;, &quot;experiment_id&quot;, <br>&quot;variable&quot;, &quot;frequency&quot;, &quot;variant_label&quot;, &quot;latest&quot;, &quot;replica&quot;]</pre><p>Here we are now launching the search</p><pre># Specifying the node from which we want the data search to start. Setting the &quot;distrib&quot; parameter to &quot;true&quot; will expand the data search to other nodes<br>conn = SearchConnection(&#39;https://esgf-node.ipsl.upmc.fr/esg-search&#39;, distrib = True)<br><br># Launching the search<br>query = conn.new_context (latest = True, # Set to &quot;true&quot; to only get the latest version of dataset<br>                          replica = False, # Set to &quot;false&quot; to avoid getting duplicate in the search result.<br>                          project = project,<br>                          source_id = source_id,<br>                       experiment_id = experiment_id,<br>                       variable = variable,<br>                       frequency = frequency,<br>                       variant_label = variant_label,<br>                       facets = facets) # This is to confirm the search criteria we have set. Must always be kept here<br><br># Here is to obtain the total number of results the search has returned<br>results_count = query.hit_count <br><br>print (f&quot;The search has returned {results_count} results&quot;)</pre><p>It is important to highlight that each result contains a certain number of files. And each file is associated with a unique URL that can be used to download it. The line below is written to extract these URLs and store them in an Excel spreadsheet.</p><pre># Initialising an empty list that will be used to store the extracted URLs<br>urls = [] <br><br># Starting the extraction of URLs.<br>for i in range(results_count): # This first loop will iterate over each result<br>    dataset = query.search()[i] # This open a dataset <br>    files_list = dataset.file_context().search() # This create a list of files contained in the opened dataset<br><br>    for file in files_list: # This loop will iterate over each file of the list to extract their URLs<br>        urls.append(file.download_url)<br><br>    print (f&quot;Results {i+1} out of {results_count} processed&quot;)<br><br># Saving the URLs in an Excel spreadsheet<br>df = pd.DataFrame(urls, columns = [&quot;Links&quot;])<br>df.to_excel(&quot;C:/Users/gilunga/Documents/files_url.xlsx&quot;)</pre><p>This script does not allow to filter date from the search results. If you are specifically looking for some years, you can do the necessary editing in the created spreadsheet before heading to the next part of the script.</p><p><strong>3. Data download using the extracted URLs</strong></p><pre># Defining a fonction for the download process<br><br>def download (url_file, output_path):<br>    # Converting the URLs table into list<br>    df_urls = pd.read_excel(url_file)<br>    df_urls_list = df_urls[&quot;Links&quot;].list()<br><br>    # Starting of download<br>    for url in df_urls_list:<br>        try:<br>            file_name = str(url.rsplit(&quot;/&quot;, 1)[-1])<br>            file_output = output_path + file_name<br>            response = requests.get(url, stream = True)<br><br>            if response.status_code == 200:<br>                with open (file_output, &#39;wb&#39;) as f:<br>                    for chunk in response.iter_content(chunk_size=1024):<br>                        f.write(chunk)<br>                print (f&quot;Data successfuly downloaded : {file_name}&quot;)<br>            else:<br>                print (f&quot;Download failed for {file_name}. Status code: {response.status_code}&quot;)<br><br>        except Exception as e:<br>            print (f&quot;Download failed for {file_name}. Error returned {e}&quot;)</pre><pre># Data download<br><br>url_file = &quot;C:/Users/gilunga/Documents/files_url.xlsx&quot; # Path to the Excel spreadsheet containing the URLs<br>output_path = &quot;C:/Users/gilunga/Documents/&quot; # Path where data will be saved<br>download(url_file, output_path) # Lauching the download</pre><p>That’s it. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8335b61fabaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>