def get_stock_price_in_n_days(code, query_date, trade_date_list): # 获取起始日,结束日 用于查询行情 # TODO: 优化 trade_date_list 改成 DataFrame ,df.first() df.last() start_date = trade_date_list[0] end_date = trade_date_list[len(trade_date_list) - 1] df_price = ts.pro_bar(ts_code=code, adj='qfq', start_date=start_date, end_date=end_date, freq='D') if df_price is None: print(code + ":无行情数据") stock_info = {'股票代码': [code], '龙虎榜日期': [query_date]} stock_info_df = pd.DataFrame(stock_info) try: counts = 0 for trade_date in trade_date_list: if counts == len(trade_date_list): break counts = counts + 1 df_price.copy() open = df_price[df_price['trade_date'] == trade_date]['open'].iloc[0] close = df_price[df_price['trade_date'] == trade_date]['close'].iloc[0] stock_info_df['T+' + str(counts) + '_开盘价'] = open stock_info_df['T+' + str(counts) + '_收盘价'] = close except IndexError as e: # 当日收盘前会出现该异常 raise CustomizeException(None, '查询日期:[' + end_date + ']尚未得到该日行情信息') return stock_info_df
def get_two_trade_date_open_difference(stock_code, date, trade_date_t1, trade_date_t2): price_df = ts.pro_bar(ts_code=stock_code, adj='qfq', start_date=trade_date_t1, end_date=trade_date_t2, freq='D') try: open_t2 = price_df[price_df['trade_date'] == trade_date_t2]['open'].iloc[0] open_t1 = price_df[price_df['trade_date'] == trade_date_t1]['open'].iloc[0] except IndexError as e: raise CustomizeException(None, '查询日期:[' + trade_date_t2 + ']尚未得到开盘价') open_different = open_t2 - open_t1 open_info = { 'stock_code': [stock_code], 'query_date': [date], 'open_t1': [open_t1], 'open_t2': [open_t2], 'open_different': [open_different] } open_info_df = pd.DataFrame(open_info) print('查询日期:[' + date + '], 股票代码:[' + stock_code + '], T+2开盘价 - T+1开盘价:[%.4f' % open_different + ']') return open_info_df
def get_trade_date_list_by_num(self): trade_date_df = self.__get_trade_date_list_df() # TODO: 从trade_date_df中截取即可 if len(trade_date_df) < self.day_num: raise CustomizeException(None, '查询起始日到今日不足自定义查询天数') date_list = [] # TODO: # 1、i 与 index 定义重复,去掉i # 2、改掉C语言思维模式,多用集成api i = 0 for index, row in trade_date_df.iterrows(): if i == 0: i = i + 1 # 当日数据不要 continue if i == self.day_num: break i = i + 1 date_list.append(row['cal_date']) return date_list
def get_last_two_trade_date(start_date): trade_date_list = get_trade_date_list(start_date) if len(trade_date_list) < 3: raise CustomizeException(None, '查询日期:[' + start_date + ']到今日不足两个交易日') two_trade_date_list = [trade_date_list[1], trade_date_list[2]] return two_trade_date_list
def get_one_fund_heavy_stock_hold(self) -> pd.DataFrame: print('单只基金重仓(多季):fund_code is ' + self.fund_code) single_fund_df = pd.DataFrame if self.__MOCK_MODE: single_fund_df = md.get_mock_fund_data(self.report_date_list) else: url = self.__generate_fund_heavy_stock_url() headers = self.__generate_headers() # 拼装data cmd = '[{"Name":"Common.CloudDynamicPicker","Paras":[{"Key":"command","Value":" Report name=F9_2.Fund.StocInvePortfolio.HeavHeldStockStock23 windCode=[' + \ self.fund_code + '] reportDate=[' + ','.join(self.report_date_list) + \ '] industryType=[''] sort=[10=asc,2=desc] showcolumnname=all "},{"Key":"digits","Value":4}],"CacheLevel":1,"Async":false}]' data = {'invoke': cmd} response = requests.post(url=url, data=data, headers=headers) if 200 == response.status_code: text = json.loads(response.text) if text.get('Result') is not None: data = text.get('Result').get('Data') single_fund_df = pd.DataFrame(data) else: print(text) raise CustomizeException( None, "Invalid response: Result is None") else: raise CustomizeException(response.status_code, 'Invalid response, status_code=') single_fund_df.rename(columns={ 'StockCode': '股票代码', 'StockName': '股票名称', 'MarketValue': '持仓市值(亿)', 'Share': '持仓数量', 'StockMarketValuePer': '占股票市值比(%)', 'FundNetPer': '占基金净值比(%)', 'TradeableSharePer': '占流通股本比(%)', 'PreSub': '持仓数量变动比(%)', 'PerChange': '股价涨跌幅(%)', 'PreSubVol': '持仓数量变动', 'RptDate': '报告期', 'IndustryName': '所属行业' }, inplace=True) return single_fund_df
def get_trade_date_list_to_today(self): trade_date_df = self.__get_trade_date_list_df() # TODO: 从trade_date_df中截取即可 if len(trade_date_df) < 0: raise CustomizeException(None, '查询起始日到今日之间无交易日') date_list = [] for index, row in trade_date_df.iterrows(): date_list.append(row['cal_date']) return date_list
def get_last_two_trade_date(date): now = datetime.datetime.today().strftime('%Y%m%d') date_df = pro.trade_cal(start_date=date, end_date=now) trade_date_df = date_df[date_df['is_open'] == 1].head(3) date_list = [] for index, row in trade_date_df.iterrows(): date_list.append(row['cal_date']) if len(date_list) < 3: raise CustomizeException(None, '查询日期到今日不足两个交易日') trade_date_list = [date_list[1], date_list[2]] return trade_date_list
def test_customize_exception(): y = 0 if y > 0: raise CustomizeException(404, 'Invalid response, status_code=') else: raise CustomizeException(None, 'Invalid response: Result is None')