Coins: 18,015
Exchanges: 1,481
Market Cap: $2.512T 3.4%
24h Vol: $92.196B
Gas: 0.954 GWEI
Go Ad-free
API
TABLE OF CONTENTS

How to Fetch Historical Crypto Data with Python

5.0
| by
Brian Lee
|
Edited by
Brian Lee
-

Building a backtesting engine, training a machine learning model, or conducting market research all share one common requirement. They all need reliable historical cryptocurrency data. Manually downloading CSV files works for one-off analyses, but it quickly becomes impractical when you need to automate data retrieval, refresh datasets regularly, or pull data for hundreds of tokens simultaneously.

In this guide, we'll build a Python toolkit that fetches historical price data from the CoinGecko API. You'll learn how to retrieve time-series data, query specific date ranges, fetch OHLC candlestick data, and export everything to CSV for further analysis.

How to Fetch Historical Crypto Data with Python


Prerequisites

Before diving into the code, ensure you have the following ready.

Install the dependencies with pip.

pip install -r requirements.txt

You'll also need a CoinGecko API key. If you don't have one, read this guide on how to get your free Demo API key. The free Demo plan provides sufficient capacity for learning, prototyping, and small-scale projects.


Setting Up Your API Configuration

Start by creating a configuration file that stores your API key securely and defines reusable helper functions.

Create a .env file in your project root to store your API key.

💡 Pro-Tip: Never commit your .env file to version control. Add it to your .gitignore to keep your API key secure.

How Do You Fetch Historical Cryptocurrency Price Data?

The /market_chart endpoint is your go-to option for fetching historical price data. It returns arrays of timestamps paired with prices, market caps, and trading volumes.

Running this script produces a DataFrame with a datetime index and columns for price, market cap, and volume.

CoinGecko API Historical Market Chart Endpoint Output Response Example

💡Pro-Tip: The API automatically optimizes data granularity based on your date range. Shorter ranges return finer intervals, while longer ranges return daily data points (recorded at 00:00 UTC). Paid plans offer manual interval control for more specific requirements.

How To Fetch Crypto Prices for a Specific Date Range?

When you need data for a precise date window rather than a rolling number of days, the /market_chart/range endpoint gives you that control. This endpoint uses UNIX timestamps instead of a days parameter.

This approach is particularly useful when you need data aligned to specific calendar periods for backtesting or reporting.

💡 Pro-Tip: Each cryptocurrency has a unique Coin ID on CoinGecko that is used across all API requests. These are often different from the coin's ticker symbol (for example, Bitcoin is bitcoin and Ethereum is ethereum). You can easily find the exact ID for any coin by referencing this master list of CoinGecko API IDs.

How To Get The Price Of Cryptocurrencies For A Specific Date?

Sometimes you only need the price at a single point in time. For example, you might want to know Ethereum's price on the day of The Merge or Bitcoin's price on a specific tax reporting date. The /history endpoint returns a snapshot of market data for any specific date.

Note: The date format for this endpoint is DD-MM-YYYY (European format), not the US format. This is important to keep in mind when constructing your requests.


How To Fetch OHLC Candlestick Data with Python?

For technical analysis and charting, OHLC (Open, High, Low, Close) data provides more detail than simple price points. The /ohlc endpoint returns candlestick data that you can use for building charts or calculating technical indicators.

This data is perfect for building candlestick charts or calculating technical indicators like RSI and Bollinger Bands. If you're interested in automating technical analysis, you might want to check out our guide on building automated crypto technical analysis tools with Python.

💡 Pro-Tip: When your project scales and requires deeper analysis, consider upgrading to an Analyst API plan. This unlocks explicit interval control and full historical data depth (going back to 2018 for hourly data, and all the way back to 2013 for daily data).

What's the Difference Between Market Chart and OHLC Data?

When fetching historical data, you might wonder whether to use the /market_chart or /ohlc endpoints.

The /market_chart endpoint returns general price, market cap, and volume data over time. The /ohlc endpoint specifically returns Open, High, Low, and Close prices for technical candlestick charting.

Use /market_chart for broad data science tasks, machine learning training, or general trend analysis. Use /ohlc when you need to build specific charting visuals or calculate technical indicators like Moving Averages or RSI.


How To Fetch Historical Data for Tokens by Contract Address?

Not all tokens have a CoinGecko ID that's easy to find. New tokens, meme coins, and lesser-known projects might be easier to query using their blockchain contract address. The contract address endpoint lets you fetch historical data using the token's address on its native blockchain.

Common platform IDs include ethereum for ERC-20 tokens, solana for SPL tokens, base for Base chain tokens, and polygon-pos for Polygon tokens. Refer to the CoinGecko API platform and network IDs sheet for the full list.


How To Export Historical Crypto Data to CSV?

After fetching your data, you'll often want to save it to a CSV file for use in other tools like Excel, R, or Jupyter notebooks.

To read the CSV back into pandas for analysis, use pd.read_csv() with the parse_dates parameter.

If you prefer working in spreadsheets, you can also learn how to pull crypto historical data directly into Google Sheets or follow our guide on importing live crypto prices into Excel.


Example: Fetching 5 Years of Bitcoin Data for Backtesting

Let's tie everything together with a practical example. This script calculates some basic metrics useful for backtesting and creates a simple visualization. Note that the free Demo plan allows you to retrieve up to 365 days of historical data.

To run this exact script and fetch five years of Bitcoin price data for deep backtesting, you will need to upgrade to at least an Analyst API plan (and use the x-cg-pro-api-key header). If you are using a Demo key, adjust the from date in the script to be within the last year.

