Reputation: 1
I got matplotlib to show the chart but the candles appear as black vertical lines, instead of green/red with open/high/low/close
The data is retrieved from Binance API and the chart picture come out ok, except for the vertical black lines.
Looking for help to see normal candles with open/high/low/close info.
import requests
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
# Binance API endpoint for Kline data
url = 'https://api.binance.com/api/v3/klines'
# Parameters for the API request
symbol = 'BTCUSDT'
interval = '1d'
limit = 200 # Number of Klines to retrieve (max: 1000)
# Prepare the request parameters
params = {
'symbol': symbol,
'interval': interval,
'limit': limit
}
# Send the GET request to the Binance API
response = requests.get(url, params=params)
data = response.json()
# Extracting the relevant data from the API response
timestamps = [entry[0] / 1000 for entry in data]
opens = [float(entry[1]) for entry in data]
highs = [float(entry[2]) for entry in data]
lows = [float(entry[3]) for entry in data]
closes = [float(entry[4]) for entry in data]
# Convert timestamps to readable dates
dates = [mdates.epoch2num(timestamp) for timestamp in timestamps]
# Plotting the candlestick chart
fig, ax = plt.subplots()
ax.xaxis_date()
candlestick_data = list(zip(dates, opens, highs, lows, closes))
ax.vlines(dates, lows, highs, color='black', linewidth=2)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
# Calculate the moving averages
moving_average_7 = np.convolve(closes, np.ones(7) / 7, mode='valid')
moving_average_20 = np.convolve(closes, np.ones(20) / 20, mode='valid')
moving_average_50 = np.convolve(closes, np.ones(50) / 50, mode='valid')
# Determine the corresponding dates for the moving averages
moving_average_dates_7 = dates[7 - 1:] # Subtract 1 to align the dates with moving average values
moving_average_dates_20 = dates[20 - 1:] # Subtract 1 to align the dates with moving average values
moving_average_dates_50 = dates[50 - 1:] # Subtract 1 to align the dates with moving average values
# Plotting the moving averages
ax.plot(moving_average_dates_7, moving_average_7, color='red', linewidth=1, label='7-day Moving Average')
ax.plot(moving_average_dates_20, moving_average_20, color='blue', linewidth=1, label='20-day Moving Average')
ax.plot(moving_average_dates_50, moving_average_50, color='orange', linewidth=1, label='50-day Moving Average')
# Calculate Bollinger Bands
period = 20 # Bollinger Bands period
std_dev = np.std(closes[-period:]) # Standard deviation for the period
middle_band = np.convolve(closes, np.ones(period) / period, mode='valid') # Middle band is the moving average
upper_band = middle_band + 2 * std_dev # Upper band is 2 standard deviations above the middle band
lower_band = middle_band - 2 * std_dev # Lower band is 2 standard deviations below the middle band
# Plotting the Bollinger Bands
ax.plot(dates[period - 1:], upper_band, color='purple', linestyle='--', linewidth=1, label='Upper Band')
ax.plot(dates[period - 1:], lower_band, color='purple', linestyle='--', linewidth=1, label='Lower Band')
# Add the last values of the indicators to the right axis
ax.text(1.02, 0.7, f'Last Price: {closes[-1]:.2f}', transform=ax.transAxes, color='black')
ax.text(1.02, 0.6, f'MA7: {moving_average_7[-1]:.2f}', transform=ax.transAxes, color='red')
ax.text(1.02, 0.5, f'MA20: {moving_average_20[-1]:.2f}', transform=ax.transAxes, color='blue')
ax.text(1.02, 0.4, f'MA50: {moving_average_50[-1]:.2f}', transform=ax.transAxes, color='orange')
plt.xticks(rotation=45)
plt.title(f'Kline Chart for {symbol} - {interval}')
plt.xlabel('Date')
plt.ylabel('Price (USDT)')
plt.legend()
plt.grid(True)
plt.show()
Upvotes: 0
Views: 123
Reputation: 13
Can you share an example of what you expected to produce? I can tell you the line that causes the candlesticks to be black is this one:
ax.vlines(dates, lows, highs, color='black', linewidth=2)
If you want to plot those lines in a different color you will need to modify the arguments to vlines
. A related question you may consider is how to plot candlesticks in python. They show a solutions in matplotlib, plotly, and other frameworks you may find helpful.
Upvotes: 1