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 DataFrame
  • 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 TraderMade dashboard 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.

Complete Implementation Example

Import Required Libraries

These libraries are essential for our forex data visualization:

  • 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: To create interactive candlestick charts
import requests
import pandas as pd
from datetime import datetime
import plotly.graph_objects as go

Complete Forex Data Visualization Script

Here's the complete implementation that fetches forex data and creates a candlestick chart ?

import requests
import pandas as pd
from datetime import datetime
import plotly.graph_objects as go

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

# Parameters
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

def convert_date_to_api_format(date_str):
    """Convert DD-MM-YYYY format to YYYY-MM-DD format for API"""
    return datetime.strptime(date_str, '%d-%m-%Y').strftime('%Y-%m-%d')

def fetch_historical_data(symbol, start_date, end_date):
    """Fetch historical forex data from TraderMade API"""
    try:
        # 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,
            'end_date': api_end_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")
        
        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:
            # Generate date range if not provided
            df['date'] = pd.date_range(start=api_start_date, periods=len(df), freq='D')
        
        # Ensure the date column is datetime
        df['date'] = pd.to_datetime(df['date'])
        return df
        
    except Exception as e:
        print(f"An error occurred while fetching data: {e}")
        return None

def create_candlestick_chart(df, symbol, start_date, end_date):
    """Create an interactive candlestick chart"""
    # Check required columns
    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 candlestick chart
    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()

# Main execution
if __name__ == "__main__":
    try:
        # Fetch the data
        df = fetch_historical_data(symbol, start_date, end_date)
        
        if df is not None and not df.empty:
            # Create and display the chart
            create_candlestick_chart(df, symbol, start_date, end_date)
        else:
            print("No data available to create the chart")
            
    except Exception as e:
        print(f"An error occurred: {e}")

Key Components Explained

Date Conversion Function: The API expects dates in YYYY-MM-DD format, so we convert from the more readable DD-MM-YYYY format.

Data Fetching: The function makes an HTTP GET request to the TraderMade API and handles potential errors like missing data fields or API failures.

Data Validation: Before creating the chart, we verify that all required columns (open, high, low, close) are present in the dataset.

Chart Creation: Using Plotly's Candlestick chart, we create an interactive visualization that displays price movements clearly.

Expected Output

When you run this script with a valid API key, you'll see:

  • Console output showing the raw API response and DataFrame structure
  • An interactive candlestick chart in your browser
  • The chart will display daily price movements for EUR/USD over the specified period

Conclusion

This tutorial demonstrates how to fetch and visualize forex data using Python, combining API requests with powerful data visualization. The candlestick chart provides traders with essential OHLC data in an easily interpretable format. Remember to secure your API keys and review the TraderMade API documentation for usage limitations.

naga chitrika
naga chitrika

Bridging the gap between technology and storytelling

Updated on: 2026-03-27T16:46:59+05:30

490 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements