{ "cells": [ { "cell_type": "markdown", "id": "92475c69", "metadata": {}, "source": [ "# Python API Example - End-of-Day JKM-TTF vs Arb Breakevens\n", "\n", "Here we plot JKM-TTF prices against relevant Arb Breakeven levels. This script can also be used for TTF prices vs TTF breakevens.\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/" ] }, { "cell_type": "markdown", "id": "c5716130", "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": "33fb0640", "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", "\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" ] }, { "cell_type": "markdown", "id": "fd3171a8", "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. Please refer to the API documentation if you have not dowloaded them already.\n", "\n", "The code then prints the available prices that are callable from the API, and their corresponding Python ticker names are displayed as a list at the bottom of the Output." ] }, { "cell_type": "code", "execution_count": null, "id": "fd7e89bf", "metadata": {}, "outputs": [], "source": [ "# Insert file 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": "10bafcf1", "metadata": {}, "source": [ "# 2. Arb Breakevens Reference Data\n", "\n", "Here we use the Cargo Netbacks Reference Data endpoint to return the UUID codes associated with each FoB Port available on the Arb Breakevens endpoint. " ] }, { "cell_type": "code", "execution_count": null, "id": "4d211cdb", "metadata": {}, "outputs": [], "source": [ "# 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", "# Fetch reference data:\n", "reldates, refdata_dict = list_netbacks(access_token)\n", "\n", "# formatting as a Dataframe\n", "available_df = pd.json_normalize(refdata_dict['staticData']['fobPorts'])\n", "available_df" ] }, { "cell_type": "markdown", "id": "e27e05fb", "metadata": {}, "source": [ "# 3. Endpoint Fetch Functions\n", "\n", "## 3.1 Cargo Arb Breakevens\n", "\n", "Details on these parameters can be found on the API docs website:\n", "\n", "https://www.sparkcommodities.com/api/lng-cargo/netbacks-arb-breakevens.html" ] }, { "cell_type": "code", "execution_count": null, "id": "24adff55", "metadata": {}, "outputs": [], "source": [ "from io import StringIO\n", "\n", "def fetch_breakevens(access_token, ticker, via=None, breakeven='jkm-ttf', start=None, end=None, format='json'):\n", "\n", "\n", " query_params = breakeven + '/' + \"?fob-port={}\".format(ticker)\n", "\n", " if via is not None:\n", " query_params += \"&via-point={}\".format(via)\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", "\n", " uri = \"/v1.0/netbacks/arb-breakevens/{}\".format(query_params)\n", " print(uri)\n", " content = do_api_get_query(\n", " uri=\"/v1.0/netbacks/arb-breakevens/{}\".format(query_params),\n", " access_token=access_token, format=format,\n", " )\n", " \n", " if format == 'json':\n", " data = content['data']\n", " else:\n", " data = content.decode('utf-8')\n", " data = pd.read_csv(StringIO(data))\n", " data['ReleaseDate'] = pd.to_datetime(data['ReleaseDate'])\n", "\n", " return data\n" ] }, { "cell_type": "markdown", "id": "8cc9fec8", "metadata": {}, "source": [ "## 3.2 Intraday EOD - Contracts Data (JKM-TTF)\n", "\n", "Details on these parameters can be found on our API docs website:\n", "\n", "https://www.sparkcommodities.com/api/intraday/eod.html" ] }, { "cell_type": "code", "execution_count": null, "id": "97554539", "metadata": {}, "outputs": [], "source": [ "## Defining the function\n", "\n", "def fetch_historical_contracts(access_token, contract, unit, start, end, format='json'):\n", " \n", " query_params = \"?contract={}\".format(contract)\n", " query_params += \"&unit={}\".format(unit)\n", "\n", " query_params += \"&start={}\".format(start)\n", " query_params += \"&end={}\".format(end)\n", "\n", " uri=\"/v1.0/intraday/contracts/eod/{}\".format(query_params)\n", " print(uri)\n", " \n", " content = do_api_get_query(\n", " uri=uri, 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 = 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\n" ] }, { "cell_type": "markdown", "id": "09f6ccc4", "metadata": {}, "source": [ "# 4. Historical Data Function\n", "\n", "Currently, a maximum of 1 year of historical data can be called at one time. If more data points are required, the below code can be used, which splits the requested date range into looped calls of 365 historical days at a time." ] }, { "cell_type": "code", "execution_count": null, "id": "596405a5", "metadata": {}, "outputs": [], "source": [ "import datetime\n", "\n", "def loop_historical_jkmttf(access_token, contract=None, breakeven_type=None, ticker=None, via=None, percent_hire=None, unit=None, hist_start=None, hist_end=None):\n", " \n", " hist_diff = (datetime.datetime.strptime(hist_end, '%Y-%m-%d') - datetime.datetime.strptime(hist_start, '%Y-%m-%d')).days\n", " t = 0\n", "\n", " starts = []\n", " ends = []\n", "\n", " w = 365\n", " print(hist_diff)\n", " while t < hist_diff:\n", " print(t)\n", " # initialising dataframe\n", " if t == 0 and hist_diff>w:\n", " diff_end = datetime.datetime.strftime(datetime.datetime.strptime(hist_start, '%Y-%m-%d') + pd.Timedelta(w, unit='days'), '%Y-%m-%d')\n", " hist_df = fetch_historical_contracts(access_token, contract=contract, unit=unit, start=hist_start, end=diff_end, format='csv')\n", "\n", " starts.append(hist_start)\n", " ends.append(diff_end)\n", " \n", " elif t==0 and hist_diff<=w:\n", " hist_df = fetch_historical_contracts(access_token, contract=contract, unit=unit, start=hist_start, end=hist_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(hist_start, '%Y-%m-%d') + pd.Timedelta(t+1, unit='days'), '%Y-%m-%d')\n", " diff_end = datetime.datetime.strftime(datetime.datetime.strptime(diff_start, '%Y-%m-%d') + pd.Timedelta(w, unit='days'), '%Y-%m-%d')\n", " historical_addition = fetch_historical_contracts(access_token, contract=contract, unit=unit, start=diff_start, end=diff_end, format='csv')\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(hist_start)\n", " ends.append(diff_end)\n", " else:\n", " diff_start = datetime.datetime.strftime(datetime.datetime.strptime(hist_start, '%Y-%m-%d') + pd.Timedelta(t+1, unit='days'), '%Y-%m-%d')\n", " diff_end = datetime.datetime.strftime(datetime.datetime.strptime(diff_start, '%Y-%m-%d') + pd.Timedelta(hist_diff-t, unit='days'), '%Y-%m-%d')\n", " historical_addition = fetch_historical_contracts(access_token, contract=contract, unit=unit, start=diff_start, end=diff_end, format='csv')\n", " hist_df = pd.concat([hist_df, historical_addition])\n", " starts.append(hist_start)\n", " ends.append(diff_end)\n", " \n", " #looping by year\n", " t += w\n", "\n", " for c in list(hist_df.columns)[13:]:\n", " hist_df[c] = pd.to_numeric(hist_df[c])\n", " hist_df['ReleaseDate'] = pd.to_datetime(hist_df['ReleaseDate'])\n", "\n", " return hist_df" ] }, { "cell_type": "markdown", "id": "c6f3a7d5", "metadata": {}, "source": [ "# 5. Calling the Historical Data" ] }, { "cell_type": "code", "execution_count": null, "id": "d6010f4f", "metadata": {}, "outputs": [], "source": [ "# Calling the extended historical data function\n", "\n", "start = '2026-01-01'\n", "today = datetime.date.today().strftime('%Y-%m-%d')\n", "\n", "tsab = available_df[available_df[\"name\"] == 'Sabine Pass'][\"uuid\"].iloc[0]\n", "\n", "# Sabine Pass (NEA via COGH) Arb Breakeven\n", "sabcogh_df = fetch_breakevens(access_token, tsab, via='cogh', breakeven='jkm-ttf', format='csv')\n", "\n", "# Sabine Pass Arb (NEA via Panama Canal) Breakeven\n", "sabpan_df = fetch_breakevens(access_token, tsab, via='panama', breakeven='jkm-ttf', format='csv')\n", "\n", "# JKM-TTF prices\n", "jkmttf = loop_historical_jkmttf(access_token, contract='jkm-ttf', unit='usd-per-mmbtu', hist_start=start, hist_end=today)\n", "\n", "sabcogh_df.head(5)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "8301f521", "metadata": {}, "outputs": [], "source": [ "# Combining the contract data & the breakevens data into a single dataframe\n", "\n", "# listing all breakevens Dataframes in a list\n", "break_dataframes = [sabcogh_df, sabpan_df]\n", "break_names = ['Sabine Pass (COGH)', 'Sabine Pass (Panama)']\n", "\n", "# initialising dataframe with the contract data\n", "combined_df = jkmttf.copy()\n", "combined_df = combined_df.rename(columns={'Value':'ContractValue'})\n", "\n", "# merging with the breakevens dataframes\n", "dc = 0\n", "for df in break_dataframes:\n", " print(break_names[dc])\n", " df = df.rename(columns={'JKMTTFSpreadBreakeven':break_names[dc]})\n", " combined_df = pd.merge(combined_df, df[['ReleaseDate', 'DeliveryMonthIndex', break_names[dc]]], \n", " left_on=['ReleaseDate', 'PeriodIndex'], right_on=['ReleaseDate', 'DeliveryMonthIndex'], how='inner')\n", " dc+=1\n", "\n", "combined_df = combined_df[['ReleaseDate', 'PeriodType', 'PeriodFrom','PeriodName','PeriodIndex', 'Unit', 'ContractValue'] + break_names]\n", "combined_df['PeriodFrom'] = pd.to_datetime(combined_df['PeriodFrom'])\n", "\n", "# Filtering out quarters, seasons and Cal data where arb breakeven levels are not available\n", "final_df = combined_df[combined_df['PeriodType'] == 'month'].copy()\n", "\n", "# creating columns to show the difference between the Contract price and the Breakeven levels\n", "final_df['Sabine Pass (COGH) - Breakeven Diff'] = final_df['ContractValue'] - final_df['Sabine Pass (COGH)']\n", "final_df['Sabine Pass (Panama) - Breakeven Diff'] = final_df['ContractValue'] - final_df['Sabine Pass (Panama)']" ] }, { "cell_type": "code", "execution_count": null, "id": "b90cd733", "metadata": {}, "outputs": [], "source": [ "final_df.head(5)" ] }, { "cell_type": "markdown", "id": "ec42bfbf", "metadata": {}, "source": [ "# 6. Plotting\n", "\n", "## 6.1. Plotting Latest Forward Curve" ] }, { "cell_type": "code", "execution_count": null, "id": "ac0646ea", "metadata": {}, "outputs": [], "source": [ "# create dataframe by filtering combined_df\n", "latest_df = final_df[final_df['ReleaseDate'] == final_df['ReleaseDate'].max()]\n", "\n", "latest_df" ] }, { "cell_type": "code", "execution_count": null, "id": "2805f55e", "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "\n", "sns.set_style('whitegrid')\n", "\n", "fig, ax = plt.subplots(figsize=(14,6))\n", "\n", "# Plotting a thicker y=0 axis line\n", "ax.hlines(0, latest_df['PeriodFrom'].iloc[-1] + pd.Timedelta(10, unit='day'), \n", " latest_df['PeriodFrom'].iloc[0] - pd.Timedelta(10, unit='day'), color='grey', alpha=0.85, zorder=0)\n", "\n", "# Plotting JKM-TTF forward Curve & Arb Breakevens\n", "ax.plot(latest_df['PeriodFrom'], latest_df['ContractValue'], color='#dc853f', label = 'JKM-TTF')\n", "ax.plot(latest_df['PeriodFrom'], latest_df['Sabine Pass (COGH)'], color='#008bcc', label='Sabine Pass (via COGH) Arb Breakeven')\n", "ax.plot(latest_df['PeriodFrom'], latest_df['Sabine Pass (Panama)'], color='#008e74', label='Sabine Pass (via Panama) Arb Breakeven')\n", "\n", "# shading green when the US arb is open (JKM-TTF > Sabine Pass Breakeven)\n", "ax.fill_between(latest_df['PeriodFrom'], latest_df['ContractValue'], latest_df['Sabine Pass (COGH)'], \n", " where=(latest_df['Sabine Pass (COGH) - Breakeven Diff'] > 0), color='mediumseagreen', alpha=0.2)\n", "\n", "# shading red when the US Arb (COGH) is closed (JKM-TTF < US Arb (COGH) Breakeven)\n", "ax.fill_between(latest_df['PeriodFrom'], latest_df['Sabine Pass (Panama)'], latest_df['ContractValue'], \n", " where=(latest_df['Sabine Pass (Panama) - Breakeven Diff'] < 0), color='red', alpha=0.1)\n", "\n", "plt.xlim([latest_df['PeriodFrom'].iloc[0]-pd.Timedelta(10, unit='day'), latest_df['PeriodFrom'].iloc[-1]+pd.Timedelta(10, unit='day')])\n", "\n", "plt.legend(loc='lower left')" ] }, { "cell_type": "markdown", "id": "a9600095", "metadata": {}, "source": [ "## 6.2 Plotting Historical Evolution of a Contract Month" ] }, { "cell_type": "code", "execution_count": null, "id": "29bc0ed9", "metadata": {}, "outputs": [], "source": [ "month = 'Dec26'\n", "\n", "month_df = final_df[final_df['PeriodName'] == month]" ] }, { "cell_type": "code", "execution_count": null, "id": "1f6fe8db", "metadata": {}, "outputs": [], "source": [ "fig, ax2 = plt.subplots(figsize=(14,6))\n", "\n", "# Plotting a thicker y=0 axis line\n", "ax2.hlines(0, month_df['ReleaseDate'].iloc[-1] + pd.Timedelta(10, unit='day'), \n", " month_df['ReleaseDate'].iloc[0] - pd.Timedelta(10, unit='day'), color='grey', alpha=0.85, zorder=0)\n", "\n", "# Plotting JKM-TTF forward Curve & Arb Breakevens\n", "ax2.plot(month_df['ReleaseDate'], month_df['ContractValue'], color='#dc853f', label = 'JKM-TTF')\n", "ax2.plot(month_df['ReleaseDate'], month_df['Sabine Pass (COGH)'], color='#008bcc', label='Sabine Pass (via COGH) Arb Breakeven')\n", "ax2.plot(month_df['ReleaseDate'], month_df['Sabine Pass (Panama)'], color='#008e74', label='Sabine Pass (via Panama) Arb Breakeven')\n", "\n", "# shading green when the US arb is open (JKM-TTF > Sabine Pass Breakeven)\n", "ax2.fill_between(month_df['ReleaseDate'], month_df['ContractValue'], month_df['Sabine Pass (COGH)'], \n", " where=(month_df['Sabine Pass (COGH) - Breakeven Diff'] > 0), color='mediumseagreen', alpha=0.2)\n", "\n", "# shading red when the US Arb (COGH) is closed (JKM-TTF < US Arb (COGH) Breakeven)\n", "ax2.fill_between(month_df['ReleaseDate'], month_df['Sabine Pass (Panama)'], month_df['ContractValue'], \n", " where=(month_df['Sabine Pass (Panama) - Breakeven Diff'] < 0), color='red', alpha=0.1)\n", "\n", "plt.xlim([month_df['ReleaseDate'].iloc[0]-pd.Timedelta(10, unit='day'), month_df['ReleaseDate'].iloc[-1]+pd.Timedelta(10, unit='day')])\n", "\n", "plt.legend(loc='upper left')" ] } ], "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 }