![見出し画像](https://assets.st-note.com/production/uploads/images/161213919/rectangle_large_type_2_605d6ff5771d47411c6027cf248a7c8e.jpeg?width=1200)
pythonでBTCやETHのフィボナッチレベルを取得しよう
大口はフィボナッチを好むと聞いて.…
pythonコードコピペ用
APIキーの入力はしないで大丈夫
テキストファイルと画像ファイルで自分の決めたフォルダに保存されます。
import matplotlib.pyplot as plt
import pandas as pd
from binance.client import Client
# 日本語フォントの設定(Windows の場合)
plt.rcParams['font.family'] = 'MS Gothic'
# macOS の場合は以下を使用
# plt.rcParams['font.family'] = 'AppleGothic'
# Linux の場合は以下を使用
# plt.rcParams['font.family'] = 'Noto Sans CJK JP'
# Binance APIクライアントの初期化
client = Client(api_key='your_api_key', api_secret='your_api_secret') # APIキーとシークレットを設定してください
def fetch_ohlcv(symbol, timeframe):
try:
# Binance APIを利用してデータを取得
klines = client.get_klines(symbol=symbol, interval=timeframe)
df = pd.DataFrame(klines, 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)
df['high'] = df['high'].astype(float)
df['low'] = df['low'].astype(float)
return df
except Exception as e:
print(f"エラー: {symbol} の {timeframe} データを取得できませんでした。")
print(f"エラーメッセージ: {str(e)}")
return None
def plot_fibonacci_retracement(ax, df):
max_price = df['high'].max()
min_price = df['low'].min()
diff = max_price - min_price
levels = [max_price,
max_price - 0.236 * diff,
max_price - 0.382 * diff,
max_price - 0.5 * diff,
max_price - 0.618 * diff,
min_price]
for level in levels:
ax.axhline(level, linestyle='--', alpha=0.5, color='r')
ax.text(df['timestamp'].iloc[-1], level, f'{level:.2f}', color='black', fontsize=10, verticalalignment='center')
return levels
def plot_price_chart(symbol):
timeframes = ['1m', '15m', '1h', '4h', '12h', '1d', '1w', '1M']
titles = ['1分足', '15分足', '1時間足', '4時間足', '12時間足', '日足', '週足', '月足']
fig, axs = plt.subplots(4, 2, figsize=(20, 30))
fig.suptitle(f'{symbol} 価格チャート', fontsize=20, y=0.95)
fibonacci_data = {}
for i, (tf, title) in enumerate(zip(timeframes, titles)):
df = fetch_ohlcv(symbol, tf)
if df is not None:
ax = axs[i // 2, i % 2]
ax.plot(df['timestamp'], df['close'])
ax.set_title(title, fontsize=16, pad=24) # タイトルのフォントサイズを大きくし、上部の余白を増やす
ax.tick_params(axis='y', labelsize=16)
ax.tick_params(axis='x', rotation=45 , labelsize=16)
# 横線を薄く表示
ax.grid(axis='y', linestyle='--', alpha=0.5)
# フィボナッチリトレースメントをプロット
levels = plot_fibonacci_retracement(ax, df)
# フィボナッチレベルの価格を保存
fibonacci_data[title] = levels
plt.tight_layout()
plt.subplots_adjust(top=0.91, hspace=0.5) # 全体のタイトルとサブプロット間の余白を調整
# 画像ファイル名を設定
filename = f'{symbol}_price_chart.png'
# グラフを画像として保存
plt.savefig(filename, dpi=300, bbox_inches='tight')
# 保存完了メッセージを表示
print(f'画像が保存されました: {filename}')
plt.show()
# フィボナッチレベルの価格をテキストファイルに出力
with open(f'{symbol}_fibonacci_levels.txt', 'w', encoding='utf-8') as f:
for timeframe, levels in fibonacci_data.items():
f.write(f'{timeframe}:\n')
for i, level in enumerate(levels):
f.write(f' Level {i+1}: {level:.2f}\n')
f.write('\n')
print(f'フィボナッチレベルの価格が保存されました: {symbol}_fibonacci_levels.txt')
# ユーザーに銘柄を入力してもらう
symbols = input("銘柄をカンマ区切りで入力してください(例: BTCUSDT,ETHUSDT): ").split(',')
# 各銘柄についてチャートをプロット
for symbol in symbols:
symbol = symbol.strip()
plot_price_chart(symbol)
BTCUSDT,ETHUSDTなど複数銘柄をカンマ区切りで入力
![](https://assets.st-note.com/img/1731150498-4qEI9sHDhw2AyVfu8rM3FtXz.jpg?width=1200)
1分足:
Level 1: 76795.69
Level 2: 76660.10
Level 3: 76576.22
Level 4: 76508.43
Level 5: 76440.63
Level 6: 76221.16
15分足:
Level 1: 77199.99
Level 2: 74753.85
Level 3: 73240.56
Level 4: 72017.49
Level 5: 70794.43
Level 6: 66835.00
1時間足:
Level 1: 77199.99
Level 2: 74382.15
Level 3: 72638.91
Level 4: 71229.99
Level 5: 69821.08
Level 6: 65260.00
4時間足:
Level 1: 77199.99
Level 2: 71382.59
Level 3: 67783.69
Level 4: 64875.00
Level 5: 61966.30
Level 6: 52550.00
12時間足:
Level 1: 77199.99
Level 2: 70544.79
Level 3: 66427.59
Level 4: 63100.00
Level 5: 59772.40
Level 6: 49000.00
日足:
Level 1: 77199.99
Level 2: 64857.43
Level 3: 57221.78
Level 4: 51050.50
Level 5: 44879.21
Level 6: 24901.00
週足:
Level 1: 77199.99
Level 2: 59645.60
Level 3: 48785.69
Level 4: 40008.50
Level 5: 31231.30
Level 6: 2817.00
月足:
Level 1: 77199.99
Level 2: 59645.60
Level 3: 48785.69
Level 4: 40008.50
Level 5: 31231.30
Level 6: 2817.00
このコードをアレンジして、自分の使いやすいようにやってみよう!