Charting Historical FX Rates | A Developer's Guide with FinFeedAPI

Visualizing the movement of foreign exchange (FX) rates over time is a common feature in financial applications, trading platforms, and economic analysis tools. A simple line chart showing the historical trend of a currency pair like EUR/USD can provide immediate context about its performance.

This guide presents a method for using FinFeedAPI Currencies API to retrieve historical exchange rate data and plot it. You will see how to fetch a time series of data and use popular Python libraries to create a clean, informative chart.

This guide covers:

  • The API endpoint for fetching historical FX data.

  • Setting up a Python environment for the task.

  • Retrieving time-series data for a currency pair.

  • Processing the data with pandas.

  • Creating a line chart of currency trends with Matplotlib.

What you need:

  • Python 3.x installed.

  • Experience with pandas and matplotlib libraries.

  • Your personal FinFeedAPI key for the Currencies API.

1. The Historical Data Endpoint

The key to this process is the /v1/exchangerate/{base}/{quote}/history endpoint from the FinFeedAPI Historical FX service. This endpoint is built to supply time-series data.

Its main parameters are:

  • base & quote: The currency pair you want (e.g., EUR and USD).

  • time_start & time_end: The date range for your data.

  • period_id: The time interval for each data point (e.g., 1DAY, 1HRS, 1MIN).

  • limit: The maximum number of data points to return.

The data for each period is often supplied in an OHLC (Open, High, Low, Close) format, which is standard for financial charting. For a simple trend line, we will use the closing price (price_close).

2. Environment Setup

First, you need the api-bricks-fx-api-rest library. If it's not on your system, you can install it using pip.

pip install api-bricks-fx-api-rest

Next, set up your Python script by importing the necessary libraries and configuring the API client.

# Import libraries
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import api_bricks_fx_api_rest
from datetime import datetime

# --- API Configuration ---
# IMPORTANT: Replace "YOUR_API_KEY_HERE" with your actual key.
API_KEY = "YOUR_API_KEY_HERE"
api_client_config = api_bricks_fx_api_rest.Configuration()
api_client_config.api_key['Authorization'] = API_KEY
api_client = api_bricks_fx_api_rest.ApiClient(configuration=api_client_config)

# --- Plotting Configuration ---
plt.style.use('seaborn-v0_8-darkgrid')
plt.rcParams['figure.figsize'] = (15, 7)

This code prepares your environment by importing the tools and setting up the API client with your key.

3. Fetching Historical FX Data

Now, we will call the history endpoint to get daily data for the EUR/USD pair for the year 2024.

# Initialize the ExchangeRatesApi
exchange_rates_api = api_bricks_fx_api_rest.ExchangeRatesApi(api_client)

# Define parameters for the data request
base_currency = "EUR"
quote_currency = "USD"
start_time = "2024-01-01"
end_time = "2024-12-31"
period = "1DAY"
data_limit = 500 # Set a limit for the number of data points

print(f"Fetching historical data for {base_currency}/{quote_currency} from {start_time} to {end_time}...")

try:
    historical_data = exchange_rates_api.v1_exchangerate_base_quote_history_get(
        base=base_currency,
        quote=quote_currency,
        time_start=start_time,
        time_end=end_time,
        period_id=period,
        limit=data_limit
    )
    print(f"Successfully fetched {len(historical_data)} data points.")
except api_bricks_fx_api_rest.ApiException as e:
    print(f"API Exception occurred: {e}")
    historical_data = [] # Assign empty list on failure

This block makes the API call for the specified currency pair and date range. The response is a list of data points.

4. Preparing the Data

The API response needs to be converted into a format suitable for plotting. A pandas DataFrame is a good choice for this.

if historical_data:
    # Convert the list of objects to a pandas DataFrame
    history_df = pd.DataFrame.from_records([vars(d) for d in historical_data])

    # Convert the time period start column to datetime objects
    history_df['time_period_start'] = pd.to_datetime(history_df['time_period_start'])

    # Set the date column as the index of the DataFrame
    history_df = history_df.set_index('time_period_start')

    # Ensure the data is sorted by date
    history_df = history_df.sort_index()

    print("\nSample of prepared data:")
    print(history_df[['price_open', 'price_high', 'price_low', 'price_close']].head())
else:
    print("\nNo data to process.")
    history_df = pd.DataFrame() # Create empty DataFrame

This code creates a DataFrame, converts the date strings into datetime objects, and sets the date as the index, which is ideal for time-series plotting.

5. Creating the Trend Chart

With the data prepared, we can now use matplotlib to create a line chart of the closing prices.

if not history_df.empty:
    plt.figure(figsize=(15, 7))
    ax = plt.gca() # Get current axes

    # Plot the closing price
    ax.plot(history_df.index, history_df['price_close'], label=f'{base_currency}/{quote_currency} Close Price', color='mediumblue')

    # Formatting the plot
    ax.set_title(f'Historical Trend for {base_currency}/{quote_currency} in 2024', fontsize=16)
    ax.set_xlabel('Date', fontsize=12)
    ax.set_ylabel(f'Price ({quote_currency})', fontsize=12)
    ax.legend()
    ax.grid(True, linestyle='--', alpha=0.6)

    # Improve date formatting on the x-axis
    ax.xaxis.set_major_locator(mdates.MonthLocator())
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
    plt.xticks(rotation=45)

    plt.tight_layout()
    plt.show()
else:
    print("\nNo data available to plot.")

This final block generates the line chart, adding a title, labels, and grid for better readability. The date formatting on the x-axis is adjusted to show months clearly.

Final Thoughts

This guide showed a direct method for obtaining historical FX data and creating a trend chart. You can adapt this process for any currency pair, adjust the time frames, or use different intervals like hours or minutes. For more detailed visualizations, the OHLC data can also be used to create candlestick charts with libraries like mplfinance.

0
Subscribe to my newsletter

Read articles from Maciej Józefowicz directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Maciej Józefowicz
Maciej Józefowicz