使用Python視覺化外匯資料
歷史外匯資料對於識別趨勢、評估過去的表現以及對貨幣市場做出明智的預測至關重要。透過清晰地顯示價格波動和模式,視覺化這些資料可以增強分析,幫助交易者和分析師做出更好的決策。
本教程將指導您使用TraderMade API檢索歷史貨幣資料,並使用Plotly將其視覺化為燭形圖格式。燭形圖在金融分析中很流行,因為它可以清晰地顯示價格波動,包括特定時期內開盤價、最高價、最低價和收盤價。我們將使用指定日期範圍內的歐元/美元貨幣對資料。
在本教程結束時,您將能夠
- 使用Python發出獲取歷史資料的API請求。
- 將JSON資料格式化並處理成資料框。
- 使用Plotly建立互動式燭形圖進行金融分析。
前提條件
在開始之前,請確保您擁有以下內容:
1. Python基礎知識:熟悉Python程式設計,特別是函式和錯誤處理,將非常有幫助。
2. TraderMade API金鑰:訪問“https://tradermade.com/dashboard”獲取API金鑰。在TraderMade註冊以獲得免費的API金鑰,您將在教程中使用它。
3. 已安裝所需的庫
requests:要安裝requests,請使用以下命令:
pip install requests
此庫使您可以向API發出HTTP請求。
pandas:要安裝pandas,請使用以下命令:
pip install pandas
Pandas將用於以表格格式組織和操作API資料。
plotly:要安裝plotly,請使用以下命令:
pip install plotly
此庫有助於建立互動式圖表,在本教程中特別是燭形圖。
示例
匯入所需的庫
這些庫是必不可少的
- requests:向TraderMade API發出HTTP請求。
- pandas:組織和操作從API獲取的資料。
- datetime:用於日期格式化和轉換。
- plotly.graph_objects:用於建立視覺化效果,在本教程中特別是燭形圖。
import requests import pandas as pd from datetime import datetime import plotly.graph_objects as go
設定API金鑰和基本URL
要訪問資料,請使用您的TraderMade API金鑰和歷史資料的基本URL。請務必將“KEY”替換為您實際的API金鑰。
API_KEY = 'KEY' # Replace with your TraderMade API Key BASE_URL = 'https://marketdata.tradermade.com/api/v1/historical'
定義引數
Set the currency pair and the date range for the historical data you wish to retrieve. symbol = 'EURUSD' # For EUR/USD currency pair start_date = '01-01-2023' # Start date in DD-MM-YYYY format end_date = '31-01-2023' # End date in DD-MM-YYYY format
定義日期轉換函式
API期望日期採用YYYY-MM-DD格式,因此輔助函式將轉換DD-MM-YYYY輸入格式。def convert_date_to_api_format(date_str): return datetime.strptime(date_str, '%d-%m-%Y').strftime('%Y-%m-%d')
獲取歷史資料函式
此函式從API檢索資料。def fetch_historical_data(symbol, start_date, end_date): # Convert date formats api_start_date = convert_date_to_api_format(start_date) api_end_date = convert_date_to_api_format(end_date) params = { 'currency': symbol, 'date': api_start_date, # Starting date 'end_date': api_end_date, # Ending date 'api_key': API_KEY } response = requests.get(BASE_URL, params=params) # Check if the request was successful if response.status_code != 200: print(f"Error: Received status code {response.status_code}") print("Response:", response.json()) raise Exception("Failed to fetch data from TraderMade API") # Log raw response for reference data = response.json() print("Raw API Response:", data) # Check for the 'quotes' field in response if 'quotes' not in data: print("Error: 'quotes' field not found in response") print("Response:", data) raise KeyError("'quotes' field missing from API response") # Convert the 'quotes' field to DataFrame df = pd.DataFrame(data['quotes']) print("DataFrame structure:\n", df.head()) # Handle date column if 'date' in data: df['date'] = data['date'] else: # Estimate dates if only one is provided df['date'] = pd.date_range(start=api_start_date, periods=len(pdf), freq='D') # Ensure the date column is datetime df['date'] = pd.to_datetime(df['date']) return df
獲取和顯示資料
使用該函式獲取資料,確保結構已準備好進行繪圖。
df = fetch_historical_data(symbol, start_date, end_date)
檢查所需列
燭形圖需要“開盤價”、“最高價”、“最低價”和“收盤價”列。驗證這些列是否存在。
required_columns = {'open', 'high', 'low', 'close'} if not required_columns.issubset(df.columns): missing_cols = required_columns - set(df.columns) raise ValueError(f"Missing columns in data for candlestick chart: {missing_cols}")
建立和自定義燭形圖
現在您已經擁有了資料,您可以使用Plotly對其進行視覺化。
fig = go.Figure(data=[go.Candlestick( x=df['date'], open=df['open'], high=df['high'], low=df['low'], close=df['close'], name=f'{symbol} OHLC' )]) fig.update_layout( title=f'{symbol} Candlestick Chart from {start_date} to {end_date}', xaxis_title='Date', yaxis_title='Price', xaxis_rangeslider_visible=False ) fig.show()
處理錯誤
如果上述步驟中發生錯誤,則會捕獲並列印該錯誤,以幫助診斷問題。
except Exception as e: print(f"An error occurred: {e}")
結論
透過此設定,您可以輕鬆修改符號或日期範圍,並使用TraderMade API視覺化各種貨幣對的歷史資料。如果將其應用於較大的專案,請記住安全地處理API金鑰,並在“https://tradermade.com/docs/restful-api”文件中檢視API使用限制。