This script demonstrates how to combine API data fetching with pandas analysis and matplotlib visualization, creating a complete workflow for historical cryptocurrency analysis and an example output that looks like this:

5 year historical bitcoin analysis chart with data fetched from CoinGecko API

If you want to take this further and build a full backtesting framework, check out our complete guide on building a crypto backtesting tool with Python.

Subscribe to CoinGecko API


Conclusion

You now have a complete Python toolkit for fetching historical cryptocurrency data programmatically. With these building blocks, you can automate data retrieval for backtesting strategies, train machine learning models on years of price history, or simply maintain accurate records for portfolio tracking and tax reporting.

The real power of programmatic access lies in its flexibility and reproducibility. Instead of manually downloading files, you can refresh your datasets with a single script, query custom date ranges on demand, and scale your analysis across thousands of tokens.

Ready to start building? Get your free Demo API key and try fetching historical data for your favorite cryptocurrency. When you're ready to dive deeper or need access to comprehensive historical data going back to 2013, consider upgrading to a paid API plan.

CoinGecko's Content Editorial Guidelines
CoinGecko’s content aims to demystify the crypto industry. While certain posts you see may be sponsored, we strive to uphold the highest standards of editorial quality and integrity, and do not publish any content that has not been vetted by our editors.
Learn more
Want to be the first to know about upcoming airdrops?
Subscribe to the CoinGecko Daily Newsletter!
Join 600,000+ crypto enthusiasts, traders, and degens in getting the latest crypto news, articles, videos, and reports by subscribing to our FREE newsletter.
Tell us how much you like this article!
Vote count: 2
Brian Lee
Brian Lee
Brian is a Growth Marketer at CoinGecko, helping developers, traders, and crypto businesses discover and use CoinGecko API to build, track, and scale smarter with real-time crypto market data.

Related Articles

Select Currency
Suggested Currencies
USD
US Dollar
IDR
Indonesian Rupiah
TWD
New Taiwan Dollar
EUR
Euro
KRW
South Korean Won
JPY
Japanese Yen
RUB
Russian Ruble
CNY
Chinese Yuan
Fiat Currencies
AED
United Arab Emirates Dirham
ARS
Argentine Peso
AUD
Australian Dollar
BDT
Bangladeshi Taka
BHD
Bahraini Dinar
BMD
Bermudian Dollar
BRL
Brazil Real
CAD
Canadian Dollar
CHF
Swiss Franc
CLP
Chilean Peso
CZK
Czech Koruna
DKK
Danish Krone
GBP
British Pound Sterling
GEL
Georgian Lari
HKD
Hong Kong Dollar
HUF
Hungarian Forint
ILS
Israeli New Shekel
INR
Indian Rupee
KWD
Kuwaiti Dinar
LKR
Sri Lankan Rupee
MMK
Burmese Kyat
MXN
Mexican Peso
MYR
Malaysian Ringgit
NGN
Nigerian Naira
NOK
Norwegian Krone
NZD
New Zealand Dollar
PHP
Philippine Peso
PKR
Pakistani Rupee
PLN
Polish Zloty
SAR
Saudi Riyal
SEK
Swedish Krona
SGD
Singapore Dollar
THB
Thai Baht
TRY
Turkish Lira
UAH
Ukrainian hryvnia
VEF
Venezuelan bolívar fuerte
VND
Vietnamese đồng
ZAR
South African Rand
XDR
IMF Special Drawing Rights
Cryptocurrencies
BTC
Bitcoin
ETH
Ether
LTC
Litecoin
BCH
Bitcoin Cash
BNB
Binance Coin
EOS
EOS
XRP
XRP
XLM
Lumens
LINK
Chainlink
DOT
Polkadot
YFI
Yearn.finance
SOL
Solana
Bitcoin Units
BITS
Bits
SATS
Satoshi
Commodities
XAG
Silver - Troy Ounce
XAU
Gold - Troy Ounce
Select Language
Popular Languages
EN
English
RU
Русский
DE
Deutsch
PL
język polski
ES
Español
VI
Tiếng việt
FR
Français
PT-BR
Português
All Languages
AR
العربية
BG
български
CS
čeština
DA
dansk
EL
Ελληνικά
FI
suomen kieli
HE
עִבְרִית
HI
हिंदी
HR
hrvatski
HU
Magyar nyelv
ID
Bahasa Indonesia
IT
Italiano
JA
日本語
KO
한국어
LT
lietuvių kalba
NL
Nederlands
NO
norsk
RO
Limba română
SK
slovenský jazyk
SL
slovenski jezik
SV
Svenska
TH
ภาษาไทย
TR
Türkçe
UK
украї́нська мо́ва
ZH
简体中文
ZH-TW
繁體中文
Welcome to CoinGecko
Welcome back!
Login or Sign up in seconds
or
Sign in with . Not you?
Forgot your password?
Didn't receive confirmation instructions?
Resend confirmation instructions
Password must contain at least 8 characters including 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character
By continuing, you acknowledge that you've read and agree fully to our Terms of Service and Privacy Policy.
Get Price Alerts with CoinGecko App
Forgot your password?
You will receive an email with instructions on how to reset your password in a few minutes.
Resend confirmation instructions
You will receive an email with instructions for how to confirm your email address in a few minutes.
Get the CoinGecko app.
Scan this QR code to download the app now App QR Code Or check it out in the app stores
Add NFT
CoinGecko
Better on the app
Real-time price alerts and a faster, smoother experience.
You’ve reached the limit.
Guest portfolios are limited to 10 coins. Sign up or log in to keep the coins listed below.