Add data retrieval and processing scripts for futures data
- Implemented a function to fetch futures data from the API with error handling and response validation. - Added example usage for fetching and saving K-line data to CSV. - Updated CSV files with new data entries for specified date ranges. - Enhanced the structure of the data retrieval function to include parameters for depth and adjust type.
This commit is contained in:
109
2.数据下载与处理/ssquant_download/专属数据库请求数据API示例.py
Normal file
109
2.数据下载与处理/ssquant_download/专属数据库请求数据API示例.py
Normal file
@@ -0,0 +1,109 @@
|
||||
import requests
|
||||
import pandas as pd
|
||||
from datetime import datetime, timedelta
|
||||
from io import StringIO
|
||||
|
||||
def get_futures_data(symbol, start_date, end_date, kline_period='1m', adjust_type='0', depth='no'):
|
||||
"""
|
||||
获取期货数据
|
||||
"""
|
||||
# 构建请求参数
|
||||
params = {
|
||||
'username': username,
|
||||
'password': password,
|
||||
'symbol': symbol,
|
||||
'start_date': start_date,
|
||||
'end_date': end_date,
|
||||
'kline_period': kline_period,
|
||||
'adjust_type': adjust_type
|
||||
}
|
||||
|
||||
if depth:
|
||||
params['Depth'] = depth
|
||||
|
||||
print("请求参数:", params) # 打印请求参数,便于调试
|
||||
|
||||
try:
|
||||
# 发送请求,设置超时时间为30秒
|
||||
response = requests.get(base_url, params=params, timeout=300)
|
||||
|
||||
# 检查响应状态
|
||||
if response.status_code == 200:
|
||||
# 检查响应是否为JSON格式
|
||||
if 'application/json' in response.headers.get('Content-Type', ''):
|
||||
data = pd.read_json(StringIO(response.text), orient='records')
|
||||
data=data.reset_index()
|
||||
#列名排序
|
||||
if depth=='yes':
|
||||
columns=['datetime','symbol','open','high','low','close','volume','amount','openint','cumulative_openint','open_askp','open_bidp','close_askp','close_bidp','开仓','平仓','多开','空开','多平','空平','双开','双平','双换','B','S','未知']
|
||||
else:
|
||||
columns=['datetime','symbol','open','high','low','close','volume','amount','openint','cumulative_openint','open_askp','open_bidp','close_askp','close_bidp']
|
||||
# 重新排列列名
|
||||
data = data.reindex(columns=columns)
|
||||
data['datetime'] = pd.to_datetime(data['datetime'])
|
||||
# 更改时间显示的格式,例如 "YYYY-MM-DD HH:MM:SS"
|
||||
# 将 UTC 时间转换为本地时区,例如 'Asia/Shanghai'
|
||||
data['datetime'] = data['datetime'].dt.tz_convert('Asia/Shanghai')
|
||||
data['datetime'] = data['datetime'].dt.strftime('%Y-%m-%d %H:%M:%S')
|
||||
return data
|
||||
else:
|
||||
print("响应不是JSON格式:", response.text[:1000])
|
||||
return None
|
||||
elif response.status_code == 401:
|
||||
print("认证失败:用户名和密码不能为空")
|
||||
return None
|
||||
elif response.status_code == 402:
|
||||
print("认证失败:账号不存在,请检查账号后重新输入......如还有问题联系管理员微信:viquant01")
|
||||
return None
|
||||
elif response.status_code == 405:
|
||||
print("认证失败:账号已过期,请联系管理员微信:viquant01")
|
||||
return None
|
||||
elif response.status_code == 406:
|
||||
print("认证失败:密码错误,请检查密码后重新输入......如还有问题联系管理员微信:viquant01")
|
||||
return None
|
||||
else:
|
||||
print(f"请求失败,状态码:{response.status_code}")
|
||||
print(f"错误信息:{response.json().get('error', '未知错误')}")
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
print(f"发生错误:{e}")
|
||||
print("请求URL:", response.url)
|
||||
print("响应内容:", response.text[:1000]) # 打印前1000个字符
|
||||
return None
|
||||
|
||||
# 使用示例
|
||||
if __name__ == "__main__":
|
||||
# API配置
|
||||
base_url = 'http://kanpan789.com:8086/ftdata'
|
||||
# 用户认证信息
|
||||
username = '240884432@qq.com' # 替换为你的手机号或者邮箱
|
||||
password = 'Zj123!@#' # 替换为你的密码
|
||||
# 示例参数
|
||||
symbol = "IM888" #
|
||||
start_date = "2025-10-01" #start_date : 开始时间
|
||||
end_date = "2025-10-10" #end_date(包含当天):结束时间
|
||||
kline_period="15M" #周期:1M..5M..NM(分钟),1D(天),1W(周),1Y(月)
|
||||
adjust_type= 0 #复权开关 :0(不复权)1(后复权)
|
||||
depth='yes' # 获取交易数据统计: yes(获取),no(不获取)
|
||||
|
||||
# 获取K线数据
|
||||
df_data = get_futures_data(
|
||||
symbol=symbol,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
kline_period=kline_period,
|
||||
adjust_type=adjust_type,
|
||||
depth=depth
|
||||
)
|
||||
|
||||
if df_data is not None:
|
||||
print("\nK线数据示例:")
|
||||
print(df_data)
|
||||
print(f"\n数据条数:{len(df_data)}")
|
||||
|
||||
# 保存到CSV文件(可选)
|
||||
csv_filename = f"{symbol}_{start_date}_{end_date}_1m.csv"
|
||||
df_data.to_csv(csv_filename, index=False)
|
||||
print(f"\n数据已保存到文件:{csv_filename}")
|
||||
|
||||
Reference in New Issue
Block a user