Files
Quant_Code/999.账户相关/simnow_trader/tmp/on_time_simnow_old.py

123 lines
4.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import subprocess
import schedule
import time
from datetime import datetime
# jerome增加akshare库
import akshare as ak
# jerome:增加下列库用于爬虫获取主力连续代码
import pandas as pd
import requests
from bs4 import BeautifulSoup
import csv
import re
import os
# 获取当前工作目录
current_directory = os.getcwd()
print("当前工作目录:", current_directory)
# 设置新的工作目录
new_directory = "C:/simnow_trader"
os.chdir(new_directory)
# 验证新的工作目录
updated_directory = os.getcwd()
print("已更改为新的工作目录:", updated_directory)
# 定义要启动的文件
files_to_run = ['dingdanliu_nb.py']
def run_scripts():
print("启动程序...")
for file in files_to_run:
time.sleep(1)
# 使用subprocess模块运行命令
subprocess.Popen(['start', 'cmd', '/k', 'python', file], shell=True)
print(file)
print(datetime.now(),'程序重新启动完成,等待明天关闭重启')
def close_scripts():
print("关闭程序...")
# 通过创建一个包含关闭指定窗口命令的批处理文件来关闭CMD窗口
def close_specific_cmd_window(cmd_window_title):
with open("close_cmd_window.bat", "w") as batch_file:
batch_file.write(f'@echo off\nfor /f "tokens=2 delims=," %%a in (\'tasklist /v /fo csv ^| findstr /i "{cmd_window_title}"\') do taskkill /pid %%~a')
# 运行批处理文件
subprocess.run("close_cmd_window.bat", shell=True)
# 循环关闭所有脚本对应的CMD窗口
for title in files_to_run:
close_specific_cmd_window(title)
print(datetime.now(),'已关闭程序,等待重新运行程序')
# jerome:增加使用akshare获取期货的手续费等数据并保存到对应目录下
def get_futures_fees_info():
futures_fees_info_df = ak.futures_fees_info()
futures_fees_info_df[['品种代码', '交割月份']] = futures_fees_info_df['合约'].apply(lambda x: pd.Series(split_alpha_numeric(x)))
futures_fees_info_df.to_csv(r'./futures_fees_info.csv', index=False)
print("期货费率表已经保存为futures_fees_info.csv")
def get_main_contacts():
url = "https://www.9qihuo.com/hangqing"
# 发送GET请求禁用SSL验证
response = requests.get(url, verify=False)
response.encoding = 'utf-8' # 确保编码正确
# 解析网页内容
soup = BeautifulSoup(response.text, 'lxml')
# 找到目标表格
table = soup.find('table', {'id': 'tblhangqinglist'})
# 初始化CSV文件
with open('tmp_main_contacts.csv', mode='w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
# 遍历表格的所有行
for row in table.find_all('tr'):
# 获取每一行的所有单元格
cols = row.find_all(['th', 'td'])
# 提取文本内容并写入CSV文件
writer.writerow([col.text.strip() for col in cols])
df = pd.read_csv('./tmp_main_contacts.csv',encoding='utf-8')
df['交易品种'] = df['合约'].str.split(r'[()]', n=1, expand=True)[0]
df['主连代码'] = df['合约'].str.split(r'[()]', n=2, expand=True)[1]
df[['品种代码', '交割月份']] = df['主连代码'].apply(lambda x: pd.Series(split_alpha_numeric(x)))
df.to_csv('./main_contacts.csv')
print("期货主力品种表已经保存为main_contacts.csv")
os.remove("./tmp_main_contacts.csv")
# 拆分字母和数字的函数
def split_alpha_numeric(s):
match = re.match(r"([a-zA-Z]+)([0-9]+)", s)
if match:
return match.groups()
else:
return (s, None) # 如果没有匹配返回原始字符串和None
# 设置定时任务,关闭程序
schedule.every().day.at("15:30").do(close_scripts)
schedule.every().day.at("03:00").do(close_scripts)
# 设置定时任务,启动程序
schedule.every().day.at("08:57").do(run_scripts)
schedule.every().day.at("20:55").do(run_scripts)
# # # 设置定时任务生成futures_fees_info和main_contacts
schedule.every().day.at("20:50").do(get_futures_fees_info)
schedule.every().day.at("20:50").do(get_main_contacts)
# 保持脚本运行,等待定时任务触发
while True:
schedule.run_pending()
time.sleep(1)