Skip to content

添加回测、模拟和实盘交易功能 #502

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions example_run.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from datetime import date
from tqsdk import TqApi, TqSim, TqAccount, TqBacktest, TqAuth

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"))

Comment on lines +4 to +6
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

认证凭据硬编码及未使用的变量问题

这段代码存在几个问题:

  1. 认证凭据直接硬编码在代码中,这是一个安全风险
  2. 创建的api变量从未被使用
  3. 缺少文档字符串说明函数用途
  4. 没有错误处理和资源清理

建议修改为:

-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.

Suggested change
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_simulation():
api = TqApi(TqSim(init_balance=100000), web_gui=True, auth=TqAuth("13760685574", "xdy19870920"))

Comment on lines +7 to +9
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

模拟交易函数存在相同的安全和资源管理问题

与回测函数类似,模拟交易函数存在安全凭据硬编码和资源管理问题。

建议修改为:

-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)

def run_real_trading():
api = TqApi(TqAccount("期货公司", "账户", "密码"), web_gui=True, auth=TqAuth("13760685574", "xdy19870920"))

Comment on lines +10 to +12
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

实盘交易函数使用了占位符账户信息且存在相同问题

实盘交易函数不仅存在与前两个函数相同的问题,还使用了明显的占位符账户信息。

建议修改为:

-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 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")

Comment on lines +13 to +24
Copy link

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.

Suggested change
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}")

if __name__ == "__main__":
main()
Empty file added mycode.py
Empty file.