domenica 6 agosto 2023

Grafico MACD e prezzo


import requests
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from datetime import datetime

def get_binance_data(symbol, interval, limit):
    url = f"https://api.binance.com/api/v3/klines?symbol={symbol}&interval={interval}&limit={limit}"
    response = requests.get(url)
    data = response.json()
    df = pd.DataFrame(data)
    df.columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'number_of_trades', 'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore']
    df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
    df['close'] = df['close'].astype(float)
    return df

def calculate_moving_average(data, window):
    return data['close'].rolling(window=window).mean()

def calculate_macd(data, fast_period, slow_period, signal_period):
    macd = data['close'].ewm(span=fast_period, adjust=False).mean() - data['close'].ewm(span=slow_period, adjust=False).mean()
    signal = macd.ewm(span=signal_period, adjust=False).mean()
    histogram = macd - signal
    return macd, signal, histogram

def plot_chart(data, ma_50, ma_99, macd, signal, histogram):
    fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(12, 8))

    ax1.plot(data['timestamp'], data['close'], label='Close')
    ax1.plot(data['timestamp'], ma_50, label='MA 50')
    ax1.plot(data['timestamp'], ma_99, label='MA 99')
    ax1.legend()

    ax2.plot(data['timestamp'], macd, label='MACD')
    ax2.plot(data['timestamp'], signal, label='Signal')
    ax2.bar(data['timestamp'], histogram, label='Histogram', color='gray')
    ax2.legend()

    plt.xlabel('Timestamp')
    plt.show()

symbol = 'BTCUSDT'
interval = '1d'
limit = 500

data = get_binance_data(symbol, interval, limit)
ma_50 = calculate_moving_average(data, 50)
ma_99 = calculate_moving_average(data, 99)
macd, signal, histogram = calculate_macd(data, 12, 26, 9)

plot_chart(data, ma_50, ma_99, macd, signal, histogram)

Nessun commento:

Posta un commento