Historical foreign exchange data is essential for traders, developers, financial analysts, and quantitative researchers. Whether you are building a trading bot, testing a strategy, or studying currency market movements, having reliable historical price information makes your work easier.
Instead of manually collecting exchange rates, developers can use a forex historical data API to retrieve currency prices programmatically and store them in CSV files. Python makes this process straightforward with libraries such as requests and pandas.
In this tutorial, we will explain how to retrieve historical forex prices, process the response, convert timestamps, and export the results into a CSV file. We will also explore how iTick can help developers access forex market data through its API infrastructure.
Why Download Historical Forex Data?
Historical forex data provides a record of currency price movements over a selected period. It allows traders and developers to examine market behavior without manually reviewing charts.
Common applications include:
- Strategy backtesting: Evaluate trading strategies against historical price movements.
- Technical analysis: Calculate indicators such as RSI, MACD, and moving averages.
- Machine learning: Prepare datasets for currency price prediction experiments.
- Risk analysis: Study volatility, drawdowns, and historical price fluctuations.
- Research: Compare currency pairs and identify long-term market patterns.
CSV files are particularly useful because they can be opened in Excel, imported into Python, or processed using data analysis tools.
1. Choosing a Forex Data API
Before writing a Python script, you need a data provider that supports historical currency prices and structured responses.
A useful provider should offer:
- Major currency pairs such as EUR/USD, GBP/USD, and USD/JPY.
- Historical OHLC prices.
- Multiple time intervals, including minute, hourly, daily, weekly, and monthly candles.
- Timestamp information for every candle.
- API authentication and predictable request limits.
- Data suitable for exporting into CSV files.
The iTick platform provides REST API access to forex K-line data, including opening, high, low, and closing prices. Its documentation also describes historical data retrieval using an end-time timestamp for backward pagination.
iTick+1
2. Understanding Forex OHLC Data
Most historical forex datasets use the OHLC format.
| Field | Meaning |
| Open | First recorded price during the interval |
| High | Highest price during the interval |
| Low | Lowest price during the interval |
| Close | Last recorded price during the interval |
| Volume | Reported transaction volume, where available |
| Time | Timestamp associated with the candle |
For example, a one-hour EUR/USD candle contains the opening price, highest price, lowest price, and closing price for that hour.
These values are useful for creating candlestick charts, calculating technical indicators, and evaluating trading strategies.
3. Getting Started with iTick
To retrieve currency market history, follow these steps:
- Visit iTick’s official website.
- Create an account and access your dashboard.
- Obtain your API token.
- Review the Forex K-line API documentation.
- Select the currency pair and candle interval you want to download.
The forex REST endpoint is:
The API uses GET requests and requires a token in the request headers.
The main parameters are:
| Parameter | Description | Example |
| region | Market region | GB |
| code | Currency pair | EURUSD |
| kType | Candle interval | 8 |
| limit | Number of records | 500 |
| et | End timestamp in milliseconds | Optional |
Supported interval codes include:
- 1 – 1 minute
- 2 – 5 minutes
- 3 – 15 minutes
- 4 – 30 minutes
- 5 – 60 minutes
- 8 – Daily
- 9 – Weekly
- 10 – Monthly
The API documentation provides these interval mappings and request parameters.
iTick+1
4. Installing Python Libraries
Python provides a convenient way to download, organize, and export financial data.
Install the required libraries using pip:
pip install requests pandas
The libraries serve different purposes:
- requests sends HTTP requests to the API.
- pandas organizes price records into a DataFrame.
- Python’s built-in datetime functionality helps convert timestamps into readable dates.
You do not need a complicated development environment. A standard Python installation, an API token, and an internet connection are enough to get started.
5. Python Script to Download Forex Data as CSV
The following example retrieves EUR/USD historical candles and saves them in a CSV file.
The script also handles API errors, converts timestamps, and organizes the downloaded prices into readable columns.
Python example:
import requestsimport pandas as pd# Your iTick API tokenAPI_TOKEN = “YOUR_API_TOKEN”# Forex API endpointURL = “https://api.itick.org/forex/kline”# Request parametersparams = { “region”: “GB”, “code”: “EURUSD”, “kType”: 8, # Daily candles “limit”: 500}headers = { “accept”: “application/json”, “token”: API_TOKEN}try: response = requests.get( URL, params=params, headers=headers, timeout=30 ) response.raise_for_status() result = response.json() if result.get(“code”) != 0: raise ValueError(
Replace YOUR_API_TOKEN with your actual API token before running the program.
Expected output
The script creates a file named:
EURUSD_historical_data.csv
The file contains timestamp, open, high, low, close, volume, and turnover fields when supplied by the API.
6. Downloading Larger Historical Datasets
The previous script downloads one batch of records. However, if you need several years of forex history, you may need multiple API requests.
The iTick API supports an et parameter that allows developers to retrieve earlier records by passing an end timestamp.
The following example demonstrates backward pagination:
import requestsimport pandas as pdimport timeAPI_TOKEN = “YOUR_API_TOKEN”URL = “https://api.itick.org/forex/kline”headers = { “accept”: “application/json”, “token”: API_TOKEN}params = { “region”: “GB”, “code”: “EURUSD”, “kType”: 8, “limit”: 500}all_data = []end_time = Nonewhile True: if end_time is not None: params[“et”] = end_time response = requests.get( URL, params=params, headers=headers, timeout=30 ) response.raise_for_status()
This approach helps build larger datasets without manually downloading every batch.
For a production download, also implement retry handling, rate-limit handling, and a date-range stopping condition. Check the API’s pagination behavior to ensure that each subsequent request returns earlier records without gaps.
7. Selecting Different Forex Currency Pairs
You can use the same script for other currency pairs by changing the code parameter.
Examples include:
| Currency pair | Description |
| EURUSD | Euro / US Dollar |
| GBPUSD | British Pound / US Dollar |
| USDJPY | US Dollar / Japanese Yen |
| USDCHF | US Dollar / Swiss Franc |
| AUDUSD | Australian Dollar / US Dollar |
| USDCAD | US Dollar / Canadian Dollar |
For example, to download GBP/USD data, change:
“code”: “GBPUSD”
You can also change kType to retrieve hourly, weekly, or monthly candles.
8. Analyzing Your Downloaded CSV File
Once your CSV file is ready, you can use pandas to perform basic financial analysis.
For example, calculate daily percentage changes:
import pandas as pddf = pd.read_csv(“EURUSD_historical_data.csv”)df[“daily_return”] = ( df[“close”].pct_change() * 100)print(df[[“time”, “close”, “daily_return”]].tail())df.to_csv( “EURUSD_analysis.csv”, index=False)
You can also calculate moving averages:
df[“SMA_20”] = df[“close”].rolling(20).mean()df[“SMA_50”] = df[“close”].rolling(50).mean()print(df.tail())
These calculations can help identify historical price trends and compare short-term and long-term market movements.
9. Common Problems When Downloading Forex Data
Even a simple API integration can encounter technical issues. Understanding common problems helps maintain a reliable data collection process.
Invalid API token: Check that your token is correct and has access to the requested market data.
Incorrect currency pair: Verify the symbol and region parameters before sending a request.
Empty API response: The requested interval, market, or historical period may not have available records.
Rate-limit errors: Reduce request frequency and implement retry logic when the provider returns a rate-limit response.
Incorrect timestamps: API timestamps are provided in milliseconds. Convert them using unit=”ms” and retain UTC for consistent analysis.
Missing or duplicate records: Sort data chronologically, remove duplicates, and check timestamp continuity before using the dataset for backtesting.
10. Why Use iTick for Forex Historical Data?
Choosing a reliable market data provider is important when developing financial applications.
iTick offers developers a unified market data infrastructure covering forex, stocks, indices, futures, funds, and cryptocurrencies.
Its forex data services provide several useful capabilities:
- REST API access to currency market data.
- Historical K-line data with multiple intervals.
- Standardized OHLC price fields.
- JSON responses suitable for Python processing.
- WebSocket access for real-time forex updates.
- Support for multiple currency pairs.
The platform also provides documentation and Python integration examples, helping developers connect market data to their applications.
iTick+2
For developers building historical analysis tools, the iTick service can be a practical option for retrieving forex prices and converting them into structured datasets.
You can explore the iTick Forex API to review its available data services and integration options.
11. Best Practices for Working with Historical Forex Data
Before using downloaded data in a trading system or research project, consider these practices:
- Check data consistency: Make sure timestamps and price values are valid.
- Use UTC timestamps: Avoid timezone confusion when comparing different currency pairs.
- Store original datasets: Keep an unchanged copy of the downloaded CSV files.
- Handle missing values: Identify incomplete candles before calculating indicators.
- Avoid look-ahead bias: Use only information that would have been available at the time of each historical trade.
- Check data coverage: Confirm historical availability and interval support for each currency pair.
- Review licensing: Verify whether your subscription permits commercial use or redistribution.
Forex markets operate across different trading sessions, and historical datasets may have gaps around weekends and holidays. Such gaps are not necessarily data errors.
Conclusion
Downloading forex prices into CSV files with Python is a straightforward process when you have a suitable API and the right libraries. Using requests and pandas, you can retrieve historical currency prices, convert timestamps, organize OHLC records, and create datasets for financial research.
A well-designed forex historical data api integration can also support automated data collection, technical analysis, machine learning experiments, and trading strategy backtesting.
Whether you are developing a personal trading tool or a professional financial application, combining Python with a structured market data provider makes historical forex analysis more efficient.
Explore iTick to learn more about forex market data, API integration, and historical price retrieval.
Frequently Asked Questions
1. How can I download historical forex data using Python?
You can use Python’s requests library to retrieve historical currency prices from a REST API. Then use pandas to convert the JSON response into a DataFrame and export it as a CSV file.
2. Which Python libraries are needed for forex data downloads?
The two main libraries are requests for API communication and pandas for organizing and exporting financial datasets.
3. Can I download EUR/USD historical prices into CSV?
Yes. Select EURUSD as the currency pair, request the desired candle interval, and save the returned records using pandas to_csv().
4. What is the difference between tick data and OHLC data?
Tick data represents individual market events, while OHLC data summarizes price movements over a defined period using opening, high, low, and closing prices.
5. Can historical forex data be used for backtesting?
Yes. Historical price records are commonly used to evaluate trading strategies, calculate technical indicators, study volatility, and test algorithmic trading systems. However, results depend on data quality and realistic trading-cost assumptions.
6. Does iTick support different forex time intervals?
Yes. Its forex K-line API documents intervals ranging from one-minute candles to monthly candles, subject to market and subscription availability.