美股市场是全球最大、流动性最强的金融市场之一,涵盖了科技、金融、医疗等多个行业的优质公司。对于量化交易者来说,美股行情数据是构建策略的基础。无论是高频交易、均值回归策略,还是基于机器学习的预测模型,都离不开准确、及时的行情数据。

然而,获取高质量的美股数据并不容易。许多数据源要么价格昂贵,要么接口复杂,难以满足量化交易的需求。因此,找到一个性价比高且易于使用的接口显得尤为重要。

接口的基本调用功能

最近使用的这款实时行情接口提供了丰富的功能,包括实时行情、历史K线、深度数据等。以下是一些基本调用功能的示例代码:

1. 获取实时行情

import requests
import json
 
#Token注册:AllTick.io
#Github: https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api/blob/main/access_guide_cn.md
 
def get_realtime_quotes(symbols):
    url = "http://quote.aatest.online/quote-stock-b-api/trade-tick"
    token = "e945d7d9-9e6e-4721-922a-7251a9d311d0-1678159756806"
    
    query = {
        "trace": "python_realtime_test",
        "data": {
            "symbol_list": [{"code": symbol} for symbol in symbols]
        }
    }
    
    response = requests.get(
        url=url,
        params={"token": token, "query": json.dumps(query)},
        headers={'Content-Type': 'application/json'}
    )
    
    if response.status_code == 200:
        data = response.json()
        if data.get("code") == 0:
            return data["data"]
        else:
            print(f"Error: {data.get('message')}")
            return None
    else:
        print(f"Request failed with status code: {response.status_code}")
        return None
 
# 获取多只股票的实时行情
symbols = ["AAPL.US", "TSLA.US", "AMZN.US"]
realtime_data = get_realtime_quotes(symbols)
print(realtime_data)

2. 获取历史K线数据

def get_historical_data(symbol, kline_type=1, kline_timestamp_end=0, query_kline_num=100):
    url = "http://quote.aatest.online/quote-stock-b-api/kline"
    token = "e945d7d9-9e6e-4721-922a-7251a9d311d0-1678159756806"
    
    query = {
        "trace": "python_historical_test",
        "data": {
            "code": symbol,
            "kline_type": kline_type,
            "kline_timestamp_end": kline_timestamp_end,
            "query_kline_num": query_kline_num
        }
    }
    
    response = requests.get(
        url=url,
        params={"token": token, "query": json.dumps(query)},
        headers={'Content-Type': 'application/json'}
    )
    
    if response.status_code == 200:
        data = response.json()
        if data.get("code") == 0:
            kline_data = data["data"]["kline"]
            df = pd.DataFrame(kline_data, columns=["timestamp", "open", "high", "low", "close", "volume"])
            df["timestamp"] = pd.to_datetime(df["timestamp"], unit="s")
            df.set_index("timestamp", inplace=True)
            return df
        else:
            print(f"Error: {data.get('message')}")
            return None
    else:
        print(f"Request failed with status code: {response.status_code}")
        return None
 
# 获取AAPL的历史K线数据
aapl_data = get_historical_data("AAPL.US", query_kline_num=252)
print(aapl_data.head())

高阶策略开发:基于波动率的动态仓位管理

基于获取的实时和历史数据,我们可以开发更复杂的量化策略。以下是一个基于波动率的动态仓位管理策略示例:

策略逻辑

计算波动率:使用历史数据计算股票的滚动波动率。

动态调整仓位:波动率较高时减少仓位,波动率较低时增加仓位。

生成交易信号:根据波动率和价格趋势生成买入或卖出信号。

代码实现

import numpy as np
 
# 计算滚动波动率
def calculate_volatility(data, window=20):
    data['returns'] = data['close'].pct_change()
    data['volatility'] = data['returns'].rolling(window=window).std() * np.sqrt(252)  # 年化波动率
    return data
 
# 动态仓位管理策略
def dynamic_position_management(data, volatility_threshold_high=0.3, volatility_threshold_low=0.1):
    data['position'] = 1.0  # 默认满仓
    data.loc[data['volatility'] > volatility_threshold_high, 'position'] = 0.5  # 高波动率时减仓
    data.loc[data['volatility'] < volatility_threshold_low, 'position'] = 1.5  # 低波动率时加仓
    
    # 生成交易信号
    data['signal'] = np.where(data['position'].shift(1) > data['position'], -1, 1)
    return data
 
# 获取AAPL的历史数据
aapl_data = get_historical_data("AAPL.US", query_kline_num=252)
aapl_data = calculate_volatility(aapl_data)
aapl_data = dynamic_position_management(aapl_data)
 
# 计算策略收益
aapl_data['strategy_return'] = aapl_data['position'].shift(1) * aapl_data['returns']
cumulative_return = (1 + aapl_data['strategy_return']).cumprod()
 
# 绘制策略净值曲线
import matplotlib.pyplot as plt
 
plt.figure(figsize=(10, 6))
plt.plot(cumulative_return)
plt.title('Dynamic Position Management Strategy - AAPL')
plt.xlabel('Date')
plt.ylabel('Cumulative Return')
plt.show()[]()

TickTank
2 声望1 粉丝

高频tick数据行情接口