数据提供商开发
本指南将帮助您为 OpenBB 平台创建自定义数据提供商。
什么是数据提供商?
数据提供商是连接外部数据源与 OpenBB 平台的桥梁。它们负责:
- 从外部 API 获取数据
- 将数据转换为标准格式
- 处理认证和错误
创建数据提供商
1. 基本结构
from openbb_core.provider.abstract.provider import Provider
from openbb_core.provider.abstract.fetcher import Fetcher
class MyProvider(Provider):
website = "https://example.com"
credentials = ["api_key"]
fetcher_dict = {
"equity_historical": MyEquityHistoricalFetcher,
}
2. 实现 Fetcher
class MyEquityHistoricalFetcher(Fetcher):
@staticmethod
def transform_query(params: dict) -> dict:
# 转换查询参数
return params
@staticmethod
def extract_data(query: dict, credentials: dict) -> list:
# 从 API 获取数据
pass
@staticmethod
def transform_data(query: dict, data: list) -> list:
# 转换数据格式
pass
最佳实践
错误处理
try:
response = requests.get(url)
response.raise_for_status()
except requests.RequestException as e:
raise ProviderError(f"API 请求失败: {e}")
数据验证
from pydantic import BaseModel, validator
class EquityHistoricalData(BaseModel):
date: str
open: float
high: float
low: float
close: float
volume: int
@validator('date')
def validate_date(cls, v):
# 验证日期格式
return v
测试
import pytest
from your_provider import MyProvider
def test_equity_historical():
provider = MyProvider()
data = provider.equity_historical("AAPL")
assert len(data) > 0
注册提供商
# 在 __init__.py 中
from openbb_core.provider.registry import Registry
Registry.register_provider(MyProvider)