hyperquant 0.21__tar.gz → 0.22__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hyperquant
3
- Version: 0.21
3
+ Version: 0.22
4
4
  Summary: A minimal yet hyper-efficient backtesting framework for quantitative trading
5
5
  Project-URL: Homepage, https://github.com/yourusername/hyperquant
6
6
  Project-URL: Issues, https://github.com/yourusername/hyperquant/issues
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "hyperquant"
3
- version = "0.21"
3
+ version = "0.22"
4
4
  description = "A minimal yet hyper-efficient backtesting framework for quantitative trading"
5
5
  authors = [
6
6
  { name = "MissinA", email = "1421329142@qq.com" }
@@ -2,4 +2,5 @@ from .core import *
2
2
  from .draw import *
3
3
  from .logkit import *
4
4
  from .datavison import *
5
+ from .notikit import *
5
6
  __version__ = "0.1.0"
@@ -0,0 +1,177 @@
1
+ import aiohttp
2
+ import asyncio
3
+ import pandas as pd
4
+ import time
5
+ from datetime import datetime, timezone
6
+ from ._util import _to_milliseconds # 确保时间转换函数可用
7
+
8
+ class OKX:
9
+ def __init__(self) -> None:
10
+ self.session = aiohttp.ClientSession()
11
+ self.base_url = "https://www.okx.com/api/v5/market"
12
+
13
+ async def get_klines(self, symbol: str, interval: str, start_time, end_time=None, limit: int = 100):
14
+ """
15
+ 获取 OKX 永续合约 K 线数据,带时间过滤,从 end_time 向 start_time 方向翻页。
16
+
17
+ :param symbol: 交易对, 如 'BTC-USDT'
18
+ :param interval: K 线间隔, 如 '1m', '15m', '1H', '4H', '1D'
19
+ :param start_time: 开始时间(datetime 或 毫秒)
20
+ :param end_time: 结束时间(datetime 或 毫秒), 可选
21
+ :param limit: 每次请求最大数量(OKX 最大 300)
22
+ :return: DataFrame 格式的 K 线数据,按时间升序
23
+ """
24
+ if 'h' in interval or 'd' in interval:
25
+ interval = interval.upper() # 确保间隔是大写格式
26
+
27
+ url = f"{self.base_url}/history-candles"
28
+ all_rows = []
29
+ # 转换 start_time 和 end_time 到毫秒时间戳
30
+ if isinstance(start_time, (int, float)):
31
+ start_ts = int(start_time)
32
+ else:
33
+ # 处理 datetime 对象
34
+ start_ts = int(start_time.timestamp() * 1000)
35
+ if end_time:
36
+ if isinstance(end_time, (int, float)):
37
+ end_ts = int(end_time)
38
+ else:
39
+ end_ts = int(end_time.timestamp() * 1000)
40
+ else:
41
+ # 如果没有指定结束时间,就用当前时间戳
42
+ end_ts = int(time.time() * 1000)
43
+
44
+ # 每次请求最多返回 limit=300
45
+ batch_limit = min(limit, 300)
46
+ # 初始 after 参数为 end_ts,向过去翻页
47
+ current_after = end_ts
48
+
49
+ while True:
50
+ params = {
51
+ "instId": symbol,
52
+ "bar": interval,
53
+ "limit": str(batch_limit),
54
+ "after": str(current_after)
55
+ }
56
+ # 发送请求
57
+ async with self.session.get(url, params=params) as resp:
58
+ data = await resp.json()
59
+ if not data or data.get("code") != "0" or not data.get("data"):
60
+ # 返回错误或无数据,结束循环
61
+ break
62
+ buf = data["data"] # 每条是 [ts, o, h, l, c, vol, volCcy, volCcyQuote, confirm]
63
+
64
+ # 本批数据按时间从新到旧排列, 最后一条是最旧的
65
+ rows_this_batch = []
66
+ for item in buf:
67
+ ts = int(item[0])
68
+ # 如果已经早于 start_ts,就跳过,并认为后面更旧,也可以结束循环
69
+ if ts < start_ts:
70
+ continue
71
+ # 如果某些条目时间超出 end_ts,也跳过
72
+ if ts > end_ts:
73
+ continue
74
+ # 解析数值字段
75
+ dt = pd.to_datetime(ts, unit='ms', utc=True)
76
+ o = float(item[1]); h = float(item[2]); l = float(item[3]); c = float(item[4]); vol = float(item[5])
77
+ # 按需把每个 K 线封装为字典,后续转换为 DataFrame
78
+ rows_this_batch.append({
79
+ "symbol": symbol,
80
+ "open_time": dt,
81
+ "open": o,
82
+ "high": h,
83
+ "low": l,
84
+ "close": c,
85
+ "volume": vol,
86
+ "interval": interval,
87
+ "confirm": item[8]
88
+ })
89
+
90
+ if not rows_this_batch:
91
+ # 本批没有符合时间范围的数据,直接结束
92
+ break
93
+
94
+ # 累积本批符合条件的行
95
+ all_rows.extend(rows_this_batch)
96
+
97
+ # 检查是否到达 start_ts 之前:buf 最后一项是最旧
98
+ oldest_ts = int(buf[-1][0])
99
+ if oldest_ts < start_ts:
100
+ # 已经翻到 start_time 范围之前,结束循环
101
+ break
102
+
103
+ # 否则,更新 after = oldest_ts,继续向过去翻页
104
+ current_after = oldest_ts
105
+ # 为了不触发速率限制,稍做休眠(根据需要可以调整或删除)
106
+
107
+ # 如果累积到数据,则转换为 DataFrame;否则返回空 DataFrame
108
+ if all_rows:
109
+ df = pd.DataFrame(all_rows)
110
+ # 去重、按时间排序
111
+ df.drop_duplicates(subset=["open_time"], inplace=True)
112
+ df.sort_values("open_time", inplace=True)
113
+ df.reset_index(drop=True, inplace=True)
114
+ return df
115
+ else:
116
+ return pd.DataFrame()
117
+
118
+ async def get_index_klines(self, pair: str, interval: str, start_time, end_time=None, limit: int = 100):
119
+ """
120
+ 获取OKX指数K线数据(自动分批)
121
+
122
+ :param pair: 指数名称, 如 'BTC-USD'
123
+ :param interval: K线间隔, 如 '1m', '1H', '1D'
124
+ :param start_time: 开始时间(毫秒时间戳/datetime/date)
125
+ :param end_time: 结束时间(毫秒时间戳/datetime/date)
126
+ :param limit: 每次请求最大数量(OKX最大300)
127
+ :return: DataFrame格式的指数K线
128
+ """
129
+ url = f"{self.base_url}/index-candles"
130
+ all_klines = []
131
+ ms_start = _to_milliseconds(start_time)
132
+ ms_end = _to_milliseconds(end_time) if end_time else None
133
+
134
+ params = {
135
+ "instId": pair,
136
+ "bar": interval,
137
+ "limit": min(limit, 300),
138
+ "after": ms_start
139
+ }
140
+ if ms_end:
141
+ params["before"] = ms_end
142
+
143
+ while True:
144
+ async with self.session.get(url, params=params) as resp:
145
+ data = await resp.json()
146
+ if data['code'] != "0":
147
+ raise Exception(f"OKX API Error: {data['msg']} (Code {data['code']})")
148
+
149
+ klines = data['data']
150
+ if not klines:
151
+ break
152
+
153
+ all_klines.extend(klines)
154
+
155
+ if len(klines) < params["limit"]:
156
+ break
157
+
158
+ last_ts = int(klines[-1][0])
159
+ params["after"] = last_ts
160
+
161
+ # 数据转换
162
+ columns = ["open_time", "open", "high", "low", "close", "confirm"]
163
+ df = pd.DataFrame(all_klines, columns=columns)
164
+
165
+ df["open_time"] = pd.to_datetime(df["open_time"].astype(int), unit="ms")
166
+ num_cols = ["open", "high", "low", "close"]
167
+ df[num_cols] = df[num_cols].apply(pd.to_numeric, errors="coerce")
168
+
169
+ return df.sort_values("open_time").reset_index(drop=True)
170
+
171
+ async def close(self):
172
+ """关闭会话"""
173
+ await self.session.close()
174
+
175
+ # 使用示例
176
+ # async with OKXSwap() as okx:
177
+ # df = await okx.get_klines("BTC-USDT", "1H", datetime(2023,1,1))
@@ -0,0 +1,104 @@
1
+ """
2
+ 通知类的功能简单封装,非必要别修改 :)
3
+ 只要知道怎么使用以下函数:
4
+ - send_wecom_msg
5
+ - send_wecom_img
6
+
7
+ Binance期现套利 | 邢不行 | 2024分享会
8
+ author: 邢不行
9
+ 微信: xbx6660
10
+ """
11
+ import base64
12
+ import hashlib
13
+ import os.path
14
+ import requests
15
+ import json
16
+ import traceback
17
+ from datetime import datetime
18
+
19
+ from hyperquant.logkit import get_logger
20
+ logger = get_logger('notikit', './data/logs/notikit.log', show_time=True)
21
+
22
+
23
+
24
+ proxy = {}
25
+
26
+
27
+ def handle_exception(e: Exception, msg: str = '') -> None:
28
+ logger.error(f"{msg}:{e}")
29
+ logger.error(e)
30
+ logger.error(traceback.format_exc())
31
+
32
+
33
+ # 企业微信通知
34
+ def send_wecom_msg(content, webhook_url):
35
+ if not webhook_url:
36
+ logger.warning('未配置wecom_webhook_url,不发送信息')
37
+ return
38
+ if not content:
39
+ logger.warning('未配置content,不发送信息')
40
+ return
41
+ try:
42
+ data = {
43
+ "msgtype": "text",
44
+ "text": {
45
+ "content": content + '\n' + datetime.now().strftime("%Y-%m-%d %H:%M:%S")
46
+ }
47
+ }
48
+ r = requests.post(webhook_url, data=json.dumps(data), timeout=10, proxies=proxy)
49
+ logger.info(f'调用企业微信接口返回: {r.text}')
50
+ logger.ok('成功发送企业微信')
51
+ except Exception as e:
52
+ handle_exception(e, '发送企业微信失败')
53
+
54
+
55
+ # 上传图片,解析bytes
56
+ class MyEncoder(json.JSONEncoder):
57
+ def default(self, obj):
58
+ """
59
+ 只要检查到了是bytes类型的数据就把它转为str类型
60
+ :param obj:
61
+ :return:
62
+ """
63
+ if isinstance(obj, bytes):
64
+ return str(obj, encoding='utf-8')
65
+ return json.JSONEncoder.default(self, obj)
66
+
67
+
68
+ # 企业微信发送图片
69
+ def send_wecom_img(file_path, webhook_url):
70
+ """
71
+ 企业微信发送图片
72
+ :param file_path: 图片地址
73
+ :param webhook_url: 企业微信webhook网址
74
+ :return:
75
+ """
76
+ if not os.path.exists(file_path):
77
+ logger.warning('找不到图片')
78
+ return
79
+ if not webhook_url:
80
+ logger.warning('未配置wecom_webhook_url,不发送信息')
81
+ return
82
+ try:
83
+ with open(file_path, 'rb') as f:
84
+ image_content = f.read()
85
+ image_base64 = base64.b64encode(image_content).decode('utf-8')
86
+ md5 = hashlib.md5()
87
+ md5.update(image_content)
88
+ image_md5 = md5.hexdigest()
89
+ data = {
90
+ 'msgtype': 'image',
91
+ 'image': {
92
+ 'base64': image_base64,
93
+ 'md5': image_md5
94
+ }
95
+ }
96
+ # 服务器上传bytes图片的时候,json.dumps解析会出错,需要自己手动去转一下
97
+ r = requests.post(webhook_url, data=json.dumps(data, cls=MyEncoder, indent=4), timeout=10, proxies=proxy)
98
+ logger.info(f'调用企业微信接口返回: {r.text}')
99
+ logger.ok('成功发送企业微信图片')
100
+ except Exception as e:
101
+ handle_exception(e, '发送企业微信图片失败')
102
+ finally:
103
+ if os.path.exists(file_path):
104
+ os.remove(file_path)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes