{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Netbacks Freight Hire Comparison\n", "\n", "This script allows you to plot multiple percentages of freight hire included in a given Netback.\n", "\n", "This script uses elements from our API code samples. If you'd like a more basic and informative example of how to pull data via the Spark API, please visit our API website:\n", "\n", "- API Website: https://www.sparkcommodities.com/api/code-examples/jupyter.html\n", "\n", "\n", "### Have any questions?\n", "\n", "If you have any questions regarding our API, or need help accessing specific datasets, please contact us at:\n", "\n", "__data@sparkcommodities.com__\n", "\n", "or refer to our API website for more information about this endpoint:\n", "https://www.sparkcommodities.com/api/lng-cargo/netbacks.html\n", "\n", "__N.B. This script requires a Cargo subscription__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Importing Data\n", "\n", "Here we define the functions that allow us to retrieve the valid credentials to access the Spark API.\n", "\n", "This section can remain unchanged for most Spark API users." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json\n", "import os\n", "import sys\n", "import pandas as pd\n", "import numpy as np\n", "from base64 import b64encode\n", "from pprint import pprint\n", "from urllib.parse import urljoin\n", "import datetime\n", "from io import StringIO\n", "import time\n", "\n", "\n", "try:\n", " from urllib import request, parse\n", " from urllib.error import HTTPError\n", "except ImportError:\n", " raise RuntimeError(\"Python 3 required\")\n", "\n", "\n", "API_BASE_URL = \"https://api.sparkcommodities.com\"\n", "\n", "\n", "def retrieve_credentials(file_path=None):\n", " \"\"\"\n", " Find credentials either by reading the client_credentials file or reading\n", " environment variables\n", " \"\"\"\n", " if file_path is None:\n", " client_id = os.getenv(\"SPARK_CLIENT_ID\")\n", " client_secret = os.getenv(\"SPARK_CLIENT_SECRET\")\n", " if not client_id or not client_secret:\n", " raise RuntimeError(\n", " \"SPARK_CLIENT_ID and SPARK_CLIENT_SECRET environment vars required\"\n", " )\n", " else:\n", " # Parse the file\n", " if not os.path.isfile(file_path):\n", " raise RuntimeError(\"The file {} doesn't exist\".format(file_path))\n", "\n", " with open(file_path) as fp:\n", " lines = [l.replace(\"\\n\", \"\") for l in fp.readlines()]\n", "\n", " if lines[0] in (\"clientId,clientSecret\", \"client_id,client_secret\"):\n", " client_id, client_secret = lines[1].split(\",\")\n", " else:\n", " print(\"First line read: '{}'\".format(lines[0]))\n", " raise RuntimeError(\n", " \"The specified file {} doesn't look like to be a Spark API client \"\n", " \"credentials file\".format(file_path)\n", " )\n", "\n", " print(\">>>> Found credentials!\")\n", " print(\n", " \">>>> Client_id={}, client_secret={}****\".format(client_id, client_secret[:5])\n", " )\n", "\n", " return client_id, client_secret\n", "\n", "\n", "def do_api_post_query(uri, body, headers):\n", " url = urljoin(API_BASE_URL, uri)\n", "\n", " data = json.dumps(body).encode(\"utf-8\")\n", "\n", " # HTTP POST request\n", " req = request.Request(url, data=data, headers=headers)\n", " try:\n", " response = request.urlopen(req)\n", " except HTTPError as e:\n", " print(\"HTTP Error: \", e.code)\n", " print(e.read())\n", " sys.exit(1)\n", "\n", " resp_content = response.read()\n", "\n", " # The server must return HTTP 201. Raise an error if this is not the case\n", " assert response.status == 201, resp_content\n", "\n", " # The server returned a JSON response\n", " content = json.loads(resp_content)\n", "\n", " return content\n", "\n", "\n", "def do_api_get_query(uri, access_token, format='json'):\n", " \"\"\"\n", " After receiving an Access Token, we can request information from the API.\n", " \"\"\"\n", " url = urljoin(API_BASE_URL, uri)\n", "\n", " if format == 'json':\n", " headers = {\n", " \"Authorization\": \"Bearer {}\".format(access_token),\n", " \"Accept\": \"application/json\",\n", " }\n", " elif format == 'csv':\n", " headers = {\n", " \"Authorization\": \"Bearer {}\".format(access_token),\n", " \"Accept\": \"text/csv\"\n", " }\n", " else:\n", " raise ValueError('The format parameter only takes `csv` or `json` as inputs')\n", "\n", " # HTTP GET request\n", " req = request.Request(url, headers=headers)\n", " try:\n", " response = request.urlopen(req)\n", " except HTTPError as e:\n", " print(\"HTTP Error: \", e.code)\n", " print(e.read())\n", " sys.exit(1)\n", "\n", " resp_content = response.read()\n", " #status = response.status\n", "\n", " # The server must return HTTP 200. Raise an error if this is not the case\n", " assert response.status == 200, resp_content\n", "\n", " # Storing response based on requested format\n", " if format == 'json':\n", " content = json.loads(resp_content)\n", " elif format == 'csv':\n", " content = resp_content\n", "\n", " return content\n", "\n", "\n", "def get_access_token(client_id, client_secret):\n", " \"\"\"\n", " Get a new access_token. Access tokens are the thing that applications use to make\n", " API requests. Access tokens must be kept confidential in storage.\n", "\n", " # Procedure:\n", "\n", " Do a POST query with `grantType` in the body. A basic authorization\n", " HTTP header is required. The \"Basic\" HTTP authentication scheme is defined in\n", " RFC 7617, which transmits credentials as `clientId:clientSecret` pairs, encoded\n", " using base64.\n", " \"\"\"\n", "\n", " # Note: for the sake of this example, we choose to use the Python urllib from the\n", " # standard lib. One should consider using https://requests.readthedocs.io/\n", "\n", " payload = \"{}:{}\".format(client_id, client_secret).encode()\n", " headers = {\n", " \"Authorization\": \"Basic {}\".format(b64encode(payload).decode()),\n", " \"Accept\": \"application/json\",\n", " \"Content-Type\": \"application/json\",\n", " }\n", " body = {\n", " \"grantType\": \"clientCredentials\",\n", " }\n", "\n", " content = do_api_post_query(uri=\"/oauth/token/\", body=body, headers=headers)\n", "\n", " print(\n", " \">>>> Successfully fetched an access token {}****, valid {} seconds.\".format(\n", " content[\"accessToken\"][:5], content[\"expiresIn\"]\n", " )\n", " )\n", "\n", " return content[\"accessToken\"]\n", "\n", "\n", "# Define the function for listing all netbacks\n", "def list_netbacks(access_token):\n", "\n", " content = do_api_get_query(\n", " uri=\"/v1.0/netbacks/reference-data/\", access_token=access_token\n", " )\n", "\n", " # retrieve release dates separately\n", " reldates = content[\"data\"][\"staticData\"][\"sparkReleases\"]\n", "\n", " # return reference data\n", " refdata_dict = content[\"data\"]\n", "\n", " return reldates, refdata_dict\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### N.B. Credentials\n", "\n", "N.B. You must have downloaded your client credentials CSV file before proceeding. Please refer to the API documentation if you have not dowloaded them already. Instructions for downloading your credentials can be found here:\n", "\n", "https://www.sparkcommodities.com/api/request/authentication.html\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Input the path to your client credentials here\n", "client_id, client_secret = retrieve_credentials(file_path=\"/tmp/client_credentials.csv\")\n", "\n", "# Authenticate:\n", "access_token = get_access_token(client_id, client_secret)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Fetch reference data:\n", "reldates, refdata_dict = list_netbacks(access_token)\n", "\n", "# Shows the structure of the raw dictionary called\n", "#refdata_dict\n", "\n", "# formatting as a Dataframe\n", "available_df = pd.json_normalize(refdata_dict['staticData']['fobPorts'])\n", "available_df" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Netbacks Import Base Functions" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from io import StringIO\n", "\n", "def fetch_netback(access_token, ticker, release=None, via=None, laden=None, ballast=None, start=None, end=None, percent_hire=None, format='json'):\n", " \n", " query_params = \"?fob-port={}\".format(ticker)\n", " if release is not None:\n", " query_params += \"&release-date={}\".format(release)\n", " if start is not None:\n", " query_params += \"&start={}\".format(start)\n", " if end is not None:\n", " query_params += \"&end={}\".format(end)\n", " if via is not None:\n", " query_params += \"&via-point={}\".format(via)\n", " if laden is not None:\n", " query_params += \"&laden-congestion-days={}\".format(laden)\n", " if ballast is not None:\n", " query_params += \"&ballast-congestion-days={}\".format(ballast)\n", " if percent_hire is not None:\n", " query_params += \"&percent-hire={}\".format(percent_hire)\n", " \n", " \n", " content = do_api_get_query(\n", " uri=\"/v1.0/netbacks/{}\".format(query_params),\n", " access_token=access_token, format=format,\n", " )\n", " \n", " if format == 'json':\n", " data = content\n", " elif format == 'csv':\n", " # if there's no data to show, returns raw response (empty string) and \"No Data to Show\" message\n", " if len(content) == 0:\n", " data = content\n", " print('No Data to Show')\n", " else:\n", " data = content.decode('utf-8')\n", " data = pd.read_csv(StringIO(data)) # automatically converting into a Pandas DataFrame when choosing CSV format\n", " data['ReleaseDate'] = pd.to_datetime(data['ReleaseDate'])\n", " data['LoadMonth'] = pd.to_datetime(data['LoadMonth'])\n", "\n", " return data\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Freight Hire Calculations\n", "\n", "As the endpoint only allows for 2 options (0% or 100%) for the freight hire percent parameter, we must calculate the netbacks when the cost included is inbetween.\n", "\n", "Here, we select 50% as well as the two available options. However, these values can be altered as necessary." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def calculate_netbacks(my_dict_0, my_dict_100, percent_hire_list):\n", "\n", " m = pd.merge(my_dict_0,my_dict_100,how='inner',on=['ReleaseDate','LoadMonth', 'LoadMonthIndex'],suffixes=(\"0%\", \"100%\"))\n", " m['NeaBaseCosts'] = m['NeaNetbackOutright100%'] - m['NeaNetbackOutright0%']\n", " m['NweBaseCosts'] = m['NweNetbackOutright100%'] - m['NweNetbackOutright0%']\n", "\n", " for percent_hire in percent_hire_list:\n", " m[f'NeaOutright{percent_hire}%'] = m['NeaBaseCosts'] * (percent_hire/100) + m['NeaNetbackOutright0%']\n", " m[f'NweOutright{percent_hire}%'] = m['NweBaseCosts'] * (percent_hire/100) + m['NweNetbackOutright0%']\n", "\n", " m[f'Arb{percent_hire}%'] = m[f'NeaOutright{percent_hire}%'] - m[f'NweOutright{percent_hire}%']\n", "\n", "\n", " return m" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. Calling data and sorting\n", "\n", "In this section, we call the data needed for the US Arb via COGH netback for both 0% Freight Hire and 100% Freight Hire." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Calling and calculating Netbacks\n", "\n", "We select the following Netback." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Choose route ID, price release date and freight hire\n", "\n", "# Select Route\n", "t = available_df[available_df[\"name\"] == 'Sabine Pass'][\"uuid\"].iloc[0]\n", "\n", "percent_hires = [0,50,100]\n", "\n", "my_dict_0 = fetch_netback(access_token, start='2025-01-01', end='2025-12-31', ticker=t, via='cogh', percent_hire=0, format='csv')\n", "my_dict_100 = fetch_netback(access_token, start='2025-01-01', end='2025-12-31', ticker=t, via='cogh', percent_hire=100, format='csv')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Sorting dataframes my load month and adding day of year column\n", "df25 = calculate_netbacks(my_dict_0,my_dict_100,percent_hires)\n", "\n", "# View one example of output\n", "df25.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Filtering by M+1\n", "df25_m1 = df25[df25['LoadMonthIndex'] == 1]\n", "\n", "df25_m1.head(10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 3. Plotting\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "\n", "# Plotting\n", "\n", "sns.set_theme(style=\"whitegrid\")\n", "\n", "fig, ax = plt.subplots(figsize=(15,6))\n", "\n", "plt.axhline(0, color='grey')\n", "\n", "ax.plot(df25_m1['ReleaseDate'], df25_m1[f'Arb0%'], color='darkblue', label=f'Arb - 0% Freight Hire Included', linewidth=2)\n", "ax.plot(df25_m1['ReleaseDate'], df25_m1[f'Arb50%'], color='darkblue', label=f'Arb - 50% Freight Hire Included', linewidth=2,linestyle='--')\n", "ax.plot(df25_m1['ReleaseDate'], df25_m1[f'Arb100%'], color='darkblue', label=f'Arb - 100% Freight Hire Included', linewidth=2,linestyle='dotted')\n", "\n", "plt.ylabel('$/MMBtu')\n", "\n", "plt.xlabel('ReleaseDate')\n", "\n", "ax.legend()\n", "\n", "sns.despine(left=True, bottom=True)" ] } ], "metadata": { "kernelspec": { "display_name": "base", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.5" } }, "nbformat": 4, "nbformat_minor": 2 }