{ "cells": [ { "cell_type": "markdown", "id": "fe798454", "metadata": {}, "source": [ "# Python API Example - Cargo Netforwards\n", "\n", "This guide is designed to provide an example of how to call the Cargo Netforwards API endpoint, and store the data accordingly.\n", "- The path to your client credentials is the only input needed to run this script (just before Section 2)\n", "\n", "__N.B. This guide is just for Cargo Netforwards data. If you're looking for other API data products (such as Contracts, Freight routes or Netbacks), please refer to their according code example files.__" ] }, { "cell_type": "markdown", "id": "1687ce60", "metadata": {}, "source": [ "### 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/netforwards.html" ] }, { "cell_type": "markdown", "id": "8e5f2c85", "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, "id": "9a5db7a5", "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 urllib.parse import urljoin\n", "from io import StringIO\n", "import datetime\n", "\n", "try:\n", " from urllib import request, parse\n", " from urllib.error import HTTPError\n", "except ImportError:\n", " raise RuntimeError(\"Python 3 required\")" ] }, { "cell_type": "code", "execution_count": null, "id": "0dee0877", "metadata": {}, "outputs": [], "source": [ "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", " \n", " return client_id, client_secret\n", "\n", "\n", "def do_api_post_query(uri, body, headers):\n", " \"\"\"\n", " OAuth2 authentication requires a POST request with client credentials before accessing the API.\n", " This POST request will return an Access Token which will be used for the API GET request.\n", " \"\"\"\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", " Supports both JSON (default) and CSV responses.\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", " print(\"Fetching {}\".format(url))\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", "\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", " payload = \"{}:{}\".format(client_id, client_secret).encode()\n", " headers = {\n", " \"Authorization\": 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\"]" ] }, { "cell_type": "markdown", "id": "6207eabf", "metadata": {}, "source": [ "## N.B. Credentials\n", "\n", "Here we call the above functions, and input the file path to our credentials.\n", "\n", "N.B. You must have downloaded your client credentials CSV file before proceeding. Instructions for downloading your credentials can be found here:\n", "\n", "https://app.sparkcommodities.com/data-integrations/api" ] }, { "cell_type": "code", "execution_count": null, "id": "e694efee", "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)" ] }, { "cell_type": "markdown", "id": "046f8966", "metadata": {}, "source": [ "## 2. Reference Data\n", "\n", "Lists every available Netforwards route: DES location, FOB port, via points and their UUIDs." ] }, { "cell_type": "code", "execution_count": null, "id": "f2f59691", "metadata": {}, "outputs": [], "source": [ "def fetch_netforwards_reference_data(access_token, format='json'):\n", "\n", " content = do_api_get_query(\n", " uri=\"/v1.0/lng/cargo/netforwards/reference-data/\", 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", "\n", " return data\n", "\n", "ref_data = fetch_netforwards_reference_data(access_token, format='csv')\n", "ref_data.head(5)" ] }, { "cell_type": "markdown", "id": "96d3a4d9", "metadata": {}, "source": [ "## 3. Netforwards Data\n", "\n", "The available parameters can be found on our API docs:\n", "\n", "https://www.sparkcommodities.com/api/lng-cargo/netforwards.html\n", "\n", "__N.B.:__ This endpoint provides the option to return a JSON or CSV formatted response. Metadata is only available in the JSON format." ] }, { "cell_type": "code", "execution_count": null, "id": "75060005", "metadata": {}, "outputs": [], "source": [ "def fetch_netforwards(access_token, unit, price_format, fob_netback, des_port_uuid=None, fob_port_uuid=None,\n", " fob_netback_via=None, des_netforward_via=None, laden_congestion_days=None, ballast_congestion_days=None,\n", " start=None, end=None, limit=None, offset=None, format='json'):\n", "\n", " query_params = \"?unit={}\".format(unit)\n", " query_params += \"&price-format={}\".format(price_format)\n", " query_params += \"&fob-netback={}\".format(fob_netback)\n", " if des_port_uuid is not None:\n", " query_params += \"&des-port-uuid={}\".format(des_port_uuid)\n", " if fob_port_uuid is not None:\n", " query_params += \"&fob-port-uuid={}\".format(fob_port_uuid)\n", " if fob_netback_via is not None:\n", " query_params += \"&fob-netback-via={}\".format(fob_netback_via)\n", " if des_netforward_via is not None:\n", " query_params += \"&des-netforward-via={}\".format(des_netforward_via)\n", " if laden_congestion_days is not None:\n", " query_params += \"&laden-congestion-days={}\".format(laden_congestion_days)\n", " if ballast_congestion_days is not None:\n", " query_params += \"&ballast-congestion-days={}\".format(ballast_congestion_days)\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 limit is not None:\n", " query_params += \"&limit={}\".format(limit)\n", " if offset is not None:\n", " query_params += \"&offset={}\".format(offset)\n", "\n", " content = do_api_get_query(\n", " uri=\"/v1.0/lng/cargo/netforwards/{}\".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 an empty DataFrame and \"No Data to Show\" message\n", " if len(content) == 0:\n", " data = pd.DataFrame()\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", "\n", " return data" ] }, { "cell_type": "code", "execution_count": null, "id": "17380915", "metadata": {}, "outputs": [], "source": [ "# choosing DES location and FOB port\n", "dahej_uuid = ref_data[ref_data['DESPortName'] == 'Dahej']['DESPortUUID'].iloc[0]\n", "sabine_uuid = ref_data[ref_data['FOBPortName'] == 'Sabine Pass']['FOBPortUUID'].iloc[0]" ] }, { "cell_type": "markdown", "id": "3ca68c14", "metadata": {}, "source": [ "#### JSON Response" ] }, { "cell_type": "code", "execution_count": null, "id": "34b38631", "metadata": {}, "outputs": [], "source": [ "json_data = fetch_netforwards(access_token, unit='usd-per-mmbtu', price_format='outright', fob_netback='max',\n", " des_port_uuid=dahej_uuid, fob_port_uuid=sabine_uuid,\n", " fob_netback_via='cogh', des_netforward_via='cogh',\n", " start='2026-09-01', end='2026-09-30')\n", "json_data" ] }, { "cell_type": "code", "execution_count": null, "id": "e79cb003", "metadata": {}, "outputs": [], "source": [ "# checking metaData\n", "json_data['metaData']" ] }, { "cell_type": "markdown", "id": "e3a713b5", "metadata": {}, "source": [ "#### CSV Response\n", "\n", "Only providing des_port_uuid here returns all Netforwards related to the chosen DES Port. The same can be done for any chosen FOB port." ] }, { "cell_type": "code", "execution_count": null, "id": "a31937d3", "metadata": {}, "outputs": [], "source": [ "csv_data = fetch_netforwards(access_token, unit='usd-per-mmbtu', price_format='outright', fob_netback='max',\n", " des_port_uuid=dahej_uuid, start='2026-09-01', end='2026-09-30', format='csv')\n", "csv_data.head(5)" ] }, { "cell_type": "markdown", "id": "6189d0e7", "metadata": {}, "source": [ "#### Latest release for all routes\n", "\n", "Leave out the port filters and use `limit=1` to retrieve every route for the latest release." ] }, { "cell_type": "code", "execution_count": null, "id": "4574d44a", "metadata": {}, "outputs": [], "source": [ "latest_data = fetch_netforwards(access_token, unit='usd-per-mmbtu', price_format='outright', fob_netback='max',\n", " limit=1, format='csv')\n", "latest_data.head(5)" ] }, { "cell_type": "markdown", "id": "1da811fb", "metadata": {}, "source": [ "## N.B. Historical Data Limits\n", "\n", "A maximum of 1 year's worth of historical data can be called at one time.\n", "\n", "The function below calls the historical data 1 year at a time and combines it into one Pandas DataFrame." ] }, { "cell_type": "code", "execution_count": null, "id": "28fdcb01", "metadata": {}, "outputs": [], "source": [ "def loop_historical_data(access_token, unit, price_format, fob_netback, des_port_uuid=None, fob_port_uuid=None,\n", " fob_netback_via=None, des_netforward_via=None, laden_congestion_days=None,\n", " ballast_congestion_days=None, start=None, end=None):\n", "\n", " hist_diff = (datetime.datetime.strptime(end, '%Y-%m-%d') - datetime.datetime.strptime(start, '%Y-%m-%d')).days\n", " t = 0\n", "\n", " starts = []\n", " ends = []\n", "\n", " w = 365\n", "\n", " while t < hist_diff:\n", " # initialising dataframe\n", " if t == 0 and hist_diff>w:\n", " diff_end = datetime.datetime.strftime(datetime.datetime.strptime(start, '%Y-%m-%d') + pd.Timedelta(days=w), '%Y-%m-%d')\n", " hist_df = fetch_netforwards(access_token, unit=unit, price_format=price_format, fob_netback=fob_netback,\n", " des_port_uuid=des_port_uuid, fob_port_uuid=fob_port_uuid,\n", " fob_netback_via=fob_netback_via, des_netforward_via=des_netforward_via,\n", " laden_congestion_days=laden_congestion_days, ballast_congestion_days=ballast_congestion_days,\n", " start=start, end=diff_end, format='csv')\n", "\n", " starts.append(start)\n", " ends.append(diff_end)\n", "\n", " elif t==0 and hist_diff<=w:\n", " hist_df = fetch_netforwards(access_token, unit=unit, price_format=price_format, fob_netback=fob_netback,\n", " des_port_uuid=des_port_uuid, fob_port_uuid=fob_port_uuid,\n", " fob_netback_via=fob_netback_via, des_netforward_via=des_netforward_via,\n", " laden_congestion_days=laden_congestion_days, ballast_congestion_days=ballast_congestion_days,\n", " start=start, end=end, format='csv')\n", "\n", " # appending additional historical data\n", " else:\n", " if t < hist_diff-w:\n", " diff_start = datetime.datetime.strftime(datetime.datetime.strptime(start, '%Y-%m-%d') + pd.Timedelta(days=t+1), '%Y-%m-%d')\n", " diff_end = datetime.datetime.strftime(datetime.datetime.strptime(diff_start, '%Y-%m-%d') + pd.Timedelta(days=w), '%Y-%m-%d')\n", " historical_addition = fetch_netforwards(access_token, unit=unit, price_format=price_format, fob_netback=fob_netback,\n", " des_port_uuid=des_port_uuid, fob_port_uuid=fob_port_uuid,\n", " fob_netback_via=fob_netback_via, des_netforward_via=des_netforward_via,\n", " laden_congestion_days=laden_congestion_days, ballast_congestion_days=ballast_congestion_days,\n", " start=diff_start, end=diff_end, format='csv')\n", "\n", " try:\n", " hist_df = pd.concat([hist_df,historical_addition])\n", " #exception if hist_df is empty\n", " except:\n", " hist_df = historical_addition.copy()\n", " starts.append(start)\n", " ends.append(diff_end)\n", " else:\n", " diff_start = datetime.datetime.strftime(datetime.datetime.strptime(start, '%Y-%m-%d') + pd.Timedelta(days=t+1), '%Y-%m-%d')\n", " diff_end = datetime.datetime.strftime(datetime.datetime.strptime(diff_start, '%Y-%m-%d') + pd.Timedelta(days=hist_diff-t), '%Y-%m-%d')\n", "\n", " historical_addition = fetch_netforwards(access_token, unit=unit, price_format=price_format, fob_netback=fob_netback,\n", " des_port_uuid=des_port_uuid, fob_port_uuid=fob_port_uuid,\n", " fob_netback_via=fob_netback_via, des_netforward_via=des_netforward_via,\n", " laden_congestion_days=laden_congestion_days, ballast_congestion_days=ballast_congestion_days,\n", " start=diff_start, end=diff_end, format='csv')\n", "\n", " hist_df = pd.concat([hist_df, historical_addition])\n", " starts.append(start)\n", " ends.append(diff_end)\n", "\n", " #looping by year\n", " t += w\n", "\n", " if len(hist_df) > 0:\n", " for c in ['DESNetforward', 'FOBPrice', 'FreightCost', 'VolumeAdjustment']:\n", " hist_df[c] = pd.to_numeric(hist_df[c])\n", " hist_df['ReleaseDate'] = pd.to_datetime(hist_df['ReleaseDate'])\n", " hist_df['DeliveryMonthDate'] = pd.to_datetime(hist_df['DeliveryMonth'])\n", " hist_df['CalMonth'] = hist_df['DeliveryMonthDate'].dt.strftime('%b%y')\n", "\n", " hist_df = hist_df.drop_duplicates()\n", " hist_df = hist_df.sort_values(['ReleaseDate', 'FOBLoadDate'])\n", "\n", " return hist_df" ] }, { "cell_type": "code", "execution_count": null, "id": "19ba0bb9", "metadata": {}, "outputs": [], "source": [ "today = datetime.datetime.now().strftime('%Y-%m-%d')\n", "\n", "hist_df = loop_historical_data(access_token, unit='usd-per-mmbtu', price_format='outright', fob_netback='max',\n", " des_port_uuid=dahej_uuid, fob_port_uuid=sabine_uuid,\n", " start='2024-01-01', end=today)\n", "hist_df" ] } ], "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.13.9" } }, "nbformat": 4, "nbformat_minor": 5 }