def get(self, request): """成交分笔明细""" db = self.mongo_conn.hotcow self.collection = db.trading_data tasks = [] if Base(TradingDay, **{ 'day': str(datetime.date.today()) }).findfilter(): sk_all = cache.iter_keys('cache_code_info_*') for i in sk_all: sk_info = cache.get(i) if sk_info and sk_info[ 'market_value'] and sk_info['market_value'] <= 500: if not Base( MyChoiceData, **{ 'code': sk_info['code'], 'trading_day': str(datetime.date.today()), }).findfilter(): tasks.append(self._constantly_deal( sk_info['exchange'])) asyncio.set_event_loop(asyncio.new_event_loop()) # 创建新的协程 loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks)) loop.close() return Response({'MainFlows': 'data update node'})
async def _close_day(self, sid, code_name): """收盘数据""" url = f'{settings.QT_URL1}appstock/app/fqkline/get?_var=kline_dayqfq¶m=' \ f'{code_name},day,{datetime.date.today().strftime("%Y-%m-%d")},,320,qfq' async with aiohttp.ClientSession() as session: url_info = await self.fetch(session, url) history_data = json.loads(url_info.split('=')[1]) # 获取分价表 day_data = [] if 'qfqday' in history_data['data'][code_name]: day_data = history_data['data'][code_name]['qfqday'] elif 'day' in history_data['data'][code_name]: day_data = history_data['data'][code_name]['day'] if day_data: for price in day_data: if not Base( StockPrice, **{ 'code': code_name[2:], 'trading_day': price[0] }).findfilter(): add_price = { 'sk_info_id': sid, 'code': code_name[2:], 'trading_day': price[0], 'open': float(price[1]), 'close': float(price[2]), 'high': float(price[3]), 'low': float(price[4]), 'hand_number': eval(price[5]) } Base(StockPrice, **add_price).save_db() return None
def get(self, request): """获取腾讯时时交易量""" data = request.GET if data and 'code' in data: code_data = [] code_query = Base( StockPrice, **{ 'code': data['code'], 'trading_day__in': trading_day(9) }).findfilter() for i in code_query: code_data.append({ 'open': i.open, 'close': i.close, 'high': i.high, 'low': i.low, 'average': i.average, 'trading_day': i.trading_day, 'hand_number': round(i.hand_number * i.average / 1000000, 2), 'turnover_rate': f'{round(i.hand_number / (i.sk_info.circulate_equity * 1000000) * 100, 2)}%', 'bidding_rate': f'{round(i.bidding_rate * 100, 0)}%', 'main_amount': i.main_amount, 'loose_amount': i.loose_amount, }) code_info = Base(StockInfo, **{ 'db_status': 1, 'code': data['code'] }).findfilter() if code_info: code = f'{str(code_info[0].exchange).lower()}{data["code"]}' context = { 'param': code_data, 'code': data['code'], 'code_name': code_info[0].name, 'flow_data': self.money_flow(code), 'total_flow': self.total_flow(code) } return render(request, 'sk_optional/datashow.html', context) return render(request, 'sk_optional/datashow.html', {'code_name': '无数据,请输入正确的代码'})
async def _ma_day(self, code_name): """日均线""" url = f'{settings.QT_URL3}data/index.php?appn=price&c={code_name}' async with aiohttp.ClientSession() as session: url_info = await HistoryDealsViewSet.fetch(session, url) price_query = re.findall('".*"', url_info) if price_query: price_distribute = str(price_query[0]).replace('"', '').split('^') if price_distribute: average, hand_number, active_number = 0, 0, 0 for i in price_distribute: num = str(i).split('~') average += eval(num[0]) * eval(num[2]) hand_number += eval(num[2]) active_number += eval(num[1]) Base( StockPrice, **{ 'code': code_name[2:], 'trading_day': datetime.date.today() }).update({ 'average': round(average / hand_number, 2), 'active_number': active_number, 'bidding_rate': round(active_number / hand_number, 2) }) return None
async def _constantly_deal(self, code: str) -> None: """时时成交""" deal_data: list = [] for i in range(0, 200): url = f'{settings.QT_URL3}data/index.php?appn=detail&action=data&c={code}&p={i}' async with aiohttp.ClientSession() as session: url_info = await HistoryDealsViewSet.fetch(session, url) if url_info: deal_info = re.search('\".*\"', url_info) for m in deal_info.group().replace('"', '').split('|'): ms = m.split('/') deal_data.append( (eval(ms[0]), ms[1], eval(ms[2]), eval(ms[3]), eval(ms[4]), eval(ms[5]), ms[6])) else: break if deal_data: add_data = { 'code': code[2:], 'trading_day': str(datetime.date.today()), 'trading_list': deal_data } mongo_id = self.collection.insert(add_data) Base( MyChoiceData, **{ 'code': code[2:], 'trading_day': str(datetime.date.today()), 'mongo_id': mongo_id }).save_db() return None
def get(self, request): """分笔交易数据展示""" data = request.GET if not data: code_info = Base(StockInfo, **{ 'db_status': 1, 'my_choice': 1 }).findfilter() context = { 'param': code_info, } return render(request, 'sk_optional/analysisshow.html', context) elif data and 'code' in data: if 'day' in data: redis_key = f'constantly_deal_{str(data["code"]).lower()}_{data["day"]}_cache' else: redis_key = f'constantly_deal_{str(data["code"]).lower()}_{datetime.date.today()}_cache' read_cache = cache.get(redis_key) if read_cache['data']: minutes_data = TradingVoViewSet.minutes_data( read_cache['data']) # 生成图表 chart_data = { 'bar': ['Total', 'liu_ru', 'liu_chu', 'z_buy', 'z_sell'], 'keys': [], 'liu_ru': [], 'liu_chu': [], 'z_buy': [], 'z_sell': [], 'Total': [] } for i in minutes_data: chart_data['keys'].append(i) chart_data['liu_ru'].append(minutes_data[i]['liu_ru']) chart_data['liu_chu'].append(minutes_data[i]['liu_chu']) chart_data['z_buy'].append(minutes_data[i]['z_buy']) chart_data['z_sell'].append(minutes_data[i]['z_sell']) chart_data['Total'].append(minutes_data[i]['total']) plt.figure(figsize=(65, 16)) for keys in chart_data['bar']: plt.bar(chart_data['keys'], chart_data[keys], label=keys) plt.xticks(rotation=45) plt.legend(loc='upper left', frameon=False) jingliu = round( (sum(chart_data['liu_ru']) - sum(chart_data['liu_chu'])) / 10000, 2) zhumai1 = round(sum(chart_data['z_buy']) / 10000, 2) zhumai2 = round(sum(chart_data['z_sell']) / 10000, 2) totle = sum(chart_data['Total']) / 10000 plt.title( f"{data['code'][:-3]} Jingliu ({jingliu} {round(jingliu / totle, 2) * 100}%) " f"Zhumai ({round(zhumai1 - zhumai2, 2)} {round((zhumai1 - zhumai2) / totle, 2) * 100}%) ", fontsize='60') plt.show() return redirect('/skoptional/analysisshow/') return redirect('/skoptional/analysisshow/')
async def _read_data(self, url, num_day, **kwargs): async with aiohttp.ClientSession() as session: url_info = await HistoryDealsViewSet.fetch(session, url) if num_day == 'many_day': url_data = url_info.replace(';', '').replace('\'', '').split('\n') for code in url_data: amount_data = code.split('=') if len(amount_data) != 2: continue amount_date = amount_data[1].split('~') amount_dict = {} for i in amount_date: if '^' in i: index = amount_date.index(i) amount_dict[i.split('^')[0]] = (float( amount_date[index - 2]), float(amount_date[index - 1])) code_price = Base( StockPrice, **{ 'code': amount_data[0].split('_')[-1][2:] }).findfilter() if code_price: for price in code_price: if str(price.trading_day) in amount_dict and\ (price.main_amount == 0 or not price.main_amount): price.main_amount = amount_dict[str( price.trading_day)][0] price.loose_amount = amount_dict[str( price.trading_day)][1] price.save() else: url_data = url_info.replace(';', '') amount_data = url_data.split('=')[1].replace('"', '').split('~') Base( StockPrice, **{ 'code': kwargs.get('code'), 'trading_day': str(datetime.date.today()) }).update({ 'main_amount': amount_data[2], 'loose_amount': amount_data[5] })
def trading_day(days: int): """获取交易日列表""" trading_days = cache.get('trading_days_cache') if not trading_days: date_query = Base(TradingDay, **{ 'day__lte': datetime.date.today() }).findfilter() trading_days = [str(i.day) for i in date_query] trading_days.reverse() cache.set('trading_days_cache', trading_days, timeout=30 * 60 * 60) return trading_days[:days]
def get(self, request): query_day = Base(TradingDay, **{ 'day': datetime.date.today() }).findfilter() if query_day: # 抓取数据 my_code = Base(StockInfo, **{ 'db_status': 1, 'my_choice': 1 }).findfilter() tasks = [] for i in my_code: tasks.append( self._constantly_deal(f'{i.exchange}{i.code}'.lower())) if tasks: asyncio.set_event_loop(asyncio.new_event_loop()) # 创建新的协程 loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks)) loop.close() return Response({"BasisData": {"Status": 1, "msg": "Trading Vo Node"}})
def get(self, request): """同步当天资金流向""" if Base(TradingDay, **{'day': datetime.date.today()}).findfilter(): tasks = [] sk_all = cache.iter_keys('cache_code_info_*') for i in sk_all: code = cache.get(i) tasks.append(self._ma_day(code['exchange'], )) asyncio.set_event_loop(asyncio.new_event_loop()) # 创建新的协程 loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks)) loop.close() return Response({'MainFlows': 'data update node'})
def post(self, request): code = str(request.body.decode()).split('=')[1] code_query = Base(StockInfo, **{ 'db_status': 1, 'code': code }).findfilter() if code_query: if code_query[0].my_choice == 1: code_query[0].my_choice = 0 else: code_query[0].my_choice = 1 code_query[0].save() return redirect('/skoptional/analysisshow/')
def get(self, request): """能量回归""" db = self.mongo_conn.hotcow collection = db.trading_data code = '603081' trading_day = Base( MyChoiceData, **{ 'code': code, 'trading_day__in': ['2018-12-17', '2018-12-18', '2018-12-19', '2018-12-20'] }).findfilter() for i in trading_day: trading_query = collection.find_one(ObjectId(i.mongo_id)) if trading_query: self.chart_show(trading_query) return Response({'MainFlows': 'data update node'})
def get(self, request): region_dict = cache.get('code_region_data_cache') conecpt_dict = cache.get('code_conecpt_data_cache') all_code = ts_api(api_name='stock_basic', params={'list_status': 'L'}, fields=['ts_code', 'name', 'list_date']) times_number = 100 for num in range(0, len(all_code) // times_number + 1): code = '' for i in all_code[num * times_number:times_number * (num + 1)]: if 'ST' in i[1]: continue code_split = str(i[0]).split('.') if not Base(StockInfo, **{ 'db_status': 1, 'code': code_split[0] }).findfilter(): listed_time = datetime.datetime.strptime(i[2], "%Y%m%d") jet_lag = (datetime.datetime.now() - listed_time).days if jet_lag <= self.listed_day: new = 1 elif jet_lag <= self.listed_day * 2: new = 2 else: new = 0 Base( StockInfo, **{ 'db_status': 1, 'exchange': code_split[1], 'code': code_split[0], 'name': i[1], 'new': new, 'listed_time': datetime.datetime.strftime(listed_time, '%Y-%m-%d'), }).save_db() code += f'{code_split[1].lower() + code_split[0]},' open_url = requests.get(settings.QT_URL2 + code, timeout=120) code_list = re.findall('".*"', open_url.text) for c in code_list: code_price_info = c.replace('"', '').split('~') query_code = Base( StockInfo, **{ 'db_status': 1, 'code': code_price_info[2] }).findfilter() if query_code: # 地域 if region_dict and query_code[0].code in region_dict: query_code[0].region = region_dict[query_code[0].code] # 概念 if conecpt_dict and query_code[0].code in conecpt_dict: query_code[0].concept['concept'] = conecpt_dict[ query_code[0].code] # 盘口 jet_lag = (datetime.date.today() - query_code[0].listed_time).days if jet_lag <= self.listed_day: new = 1 elif jet_lag <= self.listed_day * 2: new = 2 else: new = 0 query_code[0].new = new query_code[0].name = code_price_info[1] if code_price_info[-9] and code_price_info[3]: query_code[0].total_equity = round( float(code_price_info[-9]) / float(code_price_info[3]), 3) query_code[0].circulate_equity = round( float(code_price_info[-10]) / float(code_price_info[3]), 3) query_code[0].market_value = round( query_code[0].total_equity * float(code_price_info[3]), 0) query_code[0].save() # 缓存数据到redis code_all = Base(StockInfo, **{'db_status': 1}).findfilter() for codes in code_all: code_dict = { 'exchange': f'{str(codes.exchange).lower()}{codes.code}', 'code': codes.code, 'circulate_equity': codes.circulate_equity, 'market_value': codes.market_value, 'new': codes.new, 'sid': codes.id } cache.set( f'cache_code_info_{str(codes.exchange).lower()}~{codes.code}', code_dict, timeout=24 * 60 * 60) return Response( {"BasisData": { "Status": 1, "msg": "Basis data update node" }})