-
Notifications
You must be signed in to change notification settings - Fork 679
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
添加回测、模拟和实盘交易功能 #502
base: master
Are you sure you want to change the base?
添加回测、模拟和实盘交易功能 #502
Conversation
📝 WalkthroughWalkthrough新增了一个 Python 脚本 Changes
Sequence Diagram(s)sequenceDiagram
participant 用户 as 用户
participant Main as main()
participant API as TqApi
用户->>Main: 启动程序并选择交易模式
alt 回测模式
Main->>API: 调用 run_backtest() 初始化回测环境
else 模拟模式
Main->>API: 调用 run_simulation() 初始化模拟环境
else 实盘模式
Main->>API: 调用 run_real_trading() 初始化实盘环境
end
Poem
Warning Review ran into problems🔥 ProblemsErrors were encountered while retrieving linked issues. Errors (1)
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🧹 Nitpick comments (2)
example_run.py (2)
1-3
: 导入部分结构良好,但可以考虑更加明确的导入方式代码导入了所需的模块,包括
date
和多个tqsdk
类。但为了更好的代码可读性和维护性,建议考虑使用更明确的导入语句。-from datetime import date -from tqsdk import TqApi, TqSim, TqAccount, TqBacktest, TqAuth +from datetime import date +from tqsdk import TqApi, TqSim, TqAccount, TqBacktest, TqAuth +import logging # 添加日志支持
25-27
: 脚本入口点脚本入口点的结构正确,但缺少一些基本的启动设置。
if __name__ == "__main__": + # 设置基本日志配置 + import os + import logging + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s' + ) + + # 检查是否有必要的环境变量 + required_vars = ["TQ_USERNAME", "TQ_PASSWORD"] + missing = [var for var in required_vars if not os.environ.get(var)] + if missing: + print(f"警告: 缺少必要的环境变量: {', '.join(missing)}") + print("请设置这些环境变量或在代码中提供这些值") + main()
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
example_run.py
(1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
example_run.py
5-5: Local variable api
is assigned to but never used
Remove assignment to unused variable api
(F841)
8-8: Local variable api
is assigned to but never used
Remove assignment to unused variable api
(F841)
11-11: Local variable api
is assigned to but never used
Remove assignment to unused variable api
(F841)
def main(): | ||
print("请选择运行模式: 1. 回测 2. 模拟 3. 实盘") | ||
choice = input("输入选择(1/2/3): ") | ||
if choice == '1': | ||
run_backtest() | ||
elif choice == '2': | ||
run_simulation() | ||
elif choice == '3': | ||
run_real_trading() | ||
else: | ||
print("无效选择,请输入1, 2或3") | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
主函数需要增强错误处理和用户体验
主函数实现了基本功能,但缺乏适当的异常处理和用户体验优化。
建议修改为:
def main():
- print("请选择运行模式: 1. 回测 2. 模拟 3. 实盘")
- choice = input("输入选择(1/2/3): ")
- if choice == '1':
- run_backtest()
- elif choice == '2':
- run_simulation()
- elif choice == '3':
- run_real_trading()
- else:
- print("无效选择,请输入1, 2或3")
+ print("===============================")
+ print("交易系统 v1.0")
+ print("===============================")
+ print("请选择运行模式:")
+ print("1. 回测 - 使用历史数据测试策略")
+ print("2. 模拟 - 使用实时行情进行模拟交易")
+ print("3. 实盘 - 使用实际资金进行交易")
+ print("4. 退出")
+ print("===============================")
+ try:
+ choice = input("请输入选择(1/2/3/4): ")
+ if choice == '1':
+ run_backtest()
+ elif choice == '2':
+ run_simulation()
+ elif choice == '3':
+ confirm = input("确认要进行实盘交易吗?(y/n): ")
+ if confirm.lower() == 'y':
+ run_real_trading()
+ else:
+ print("已取消实盘交易")
+ main() # 返回主菜单
+ elif choice == '4':
+ print("感谢使用,再见!")
+ return
+ else:
+ print("无效选择,请输入1, 2, 3或4")
+ main() # 重新显示主菜单
+ except KeyboardInterrupt:
+ print("\n程序已被用户中断")
+ except Exception as e:
+ print(f"发生错误: {e}")
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
def main(): | |
print("请选择运行模式: 1. 回测 2. 模拟 3. 实盘") | |
choice = input("输入选择(1/2/3): ") | |
if choice == '1': | |
run_backtest() | |
elif choice == '2': | |
run_simulation() | |
elif choice == '3': | |
run_real_trading() | |
else: | |
print("无效选择,请输入1, 2或3") | |
def main(): | |
print("===============================") | |
print("交易系统 v1.0") | |
print("===============================") | |
print("请选择运行模式:") | |
print("1. 回测 - 使用历史数据测试策略") | |
print("2. 模拟 - 使用实时行情进行模拟交易") | |
print("3. 实盘 - 使用实际资金进行交易") | |
print("4. 退出") | |
print("===============================") | |
try: | |
choice = input("请输入选择(1/2/3/4): ") | |
if choice == '1': | |
run_backtest() | |
elif choice == '2': | |
run_simulation() | |
elif choice == '3': | |
confirm = input("确认要进行实盘交易吗?(y/n): ") | |
if confirm.lower() == 'y': | |
run_real_trading() | |
else: | |
print("已取消实盘交易") | |
main() # 返回主菜单 | |
elif choice == '4': | |
print("感谢使用,再见!") | |
return | |
else: | |
print("无效选择,请输入1, 2, 3或4") | |
main() # 重新显示主菜单 | |
except KeyboardInterrupt: | |
print("\n程序已被用户中断") | |
except Exception as e: | |
print(f"发生错误: {e}") |
def run_backtest(): | ||
api = TqApi(backtest=TqBacktest(start_dt=date(2021, 1, 1), end_dt=date(2021, 12, 31)), web_gui=True, auth=TqAuth("13760685574", "xdy19870920")) | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
认证凭据硬编码及未使用的变量问题
这段代码存在几个问题:
- 认证凭据直接硬编码在代码中,这是一个安全风险
- 创建的
api
变量从未被使用 - 缺少文档字符串说明函数用途
- 没有错误处理和资源清理
建议修改为:
-def run_backtest():
- api = TqApi(backtest=TqBacktest(start_dt=date(2021, 1, 1), end_dt=date(2021, 12, 31)), web_gui=True, auth=TqAuth("13760685574", "xdy19870920"))
+def run_backtest():
+ """回测交易模式,使用2021年全年数据进行回测"""
+ try:
+ # 从环境变量或配置文件获取凭据
+ username = os.environ.get("TQ_USERNAME")
+ password = os.environ.get("TQ_PASSWORD")
+
+ api = TqApi(backtest=TqBacktest(start_dt=date(2021, 1, 1), end_dt=date(2021, 12, 31)),
+ web_gui=True,
+ auth=TqAuth(username, password))
+
+ # 这里添加您的交易策略代码
+
+ # 等待策略运行
+ while True:
+ api.wait_update()
+ except Exception as e:
+ logging.error(f"回测过程中出现错误: {e}")
+ finally:
+ if api:
+ api.close()
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
def run_backtest(): | |
api = TqApi(backtest=TqBacktest(start_dt=date(2021, 1, 1), end_dt=date(2021, 12, 31)), web_gui=True, auth=TqAuth("13760685574", "xdy19870920")) | |
def run_backtest(): | |
"""回测交易模式,使用2021年全年数据进行回测""" | |
try: | |
# 从环境变量或配置文件获取凭据 | |
username = os.environ.get("TQ_USERNAME") | |
password = os.environ.get("TQ_PASSWORD") | |
api = TqApi( | |
backtest=TqBacktest(start_dt=date(2021, 1, 1), end_dt=date(2021, 12, 31)), | |
web_gui=True, | |
auth=TqAuth(username, password) | |
) | |
# 这里添加您的交易策略代码 | |
# 等待策略运行 | |
while True: | |
api.wait_update() | |
except Exception as e: | |
logging.error(f"回测过程中出现错误: {e}") | |
finally: | |
if api: | |
api.close() |
🧰 Tools
🪛 Ruff (0.8.2)
5-5: Local variable api
is assigned to but never used
Remove assignment to unused variable api
(F841)
def run_real_trading(): | ||
api = TqApi(TqAccount("期货公司", "账户", "密码"), web_gui=True, auth=TqAuth("13760685574", "xdy19870920")) | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
实盘交易函数使用了占位符账户信息且存在相同问题
实盘交易函数不仅存在与前两个函数相同的问题,还使用了明显的占位符账户信息。
建议修改为:
-def run_real_trading():
- api = TqApi(TqAccount("期货公司", "账户", "密码"), web_gui=True, auth=TqAuth("13760685574", "xdy19870920"))
+def run_real_trading():
+ """实盘交易模式,使用真实账户进行交易"""
+ try:
+ # 从环境变量或配置文件获取凭据
+ username = os.environ.get("TQ_USERNAME")
+ password = os.environ.get("TQ_PASSWORD")
+ broker = os.environ.get("TQ_BROKER")
+ account = os.environ.get("TQ_ACCOUNT")
+ account_password = os.environ.get("TQ_ACCOUNT_PASSWORD")
+
+ if not all([broker, account, account_password, username, password]):
+ print("请先设置环境变量: TQ_BROKER, TQ_ACCOUNT, TQ_ACCOUNT_PASSWORD, TQ_USERNAME, TQ_PASSWORD")
+ return
+
+ api = TqApi(TqAccount(broker, account, account_password),
+ web_gui=True,
+ auth=TqAuth(username, password))
+
+ # 这里添加您的交易策略代码
+
+ # 等待策略运行
+ while True:
+ api.wait_update()
+ except Exception as e:
+ logging.error(f"实盘交易过程中出现错误: {e}")
+ finally:
+ if api:
+ api.close()
Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Ruff (0.8.2)
11-11: Local variable api
is assigned to but never used
Remove assignment to unused variable api
(F841)
def run_simulation(): | ||
api = TqApi(TqSim(init_balance=100000), web_gui=True, auth=TqAuth("13760685574", "xdy19870920")) | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
模拟交易函数存在相同的安全和资源管理问题
与回测函数类似,模拟交易函数存在安全凭据硬编码和资源管理问题。
建议修改为:
-def run_simulation():
- api = TqApi(TqSim(init_balance=100000), web_gui=True, auth=TqAuth("13760685574", "xdy19870920"))
+def run_simulation():
+ """模拟交易模式,初始资金为100000"""
+ try:
+ # 从环境变量或配置文件获取凭据
+ username = os.environ.get("TQ_USERNAME")
+ password = os.environ.get("TQ_PASSWORD")
+
+ api = TqApi(TqSim(init_balance=100000),
+ web_gui=True,
+ auth=TqAuth(username, password))
+
+ # 这里添加您的交易策略代码
+
+ # 等待策略运行
+ while True:
+ api.wait_update()
+ except Exception as e:
+ logging.error(f"模拟交易过程中出现错误: {e}")
+ finally:
+ if api:
+ api.close()
Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Ruff (0.8.2)
8-8: Local variable api
is assigned to but never used
Remove assignment to unused variable api
(F841)
Summary by CodeRabbit