# Create Python Cryptocurrency Charts with CoinAPI

Heres a step-by-step guide to creating a Python library that provides a lightweight and interactive charting solution for data visualization using CoinAPI data. This tutorial is dedicated to developers who want to build interactive cryptocurrency charts with Python and CoinAPI. Step 1: Set Up Your Project Start by setting up a new Python project. Create &hellip; <a href="https://api.blog.coinapi.io/2023/05/create-cryptocurrency-charts-python-coinapi-step-by-step-guide-developers/" class="more-link">Continue reading<span class="screen-reader-text"> &#8220;Create cryptocurrency charts with Python and CoinAPI&#8221;</span></a>

# Create Python Cryptocurrency Charts with CoinAPI

**_Here’s a step-by-step guide to creating interactive cryptocurrency charts with [Python](https://www.python.org/) and [CoinAPI](https://www.coinapi.io/products/market-data-api). This tutorial shows how to fetch historical OHLCV data from the CoinAPI Market Data REST API, convert it into a Pandas DataFrame, and visualize it as an interactive candlestick chart with Plotly._**

## Step 1: Set Up Your Project and API Key

Start by setting up a new Python project. Create a directory for your project and navigate to it in your terminal or command prompt.

You’ll also need a CoinAPI API key.

Create an account in the [API BRICKS Console](https://console.apibricks.io/), generate a CoinAPI Market Data API key, and use it to authenticate your requests. New users can start with **$25 in free credits** to test API calls.

For local development, it is better to store your API key as an environment variable instead of placing it directly in your Python source code.

For example:

```
export COINAPI_KEY="YOUR_API_KEY"
```

Then access it in Python:

```
import os

API_KEY = os.environ["COINAPI_KEY"]
```

Do not commit API keys to GitHub or expose them in frontend code.

## Step 2: Install Dependencies

To begin, install the packages required to retrieve, process, and visualize the data.

For this tutorial, you’ll need:

* `requests` for CoinAPI REST requests
* `pandas` for working with OHLCV data
* `plotly` for interactive charts

Install them using pip:

```
pip install requests pandas plotly
```

You do not need to connect separately to individual exchanges. CoinAPI provides standardized access to supported exchange data through its Market Data API.

## Step 3: Find a CoinAPI Symbol

Before requesting historical OHLCV data, you need a valid CoinAPI `symbol_id`.

CoinAPI uses standardized identifiers that specify the exchange, instrument type, and asset pair.

For example:

```
BITSTAMP_SPOT_BTC_USD
```

This identifies the BTC/USD spot market on Bitstamp.

You can discover supported symbols through the `/v1/symbols` endpoint:

```
curl -H "X-CoinAPI-Key: YOUR_API_KEY" \
"https://rest.coinapi.io/v1/symbols"
```

You can also query a specific identifier:

```
curl -H "X-CoinAPI-Key: YOUR_API_KEY" \
"https://rest.coinapi.io/v1/symbols?filter_symbol_id=BITSTAMP_SPOT_BTC_USD"
```

Using the complete `symbol_id` is important. The OHLCV endpoint expects an identifier such as `BITSTAMP_SPOT_BTC_USD`, rather than simply `BTC` or `BTC/USD`.

## Step 4: Fetch Historical OHLCV Data

Now create a file named `coinapi.py`.

This tutorial uses the CoinAPI **Market Data REST API** to retrieve historical OHLCV bars.

```
import os
import requests
import pandas as pd

API_KEY = os.environ["COINAPI_KEY"]
BASE_URL = "https://rest.coinapi.io/v1"


def get_historical_ohlcv(
    symbol_id,
    period_id="1DAY",
    time_start="2025-06-01T00:00:00",
    limit=100
):
    url = f"{BASE_URL}/ohlcv/{symbol_id}/history"

    headers = {
        "X-CoinAPI-Key": API_KEY
    }

    params = {
        "period_id": period_id,
        "time_start": time_start,
        "limit": limit
    }

    response = requests.get(
        url,
        headers=headers,
        params=params,
        timeout=30
    )

    if response.status_code == 429:
        raise RuntimeError(
            "Rate limit or quota exceeded. "
            "Check your usage in the API BRICKS Console."
        )

    response.raise_for_status()

    credits_used = response.headers.get("x-credits-used")
    if credits_used:
        print(f"Credits used: {credits_used}")

    data = response.json()

    if not data:
        raise RuntimeError(
            f"No OHLCV data returned for {symbol_id}."
        )

    df = pd.DataFrame(data)

    df["time_period_start"] = pd.to_datetime(
        df["time_period_start"]
    )

    return df
```

The request uses:

```
/v1/ohlcv/BITSTAMP_SPOT_BTC_USD/history
```

to fetch historical OHLCV bars for the selected market.

The response can include fields such as:

* `time_period_start`
* `time_period_end`
* `price_open`
* `price_high`
* `price_low`
* `price_close`
* `volume_traded`
* `trades_count`

When experimenting with REST requests, start with a relatively small `limit`. You can also inspect the `x-credits-used` response header when available to monitor API usage.

### A Note About CoinAPI OHLCV Data

OHLCV stands for **Open, High, Low, Close, and Volume**.

CoinAPI's OHLCV formation can use transaction and order book activity. If no trades occur during a period but the order book remains active, a bar can still be emitted with:

```
volume_traded = 0
trades_count = 0
```

This is useful to understand when interpreting periods with little or no trading activity.

## Step 5: Create the Cryptocurrency Chart

Next, create a separate file named `charting.py`.

Because we are working with OHLCV data, a candlestick chart is more informative than plotting only `price_close`.

```
import plotly.graph_objects as go


def generate_chart(df, symbol_id):
    fig = go.Figure(
        data=[
            go.Candlestick(
                x=df["time_period_start"],
                open=df["price_open"],
                high=df["price_high"],
                low=df["price_low"],
                close=df["price_close"],
                name=symbol_id
            )
        ]
    )

    fig.update_layout(
        title=f"{symbol_id} OHLCV",
        xaxis_title="Time",
        yaxis_title="Price",
        xaxis_rangeslider_visible=False
    )

    fig.show()
```

Plotly uses the CoinAPI fields `price_open`, `price_high`, `price_low`, and `price_close` to create each candle.

The result is an interactive chart that allows you to inspect historical BTC/USD price behavior directly in your browser.

### Advanced Charting Techniques

Once the basic candlestick chart is working, you can extend it with additional visualizations.

For example, you could add:

* Moving averages
* Trading volume
* Relative Strength Index (RSI)
* Bollinger Bands
* Multiple symbols
* Different OHLCV periods

Advanced charting techniques can help visualize trends, volatility, volume, and historical price behavior for research and strategy analysis.

For example, a simple moving average can be calculated directly with Pandas:

```
df["sma_20"] = df["price_close"].rolling(window=20).mean()
```

You could then add it to your Plotly chart:

```
fig.add_trace(
    go.Scatter(
        x=df["time_period_start"],
        y=df["sma_20"],
        name="20-period SMA"
    )
)
```

These indicators are analytical tools rather than predictions of future market behavior.

## Step 6: Put It All Together

Now create a `main.py` file and import the CoinAPI and charting functions:

```
from coinapi import get_historical_ohlcv
from charting import generate_chart

SYMBOL_ID = "BITSTAMP_SPOT_BTC_USD"

df = get_historical_ohlcv(
    symbol_id=SYMBOL_ID,
    period_id="1DAY",
    time_start="2025-06-01T00:00:00",
    limit=100
)

generate_chart(df, SYMBOL_ID)
```

Run the project:

```
python main.py
```

The script will:

1. Authenticate using your CoinAPI key.
2. Request historical OHLCV data for `BITSTAMP_SPOT_BTC_USD`.
3. Convert the response into a Pandas DataFrame.
4. Parse the CoinAPI timestamps.
5. Generate an interactive Plotly candlestick chart.

You can change `SYMBOL_ID`, `period_id`, `time_start`, and `limit` to explore different markets and historical periods.

## Cryptocurrency Data Charts with Python and CoinAPI

The example above demonstrates a basic way to combine Python, Pandas, Plotly, and CoinAPI.

Instead of retrieving generic “historical prices,” the application is specifically requesting **historical OHLCV bars** for a CoinAPI `symbol_id`.

This distinction becomes important as your application grows because CoinAPI provides several different types of market data, including trades, quotes, order books, OHLCV, metrics, and metadata.

For continuous **real-time charts**, CoinAPI WebSocket streams are more appropriate than repeatedly polling historical REST endpoints.

For large historical research datasets, [CoinAPI Flat Files](https://www.coinapi.io/products/flat-files) provides bulk access to historical trades, quotes, order books, and OHLCV.

## Production Tips

The example above is intentionally simple, but a production application should include a few additional safeguards.

* **Protect your API key.** Store it in an environment variable or secrets manager rather than hardcoding it into your application.
* **Handle API errors.** Check HTTP responses and implement appropriate handling for connection problems, invalid requests, and `429` responses.
* **Monitor usage.** When available, log the `x-credits-used` response header and monitor your consumption in the API BRICKS Console.
* **Cache historical data.** If the same historical period is used repeatedly, storing the result locally can prevent unnecessary API requests.
* **Use the right CoinAPI interface.** REST is useful for targeted historical requests. WebSocket or FIX is better suited to continuous real-time market data, while Flat Files is designed for bulk historical datasets.

## Start Building Your Cryptocurrency Chart

With a few Python packages and the CoinAPI Market Data REST API, you can retrieve historical OHLCV data and turn it into an interactive cryptocurrency chart.

From there, you can extend the project with volume charts, moving averages, additional symbols, technical indicators, or real-time WebSocket data.

Remember to replace `YOUR_API_KEY` with your own CoinAPI key when using the command-line examples. You can review current access and pricing on the [Market Data API pricing page](https://www.coinapi.io/products/market-data-api/pricing) and find endpoint details in the [CoinAPI documentation](https://docs.coinapi.io/).

_This tutorial is for educational purposes and is not investment advice._

#### More to read:

[**How to deploy a currency alerting pipeline with Quix and CoinAPI**](https://www.coinapi.io/blog/deploy-real-time-currency-alerting-pipeline)

[**CoinAPI Flat Files for bulk historical cryptocurrency data**](https://www.coinapi.io/products/flat-files)