Visualising Forex Data Using Python



Historical forex data is crucial for identifying trends, assessing past performance, and making informed predictions in currency markets. Visualizing this data enhances analysis by clearly displaying price movements and patterns, aiding in better decision-making for traders and analysts.

This tutorial will guide you through retrieving historical currency data using the TraderMade API and visualizing it in a candlestick chart format with Plotly. Candlestick charts are popular in financial analysis because they provide a clear view of price movements, including open, high, low, and close prices for a specific period. We will use the EUR/USD currency pair data over a specified date range.

By the end of this tutorial, you'll be able to:

  • Use Python to make API requests for historical data.
  • Format and process JSON data into a data frame.
  • Create an interactive candlestick chart for financial analysis using Plotly.

Prerequisites

Before you begin, ensure you have the following:

1. Basic Python Knowledge: Familiarity with Python programming, especially with functions and error handling, will be helpful.

2. TraderMade API Key: Access to the "https://tradermade.com/dasard" for an API key. Register at TraderMade to obtain a free API key, which you'll use in the tutorial.

3. Required Libraries Installed

requests: To install requests, use the following command,

pip install requests

This library enables you to make HTTP requests to the API.

pandas: To install pandas, use the following command,

pip install pandas

Pandas will be used to structure and manipulate the API data in a tabular format.

plotly: to install plotly, use the following command

pip install plotly

This library helps create interactive charts, specifically a candlestick chart, in this tutorial.

Example

Import Required Libraries

These libraries are essential:

  • requests: To make HTTP requests to the TraderMade API.
  • pandas: To structure and manipulate the data fetched from the API.
  • datetime: For date formatting and conversion.
  • plotly.graph_objects: This is used to create visualizations, specifically a candlestick chart.
import requests
import pandas as pd
from datetime import datetime
import plotly.graph_objects as go

Setting Up the API Key and Base URL

To access data, use your TraderMade API key and the base URL for historical data. Make sure to replace 'KEY'' with your actual API key.

API_KEY = 'KEY' # Replace with your TraderMade API Key
BASE_URL = 'https://marketdata.tradermade.com/api/v1/historical'

Define Parameters

Set the currency pair and the date range for the historical data you wish to retrieve.
symbol = 'EURUSD' # For EUR/USD currency pair
start_date = '01-01-2023' # Start date in DD-MM-YYYY format
end_date = '31-01-2023' # End date in DD-MM-YYYY format

Define a Date Conversion Function

The API expects dates in the YYYY-MM-DD format, so a helper function converts the DD-MM-YYYY input format.
def convert_date_to_api_format(date_str):
    return datetime.strptime(date_str, '%d-%m-%Y').strftime('%Y-%m-%d')

Fetch Historical Data Function

This function retrieves the data from the API.
def fetch_historical_data(symbol, start_date, end_date):
    # Convert date formats
    api_start_date = convert_date_to_api_format(start_date)
    api_end_date = convert_date_to_api_format(end_date)
    
    params = {
        'currency': symbol,
        'date': api_start_date, # Starting date
        'end_date': api_end_date, # Ending date
        'api_key': API_KEY
    }
    
    response = requests.get(BASE_URL, params=params)
    
    # Check if the request was successful
    if response.status_code != 200:
        print(f"Error: Received status code {response.status_code}")
        print("Response:", response.json())
        raise Exception("Failed to fetch data from TraderMade API")
    
    # Log raw response for reference
    data = response.json()
    print("Raw API Response:", data)
    
    # Check for the 'quotes' field in response
    if 'quotes' not in data:
        print("Error: 'quotes' field not found in response")
        print("Response:", data)
        raise KeyError("'quotes' field missing from API response")
    
    # Convert the 'quotes' field to DataFrame
    df = pd.DataFrame(data['quotes'])
    print("DataFrame structure:\n", df.head())
    
    # Handle date column
    if 'date' in data:
        df['date'] = data['date']
    else:
        # Estimate dates if only one is provided
        df['date'] = pd.date_range(start=api_start_date, periods=len(pdf), freq='D')
    
    # Ensure the date column is datetime
    df['date'] = pd.to_datetime(df['date'])
    return df

Fetch and Display Data

Use the function to get data, ensuring the structure is ready for plotting.

df = fetch_historical_data(symbol, start_date, end_date)

Check Required Columns

A candlestick chart needs 'open', 'high', 'low', and 'close' columns. Validate these are present.

required_columns = {'open', 'high', 'low', 'close'}
if not required_columns.issubset(df.columns):
    missing_cols = required_columns - set(df.columns)
    raise ValueError(f"Missing columns in data for candlestick chart: {missing_cols}")

Create and Customize the Candlestick Chart

Now that you have the data, you can visualize it with Plotly.

fig = go.Figure(data=[go.Candlestick(
    x=df['date'],
    open=df['open'],
    high=df['high'],
    low=df['low'],
    close=df['close'],
    name=f'{symbol} OHLC'
)])
fig.update_layout(
    title=f'{symbol} Candlestick Chart from {start_date} to {end_date}',
    xaxis_title='Date',
    yaxis_title='Price',
    xaxis_rangeslider_visible=False
)
fig.show()

Handle Errors

If an error occurs during the above steps, it will be caught and printed to help diagnose the issue.

except Exception as e:
    print(f"An error occurred: {e}")

Conclusion

With this setup, you can easily modify the symbol or date range and visualize historical data for various currency pairs using the TraderMade API. If applying this to larger projects, remember to handle API keys securely and review API usage limitations in the "https://tradermade.com/docs/restful-api" documentation.

naga chitrika
naga chitrika

Bridging the gap between technology and storytelling

Updated on: 2024-11-15T15:44:58+05:30

270 Views

Kickstart Your Career

Get certified by completing the course

Get Started