主要变更: - 重构 models: 统一使用 SQLAlchemy ORM,分离 Pydantic schemas - 新增 service_manager: 服务启动/停止统一管理 - 新增 data_downloader: 基于 xtquant 的数据下载服务 - 简化 main.py: 只启动必要服务 (Redis, Database) - 更新 .gitignore: 排除 xtquant 数据目录
285 lines
12 KiB
Python
285 lines
12 KiB
Python
import time
|
|
import pandas as pd
|
|
import numpy as np
|
|
from datetime import datetime, timedelta
|
|
import json
|
|
import requests
|
|
from xtquant import xtdata
|
|
from xtquant import xtdatacenter as xtdc
|
|
|
|
import schedule
|
|
|
|
class XTDataSynchronizer:
|
|
def __init__(self):
|
|
xtdc.set_token('e83d8eec5226c0b4db4a1d40830e09e4ffe73e15')
|
|
xtdc.init()
|
|
xtdc.set_allow_optmize_address(['115.231.218.73:55310', '115.231.218.79:55310', '218.16.123.11:55310', '218.16.123.27:55310'])
|
|
xtdata.download_sector_data()
|
|
xtdata.download_history_contracts()
|
|
self.headers = {
|
|
"Content-Type": "application/json; charset=UTF-8"
|
|
}
|
|
self.api = "http://localhost:5000/api/v1"
|
|
self.fields = ["open","high","low","close","volume","amount"]
|
|
self.concepts = self.get_concepts()
|
|
self.start_time =(datetime.now() - timedelta(days=120)).strftime("%Y%m%d")
|
|
self.end_time = (datetime.now() + timedelta(days=1)).strftime("%Y%m%d") #'20240311'
|
|
self.download(self.concepts)
|
|
|
|
def run(self):
|
|
for concept in self.concepts:
|
|
xtdata.subscribe_quote(concept, period='1d', start_time='', end_time='', count=1, callback=None)
|
|
schedule.clear()
|
|
schedule.every(60*2).seconds.do(self.sync)
|
|
now = datetime.now().strftime('%Y-%m-%d%H:%M:%S')
|
|
while True:
|
|
schedule.run_pending()
|
|
|
|
|
|
def download(self, stocks):
|
|
for stock in stocks:
|
|
xtdata.download_history_data(stock, '1d', self.start_time, self.end_time)
|
|
|
|
def get_concepts(self):
|
|
url = f"{self.api}/trade/all_concepts"
|
|
concepts = []
|
|
conceptDtos = json.loads(requests.get(url,headers = self.headers).text)
|
|
for concept in conceptDtos:
|
|
concepts.append(concept['conceptCode'])
|
|
print(f'concepts: {conceptDtos}')
|
|
return concepts
|
|
|
|
def get_stocks(self):
|
|
url = f"{self.api}/trade/all_stocks"
|
|
stocks = []
|
|
stockdtos = json.loads(requests.get(url,headers = self.headers).text)
|
|
for stock in stockdtos:
|
|
stocks.append(stock)
|
|
print(stocks)
|
|
return stocks
|
|
|
|
|
|
def get_xt_concept_infos(self):
|
|
concepts=[]
|
|
xt_sector_index_list = xtdata.get_stock_list_in_sector("概念指数")
|
|
for sector in xt_sector_index_list:
|
|
detail = xtdata.get_instrument_detail(sector)
|
|
InstrumentName = detail['InstrumentName'].replace("\r\n","")
|
|
concepts.append(f"{detail['InstrumentID']}.{detail['ExchangeID']}")
|
|
print(f",('{detail['InstrumentID']}.{detail['ExchangeID']}','{InstrumentName}')")
|
|
return concepts
|
|
|
|
def get_stocks_in_sector(self,selector_code):
|
|
#f = open("D:\Workspace\stocks.txt", "a")
|
|
sector = xtdata.get_instrument_detail(selector_code)
|
|
sector_code = f"{sector['InstrumentID']}.{sector['ExchangeID']}"
|
|
sector_name = sector['InstrumentName'].replace("\r\n","")
|
|
stocks =[]
|
|
#f.write(f",('{sector_code}','{sector_name}','[]',1,2)\r")
|
|
print(f"--,('{sector_code}','{sector_name}','[]',1,2)")
|
|
for stock in xtdata.get_stock_list_in_sector(selector_code):
|
|
if stock.startswith('688') or stock.startswith('300') or \
|
|
stock.startswith('900') or stock.endswith('.BJ') or stock.startswith('301'):
|
|
continue
|
|
detail = xtdata.get_instrument_detail(stock)
|
|
stock_code = f"{detail['InstrumentID']}.{detail['ExchangeID']}"
|
|
stock_name = detail['InstrumentName']
|
|
if stock_name.startswith('ST') or stock_name.startswith('*ST'):
|
|
continue
|
|
#concept = f'["000001.SH"]'
|
|
#if stock_code.endswith('.SZ'):
|
|
# concept=f'["399001.SZ"]'
|
|
concept = f'["{selector_code}"]'
|
|
#print(f",('{stock_code}','{stock_name}','{concept}',1,1,1)")
|
|
#f.write(f",('{stock_code}','{stock_name}','{concept}',1,1,1)\r")
|
|
stocks.append(stock_code)
|
|
#print(f"Stocks -> {len(stocks)}")
|
|
#f.close()
|
|
return stocks
|
|
|
|
def sync(self,include_history=False):
|
|
calendars = []
|
|
if include_history:
|
|
calendars = xtdata.get_trading_calendar('SH', self.start_time , self.end_time)
|
|
else:
|
|
self.start_time = (datetime.now() - timedelta(days=20)).strftime("%Y%m%d")
|
|
calendars = pd.Series(xtdata.get_trading_calendar('SH', self.start_time , self.end_time)).iloc[-2:]
|
|
|
|
for calendar in calendars:
|
|
print(f'Start sync kdata. bartime:{calendar}')
|
|
prices = xtdata.get_market_data_ex(field_list =self.fields , \
|
|
stock_list = self.concepts, period = '1d', \
|
|
start_time = calendar, end_time = calendar, \
|
|
count = -1, dividend_type = 'none', fill_data = True)
|
|
for sector in prices.keys():
|
|
kdata=[]
|
|
for item in self.convert_to_kdata(sector, '1d', prices[sector]):
|
|
kdata.append(item)
|
|
url = self.api + "/trade/kdata/sync"
|
|
data = json.dumps({'kdata':kdata})
|
|
print(data)
|
|
responseBody = requests.post(url,data = data,headers=self.headers).text
|
|
print(responseBody)
|
|
|
|
|
|
def convert_to_kdata(self, stock, period, prices):
|
|
kdata = []
|
|
for index,row in prices.iterrows():
|
|
kdata.append({
|
|
"code": stock,
|
|
"datetime":index,
|
|
"period": period,
|
|
"open":row['open'],
|
|
"high":row['high'],
|
|
"low":row['low'],
|
|
"close":row['close'],
|
|
"volume":row['volume'],
|
|
"amount":row['amount']
|
|
})
|
|
return kdata
|
|
|
|
def convert_to_kdata2(self, stock, period, index, row):
|
|
if np.isnan(np.mean(row['open'])):
|
|
return None
|
|
|
|
return {
|
|
"code": stock,
|
|
"datetime":index,
|
|
"period": period,
|
|
"open":row['open'],
|
|
"high":row['high'],
|
|
"low":row['low'],
|
|
"close":row['close'],
|
|
"volume":row['volume'],
|
|
"amount":row['amount']
|
|
}
|
|
|
|
|
|
|
|
def list_potential_stocks(self,concepts):
|
|
calendars = pd.Series(xtdata.get_trading_calendar('SH', self.start_time , self.end_time)).iloc[-2:]
|
|
existing=[]
|
|
for concept in concepts:
|
|
detail = xtdata.get_instrument_detail(concept)
|
|
concept_name = detail['InstrumentName']
|
|
stocks = self.get_stocks_in_sector(concept)
|
|
for stock in stocks:
|
|
if stock.startswith('688') or stock.startswith('300') or \
|
|
stock.startswith('900') or stock.endswith('.BJ') or stock.startswith('301'):
|
|
continue
|
|
xtdata.download_history_data(stock, '1d', calendars.values[0], calendars.values[-1])
|
|
|
|
prices = xtdata.get_market_data_ex(field_list =self.fields , stock_list = stocks, period = '1d', \
|
|
start_time = calendars.values[0], end_time = calendars.values[-1], \
|
|
count = -1, dividend_type = 'none', fill_data = True)
|
|
print(f"--{concept} {concept_name}")
|
|
for stock in prices.keys():
|
|
if stock in existing:
|
|
continue
|
|
change_rate = (prices[stock].iloc[1]['close'] - prices[stock].iloc[0]['close']) / prices[stock].iloc[0]['close']
|
|
if change_rate >=0.09:
|
|
detail = xtdata.get_instrument_detail(stock)
|
|
stock_code = f"{detail['InstrumentID']}.{detail['ExchangeID']}"
|
|
stock_name = detail['InstrumentName']
|
|
conceptx = f'["{concept}"]'
|
|
print(f",('{stock_code}','{stock_name}','{conceptx}',1,1,1)")
|
|
existing.append(stock)
|
|
|
|
|
|
def list_concept_data(self,concepts):
|
|
self.concepts=concepts
|
|
self.download(self.concepts)
|
|
self.sync(True)
|
|
|
|
def sync_history(self):
|
|
stocks = self.get_stocks()
|
|
if len(stocks) == 0:
|
|
print("没有需要同步的股票代码")
|
|
return
|
|
|
|
print(f"{self.start_time}, {self.end_time}")
|
|
calendars = pd.Series(xtdata.get_trading_calendar('SH', self.start_time , self.end_time))
|
|
for stock in stocks:
|
|
xtdata.download_history_data(stock, '1d', calendars.values[0], calendars.values[-1])
|
|
xtdata.download_history_data(stock, '5m', calendars.values[0], calendars.values[-1])
|
|
|
|
min5_prices = xtdata.get_market_data_ex(field_list =self.fields , stock_list = stocks, period = '5m', \
|
|
start_time = calendars.values[0], end_time = calendars.values[-1], \
|
|
count = -1, dividend_type = 'front', fill_data = True)
|
|
|
|
daily_prices = xtdata.get_market_data_ex(field_list =self.fields , stock_list = stocks, period = '1d', \
|
|
start_time = calendars.values[0], end_time = calendars.values[-1], \
|
|
count = -1, dividend_type = 'front', fill_data = True)
|
|
#convert_to_kdata2(self, stock, period, index, row):
|
|
for index in min5_prices[stocks[0]].index:
|
|
kdata = []
|
|
for stock in min5_prices.keys():
|
|
tempKdata = self.convert_to_kdata2(stock,'5m', index, min5_prices[stock].loc[index])
|
|
if tempKdata is not None:
|
|
kdata.append(self.convert_to_kdata2(stock,'5m', index, min5_prices[stock].loc[index]))
|
|
|
|
for stock in daily_prices.keys():
|
|
daily_index = index[0:8]
|
|
tempKdata = self.convert_to_kdata2(stock,'1d',daily_index, daily_prices[stock].loc[daily_index])
|
|
if tempKdata is not None:
|
|
kdata.append(self.convert_to_kdata2(stock,'1d',daily_index, daily_prices[stock].loc[daily_index]))
|
|
data = json.dumps({
|
|
'realTime': index,
|
|
'kdata':kdata,
|
|
'positionInfos': [],
|
|
'allowTrade': False,
|
|
'account':{
|
|
'Balance': 0,
|
|
'available': 0,
|
|
}
|
|
})
|
|
|
|
url = self.api + "/bssignal/detect"
|
|
responseBody = requests.post(url,data = data,headers=self.headers).text
|
|
#time.sleep(2)
|
|
print(index)
|
|
|
|
def get_kdata(self, stock,period):
|
|
url = f"{self.api}/trade/kdata/{period}/{stock}/100"
|
|
kdata = json.loads(requests.get(url,headers = self.headers).text)
|
|
index = []
|
|
open=[]
|
|
high=[]
|
|
low=[]
|
|
close=[]
|
|
spike = []
|
|
for item in kdata:
|
|
index.append(pd.to_datetime(item["dateTime"]))
|
|
open.append(item["open"])
|
|
high.append(item["high"])
|
|
low.append(item["low"])
|
|
close.append(item["close"])
|
|
spike.append(item["spike"])
|
|
data = {
|
|
"DateTime":pd.Series(index),
|
|
"Open":pd.Series(open),
|
|
"High":pd.Series(high),
|
|
"Low":pd.Series(low),
|
|
"Close":pd.Series(close),
|
|
"Spike":pd.Series(spike)
|
|
}
|
|
df = pd.DataFrame(data)
|
|
df.set_index("DateTime",inplace=True)
|
|
return df
|
|
|
|
def get_ret(self):
|
|
ret_sector_data = xtdata.get_stock_list_in_sector("沪深基金")
|
|
for stock in ret_sector_data:
|
|
detail = xtdata.get_instrument_detail(stock)
|
|
stock_code = f"{detail['InstrumentID']}.{detail['ExchangeID']}"
|
|
stock_name = detail['InstrumentName']
|
|
print(f"('{stock_code}','{stock_name}','[]',1,1)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|