增加交易策略、交易指标、量化库代码等文件夹

This commit is contained in:
Win_home
2025-04-27 15:54:09 +08:00
parent ca3b209096
commit f57150dae8
589 changed files with 854346 additions and 1757 deletions

View File

@@ -0,0 +1,157 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# akshare库使用教程\n",
"### akshare函数\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import akshare as ak\n",
"\n",
"futures_contract_detail_df = ak.futures_contract_detail(symbol='V2001')\n",
"print(futures_contract_detail_df)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" 日期 开盘价 最高价 最低价 收盘价 成交量 持仓量 动态结算价\n",
"0 2024-09-02 4612.0 4634.8 4508.8 4515.6 89892 142020 0\n",
"1 2024-09-03 4524.0 4592.8 4514.0 4547.4 95410 140430 0\n",
"2 2024-09-04 4530.0 4587.0 4507.0 4536.2 95403 134704 0\n",
"3 2024-09-05 4544.6 4611.4 4544.6 4577.2 88060 131885 0\n",
"4 2024-09-06 4595.0 4597.4 4482.0 4497.2 90398 127548 0\n",
"5 2024-09-09 4487.2 4518.6 4445.2 4457.4 85871 125870 0\n",
"6 2024-09-10 4471.0 4502.4 4378.8 4473.6 116746 129541 0\n",
"7 2024-09-11 4460.0 4494.4 4439.0 4474.8 86309 111092 0\n",
"8 2024-09-12 4484.0 4545.0 4461.6 4468.4 86856 106827 0\n",
"9 2024-09-13 4475.0 4478.6 4414.2 4416.8 80427 94210 0\n",
"10 2024-09-18 4413.0 4423.0 4337.4 4405.0 90715 75838 0\n",
"11 2024-09-19 4422.2 4543.2 4380.0 4487.4 92123 42680 0\n",
"12 2024-09-20 4483.0 4493.0 4437.0 4447.8 35454 17785 0\n",
"13 2024-09-23 4415.2 4497.8 4402.4 4437.0 78245 101314 0\n",
"14 2024-09-24 4496.0 4656.8 4438.2 4653.2 156875 127361 0\n",
"15 2024-09-25 4710.0 4802.8 4672.6 4680.0 130643 110238 0\n",
"16 2024-09-26 4671.4 4940.0 4662.4 4937.4 152942 119316 0\n",
"17 2024-09-27 5022.0 5362.6 4954.4 5362.2 212983 109667 0\n"
]
}
],
"source": [
"import akshare as ak\n",
"\n",
"futures_main_sina_hist = ak.futures_main_sina(symbol=\"IM0\", start_date=\"20240901\", end_date=\"20240927\")\n",
"print(futures_main_sina_hist)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import akshare as ak\n",
"from datetime import datetime, timedelta\n",
" \n",
"# 获取当前日期的数据\n",
"today = datetime.now().strftime('%Y%m%d')\n",
"# 计算20日前的日期\n",
"start_day = (datetime.now() - timedelta(days=60)).strftime('%Y%m%d')\n",
"\n",
"futures_main_sina_hist = ak.futures_main_sina(symbol=\"IM0\", start_date=start_day, end_date=today)\n",
"print(futures_main_sina_hist)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"futures_main_sina_hist['收盘价'].iloc[0]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"futures_main_sina_hist['5day_ma'] = futures_main_sina_hist['收盘价'].rolling(window=5).mean()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"futures_main_sina_hist['5day_ma'].iloc[-1]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(futures_main_sina_hist)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import akshare as ak\n",
"\n",
"futures_main_sina_hist = ak.futures_main_sina(symbol=\"IM0\", start_date=\"20240901\", end_date=\"20240927\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from findpeaks import findpeaks "
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.9"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

View File

@@ -0,0 +1,71 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "2d85dda4",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import pandas as pd\n",
"import talib\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "65b4b7aa",
"metadata": {},
"outputs": [],
"source": [
"df = pd.read_csv('D:/of_data/主力连续/tick生成的OF数据(5M)/data_rs_merged/上期所/ag888/ag888_rs_2021_5T_back_ofdata_dj.csv')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "edd4f1e5",
"metadata": {},
"outputs": [],
"source": [
"df['HT_TRENDLINE'] = talib.HT_TRENDLINE(df['delta'])"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "25c70609",
"metadata": {},
"outputs": [],
"source": [
"df[['delta','HT_TRENDLINE']].plot(title = '希尔伯特瞬时变换')\n",
"plt.grid()\n",
"plt.legend(['delta','HT_TRENDLINE'])\n",
"plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.1"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

View File

@@ -0,0 +1,30 @@
[
{
"account_name": "TEST_2_ACCOUNT",
"gateway": "CTP",
"workspace": "C:/TEST_ACCOUNT_2_WORKSPACE/",
"logon_detail": {
"用户名": "",
"密码": "",
"经纪商代码": "",
"交易服务器": "",
"行情服务器": "",
"产品名称": "",
"授权编码": ""
}
},
{
"account_name": "TEST_1_ACCOUNT",
"gateway": "CTP",
"workspace": "C:/TEST_ACCOUNT_1_WORKSPACE/",
"logon_detail": {
"用户名": "",
"密码": "",
"经纪商代码": "",
"交易服务器": "",
"行情服务器": "",
"产品名称": "",
"授权编码": ""
}
}
]

View File

@@ -0,0 +1,142 @@
import multiprocessing
import json
from threading import Timer
import sys
import os
from time import sleep
from datetime import datetime, time
from logging import INFO
# Chinese futures market trading period (day/night)
DAY_START = time(8, 45)
DAY_END = time(15, 0)
NIGHT_START = time(20, 45)
NIGHT_END = time(1, 30)
def check_trading_period():
""""""
current_time = datetime.now().time()
trading = False
if (
(current_time >= DAY_START and current_time <= DAY_END)
or (current_time >= NIGHT_START)
or (current_time <= NIGHT_END)
):
trading = True
return trading
def run_child(account_detail):
"""
Running in the child process.
"""
account_name = account_detail["account_name"]
ctp_setting = account_detail["logon_detail"]
# 更改工作路径
os.chdir(account_detail["workspace"])
# 把对vntrader 包的引用放在工作路径更改后,不然工作路径更改无法生效,
from vnpy.event import EventEngine
from vnpy.trader.setting import SETTINGS
from vnpy.trader.engine import MainEngine
from vnpy.gateway.ctp import CtpGateway
from vnpy.app.cta_strategy import CtaStrategyApp
from vnpy.app.cta_strategy.base import EVENT_CTA_LOG
SETTINGS["log.active"] = True
SETTINGS["log.level"] = INFO
SETTINGS["log.console"] = True
from vnpy.trader.utility import TRADER_DIR, TEMP_DIR
# 结束引用
SETTINGS["log.file"] = True
event_engine = EventEngine()
main_engine = MainEngine(event_engine)
main_engine.add_gateway(CtpGateway)
cta_engine = main_engine.add_app(CtaStrategyApp)
main_engine.write_log(f" 主引擎创建成功")
main_engine.write_log(f"工作路径: {TRADER_DIR, TEMP_DIR}")
log_engine = main_engine.get_engine("log")
# 更新log 格式。
event_engine.register(EVENT_CTA_LOG, log_engine.process_log_event)
main_engine.write_log(f"注册日志事件监听")
main_engine.connect(ctp_setting, account_detail["gateway"])
main_engine.write_log(f"连接CTP接口")
sleep(10)
cta_engine.init_engine()
main_engine.write_log(f"CTA策略初始化完成")
def recheck_thread():
# 每个10秒检查所有策略是否初始化完成使用Timer线程每10秒检查
all_strategise_inited = False
for strategy in cta_engine.strategies.values():
if strategy.inited == False:
all_strategise_inited = False
break
all_strategise_inited = True
if all_strategise_inited:
main_engine.write_log(f"CTA策略全部初始化=====")
cta_engine.start_all_strategies()
main_engine.write_log(f"CTA策略全部启动=====")
else:
newTask = Timer(10, recheck_thread)
newTask.start()
cta_engine.init_all_strategies()
newTask = Timer(5, recheck_thread)
newTask.start()
def recheck_trading_period():
# 每隔10秒检查是否交易时段否则退出使用Timer线程每10秒检查
trading = check_trading_period()
if not trading:
main_engine.write_log(f"关闭子进程")
main_engine.close()
sys.exit(0)
else:
closeTask = Timer(10, recheck_trading_period)
closeTask.start()
closeTask = Timer(5, recheck_trading_period)
closeTask.start()
def run_parent():
"""
Running in the parent process.
"""
print("启动CTA策略守护父进程")
with open("Mutiple_Accounts_Config.json", mode="r", encoding="UTF-8") as f:
account_detail_list = json.load(f)
child_process_list = []
while True:
trading = check_trading_period()
# Start child process in trading period
if trading and child_process_list == []:
print("启动子进程")
# 同时运行account 不应该超过cpu核心数因为vntrader 可以看成是一个持续循环在main_engine.close之前不会退出cpu占用
# 等待的运行事务将一直等待
for account_detail in account_detail_list:
new_process = multiprocessing.Process(
target=run_child,
name=account_detail["account_name"],
args=(account_detail,),
)
new_process.start()
child_process_list.append(new_process)
# # 使用进程池更加方便但是无法给进程命名去查看log 是那个account的所以不建议
# pool = multiprocessing.Pool(multiprocessing.cpu_count())
# child_process_list = pool.map_async(run_child, account_detail_list)
print("子进程启动成功")
# 非记录时间则退出子进程
if not trading and child_process_list:
for process in child_process_list:
if not process.is_alive():
child_process_list.remove(process)
if child_process_list == []:
print("子进程关闭成功")
sleep(10)
if __name__ == "__main__":
run_parent()

View File

@@ -0,0 +1,113 @@
import multiprocessing
from time import sleep
from datetime import datetime, time
from logging import INFO
from vnpy.event import EventEngine
from vnpy.trader.setting import SETTINGS
from vnpy.trader.engine import MainEngine
from vnpy.gateway.ctp import CtpGateway
from vnpy.app.cta_strategy import CtaStrategyApp
from vnpy.app.cta_strategy.base import EVENT_CTA_LOG
SETTINGS["log.active"] = True
SETTINGS["log.level"] = INFO
SETTINGS["log.console"] = True
ctp_setting = {
"用户名": "",
"密码": "",
"经纪商代码": "",
"交易服务器": "",
"行情服务器": "",
"产品名称": "",
"授权编码": "",
"产品信息": ""
}
def run_child():
"""
Running in the child process.
"""
SETTINGS["log.file"] = True
event_engine = EventEngine()
main_engine = MainEngine(event_engine)
main_engine.add_gateway(CtpGateway)
cta_engine = main_engine.add_app(CtaStrategyApp)
main_engine.write_log("主引擎创建成功")
log_engine = main_engine.get_engine("log")
event_engine.register(EVENT_CTA_LOG, log_engine.process_log_event)
main_engine.write_log("注册日志事件监听")
main_engine.connect(ctp_setting, "CTP")
main_engine.write_log("连接CTP接口")
sleep(10)
cta_engine.init_engine()
main_engine.write_log("CTA策略初始化完成")
cta_engine.init_all_strategies()
sleep(60) # Leave enough time to complete strategy initialization
main_engine.write_log("CTA策略全部初始化")
cta_engine.start_all_strategies()
main_engine.write_log("CTA策略全部启动")
while True:
sleep(1)
def run_parent():
"""
Running in the parent process.
"""
print("启动CTA策略守护父进程")
# Chinese futures market trading period (day/night)
DAY_START = time(8, 45)
DAY_END = time(15, 30)
NIGHT_START = time(20, 45)
NIGHT_END = time(2, 45)
child_process = None
while True:
current_time = datetime.now().time()
trading = False
# Check whether in trading period
if (
(current_time >= DAY_START and current_time <= DAY_END)
or (current_time >= NIGHT_START)
or (current_time <= NIGHT_END)
):
trading = True
# Start child process in trading period
if trading and child_process is None:
print("启动子进程")
child_process = multiprocessing.Process(target=run_child)
child_process.start()
print("子进程启动成功")
# 非记录时间则退出子进程
if not trading and child_process is not None:
print("关闭子进程")
child_process.terminate()
child_process.join()
child_process = None
print("子进程关闭成功")
sleep(5)
if __name__ == "__main__":
run_parent()