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.

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.
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.

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.
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.
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:

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.
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.
Subscribe to the CoinGecko Daily Newsletter!
