Skip to content

Instantly share code, notes, and snippets.

@suissa
Created March 19, 2025 21:33
Show Gist options
  • Select an option

  • Save suissa/e3fc64b4d015850b642052a00f10f00c to your computer and use it in GitHub Desktop.

Select an option

Save suissa/e3fc64b4d015850b642052a00f10f00c to your computer and use it in GitHub Desktop.

Revisions

  1. suissa created this gist Mar 19, 2025.
    72 changes: 72 additions & 0 deletions volatilidade.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,72 @@
    import math
    import requests
    import sys

    def get_binance_data(symbol, interval):
    url = f"https://api.binance.com/api/v1/klines?symbol={symbol}&interval={interval}"
    try:
    response = requests.get(url)
    response.raise_for_status()
    data = response.json()
    except requests.exceptions.RequestException as e:
    raise Exception(f"Erro ao obter dados da Binance: {e}")

    result = []
    for d in data:
    open_time = int(d[0])
    open_price = d[1]
    high = d[2]
    low = d[3]
    close = d[4]
    volume = d[5]
    close_time = int(d[6])

    result.append({
    'OpenTime': open_time,
    'Open': open_price,
    'High': high,
    'Low': low,
    'Close': close,
    'Volume': volume,
    'CloseTime': close_time
    })
    return result

    def calculate_volatility(data):
    if len(data) < 2:
    return 0.0

    log_returns = []
    for i in range(1, len(data)):
    prev_close_str = data[i-1]['Close']
    curr_close_str = data[i]['Close']

    prev_close = float(prev_close_str)
    curr_close = float(curr_close_str)

    if prev_close == 0:
    continue

    log_return = math.log(curr_close / prev_close)
    log_returns.append(log_return)

    if not log_returns:
    return 0.0

    mean_return = sum(log_returns) / len(log_returns)
    variance = sum((r - mean_return) ** 2 for r in log_returns) / len(log_returns)
    volatility = math.sqrt(variance)
    return volatility

    if __name__ == "__main__":
    symbol = "BTCUSDT"
    interval = "5m"

    try:
    data = get_binance_data(symbol, interval)
    except Exception as e:
    print(f"Erro: {e}")
    sys.exit(1)

    volatility = calculate_volatility(data)
    print(f"A volatilidade intradiária (5min) do BTC/USD é: {volatility}")