AllTick作为一家专业的行情数据服务商,已经为超过200家海外交易平台、数千个专业量化交易团队提供稳定实时的行情数据。在提供实时数据的同时,AllTick也为用户带来了丰富的历史数据查询功能。无论是A股、港股、美股,还是外汇、商品期货、加密货币,用户都可以通过AllTick的API轻松获取这些资产的历史成交数据。这些数据不仅为策略回测和量化分析提供了基础,还帮助用户深入理解市场动态,优化交易决策。

获取历史数据的简单方法

下面我们展示如何通过简单的HTTP请求获取外汇历史数据。你可以在我们提供的文档里找到你想查询的code,并作为参数带入。下面是美元/日元(USD/JPY)的1分钟K线数据,并展示查询到的2根K线信息:

import time
 
import requests	# pip3 install requests
import json
 
# Extra headers
test_headers = {
    'Content-Type' : 'application/json'
}
 
'''
github:https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
申请免费token:https://alltick.co/register
官网:https://alltick.co

code:请查看文档中的code列表,选择你要查询的code
kline_type:k线类型,1分钟K,2为5分钟K,3为15分钟K,4为30分钟K,5为小时K,6为2小时K,7为4小时K,8为日K,9为周K,10为月K
query_kline_num:查询多少根K线,最多1000根
 
将如下JSON进行url的encode,复制到http的查询字符串的query字段里
{"trace" : "python_http_test1","data" : {"code" : "USDJPY","kline_type" : 1,"kline_timestamp_end" : 0,"query_kline_num" : 2,"adjust_type": 0}}
{"trace" : "python_http_test2","data" : {"symbol_list": [{"code": "GOLD"}]}}
{"trace" : "python_http_test3","data" : {"symbol_list": [{"code": "GOLD"}]}}
'''
test_url1 = 'https://quote.aatest.online/quote-b-api/kline?token=3662a972-1a5d-4bb1-88b4-66ca0c402a03-1688712831841&query=%7B%22trace%22%20%3A%20%22python_http_test1%22%2C%22data%22%20%3A%20%7B%22code%22%20%3A%20%22USDJPY%22%2C%22kline_type%22%20%3A%201%2C%22kline_timestamp_end%22%20%3A%200%2C%22query_kline_num%22%20%3A%202%2C%22adjust_type%22%3A%200%7D%7D'
 
resp1 = requests.get(url=test_url1, headers=test_headers)
 
# Decoded text returned by the request
text1 = resp1.text
print(text1)

如何使用历史数据跑回测

拿到历史行情数据后的主要作用是用于验证你的交易策略,把它丢到历史中去跑一遍看看效果,也即所谓的回测。下面是利用AllTick的历史数据跑简单回测的代码示例:

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

# 请求头,Content-Type为json格式
headers = {
    'Content-Type': 'application/json'
}

# 请求数据的URL和Token
token = "your_api_token"  # 请替换为你的AllTick API Token
symbol = "USDJPY"
kline_type = 1  # 1分钟K线
query_kline_num = 1000  # 查询1000根K线数据

# 请求URL
url = f'https://quote.aatest.online/quote-b-api/kline?token={token}&query=%7B%22trace%22%3A%20%22python_http_test1%22%2C%22data%22%3A%20%7B%22code%22%3A%20%22{symbol}%22%2C%22kline_type%22%3A%20{kline_type}%2C%22kline_timestamp_end%22%3A%200%2C%22query_kline_num%22%3A%20{query_kline_num}%2C%22adjust_type%22%3A%200%7D%7D'

# 发送请求获取K线数据
response = requests.get(url, headers=headers)
data = response.json()

# 将K线数据转换为DataFrame
df = pd.DataFrame(data['data']['klines'], columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
df.set_index('timestamp', inplace=True)

# 将价格转换为浮点数
df['open'] = df['open'].astype(float)
df['high'] = df['high'].astype(float)
df['low'] = df['low'].astype(float)
df['close'] = df['close'].astype(float)
df['volume'] = df['volume'].astype(float)

# 简单移动平均线策略:短期和长期均线
short_window = 20
long_window = 50

# 计算移动平均线
df['SMA20'] = df['close'].rolling(window=short_window).mean()
df['SMA50'] = df['close'].rolling(window=long_window).mean()

# 生成交易信号
df['signal'] = 0
df['signal'][short_window:] = np.where(df['SMA20'][short_window:] > df['SMA50'][short_window:], 1, 0)

# 生成持仓信号
df['position'] = df['signal'].diff()

# 简单回测逻辑:计算策略收益
initial_capital = 10000  # 初始资金
position_size = 1000  # 每次交易的单位

df['returns'] = df['close'].pct_change()
df['strategy_returns'] = df['position'].shift(1) * df['returns'] * position_size

# 计算策略的累计收益
df['portfolio_value'] = initial_capital + df['strategy_returns'].cumsum()

# 绘制策略表现图
plt.figure(figsize=(14,7))
plt.plot(df['close'], label='USD/JPY Price')
plt.plot(df['SMA20'], label='20 Period SMA', alpha=0.7)
plt.plot(df['SMA50'], label='50 Period SMA', alpha=0.7)
plt.plot(df['portfolio_value'], label='Portfolio Value', linestyle='--')
plt.title('USD/JPY Backtest - SMA Crossover Strategy')
plt.legend(loc='best')
plt.show()