def init_finance_table(self, start_date=0): self.authenticate() self.stock = jdk.normalize_code(self.stock) self.stock_info = jdk.get_security_info(self.stock) if self.stock_info is None: print('Error: Cannot get data or stock code not correct!') '''Internal usage. To get finance table''' q = jdk.query(jdk.valuation).filter(jdk.valuation.code == self.stock) end_date = datetime.now().date() if start_date == 0: df = jdk.get_fundamentals_continuously(q, end_date=end_date, count=5000) else: # get the days between start date and end date date_span = jdk.get_trade_days(start_date=start_date, end_date=end_date) if len(date_span) == 0: return df = jdk.get_fundamentals_continuously(q, end_date=end_date, count=len(date_span)) if df is None: return self.finance_data = df.swapaxes('items', 'minor_axis') self.finance_data = self.finance_data[self.stock] del self.finance_data['day.1'] del self.finance_data['code.1'] del self.finance_data['id'] return
def get_single_price(code: str, freq: str, start=None, end=None) -> pd.DataFrame: if start is None: start = jq.get_security_info(code).start_date if end is None: end = datetime.today() df = jq.get_price(code, start_date=start, end_date=end, frequency=freq, panel=False) print(df) return df
def delect_stop(stocks,begin_date,n=30*3): stock_list = list() begin_date = datetime.datetime.strptime(begin_date,"%Y-%m-%d") for stock in stocks: start_date = jq.get_security_info(stock).start_date if start_date < (begin_date - datetime.timedelta(days=n)).date(): stock_list.append(stock) return stock_list
def init_light(self): self.authenticate() self.stock = jdk.normalize_code(self.stock) self.stock_info = jdk.get_security_info(self.stock) if self.stock_info is None: print('Error: Cannot get data or stock code not correct!') self.finance_table = self.__generate_table_name() + '_finance' self.price_table = self.__generate_table_name() + '_price'
def getDateData(self, jqID, intDate): dataTable = self.cfg.dictDataTable[jq.get_security_info(jqID).type] sqlword = "SELECT * FROM %s where id='%s' and CONVERT(varchar(10), tm, 112)='%d'" % ( dataTable, jqID, intDate) data = pd.read_sql(sqlword, con=self.conn) if len(data) > 0: return data data = getJQTickData(jqID, intDate) updateTickData(data, dataTable) return data
def get_price(self, code, start_date='2005-01-01', end_date='2018-11-30'): '''Download stock data (adjusted close) Parameters ---------------------- code: str or int code of stock start_date: str start_date end_date: str end_date Returns ---------------------- normalized_code, pd.DataFrame ''' try: normalized_code = self.normalize_code(str(code)) except Exception as e: print(e) return [], None if normalized_code == "000001.XSHE": price_df = pd.read_csv("finance/data/000001.SXHE.csv", index_col=0) price_df = price_df.loc[start_date:end_date, ['open', 'close', 'high', 'low', 'volume']] else: security_info = get_security_info(normalized_code) if security_info is None: return [], None security_start_date = security_info.start_date security_end_date = security_info.end_date # compare date information of security and requery date if datetime.datetime.strptime( start_date, "%Y-%m-%d").date() < security_start_date: start_date = security_start_date if datetime.datetime.strptime( end_date, "%Y-%m-%d").date() > security_end_date: end_date = security_end_date price_df = get_price( normalized_code, start_date=start_date, end_date=end_date, frequency='daily', fields=['open', 'close', 'high', 'low', 'volume'], skip_paused=False, fq='pre') self.fill_missing_values(price_df) return normalized_code, price_df
def get_index_data(self, index_code, trade_days): open_date = jqdatasdk.get_security_info(index_code).start_date if (open_date > trade_days[0]): trade_days = jqdatasdk.get_trade_days(start_date=open_date) df = pd.DataFrame() for day in trade_days: dic = self._calc_pe_pb(index_code, day) if dic: df = df.append(dic, ignore_index=True) if not df.empty: df.set_index('day', inplace=True) return df
def remove_new(stocks, tradeDate=None, day=1): """ list: 去掉新股股票之后的股票列表 """ tradeDate = tradeDate if tradeDate is not None else datetime.datetime.now() nday = helper.get_ndays_before(str(tradeDate.date()), day) rm_news = [] for s in stocks: info = jq.get_security_info(s) # 上市日期小于指定日期 if str(info.start_date) < nday: rm_news.append(s) return rm_news
def draw_line(stock_name, type, days=600): info = jqdatasdk.get_security_info(stock_name) if info is None: return 'error' q = jqdatasdk.query(jqdatasdk.valuation).filter(jqdatasdk.valuation.code == stock_name) now = datetime.now() date = '%d-%d-%d' % (now.year, now.month, now.day) df = jqdatasdk.get_fundamentals_continuously(q, end_date=date, count=days) print(df['pe_ratio'].index) if type == 'PE': return draw_diagram(df['pe_ratio'], 'PE-TTM', stock_name, info.display_name) elif type == 'PB': return draw_diagram(df['pb_ratio'], 'PB', stock_name, info.display_name)
def get_all_financial_data(): df_set = [] jdk.auth('18951518869', 'ceshi123') for stock in stock_set: stock_info = jdk.get_security_info(stock) stock = stock.split('.')[0] df = read_finance_data(stock, 'pe_ratio', '2016-1-1', '2018-10-4') if df is None: print(stock) continue df_set.append(df) try: waveline.draw_diagram(df, 'PE-TTM', stock, stock_info.display_name) except: continue
def init(self): ''' Get price, open, close, high, low, volume. And finantial data, TTM, PB, etc. ''' self.authenticate() self.stock = jdk.normalize_code(self.stock) self.stock_info = jdk.get_security_info(self.stock) if self.stock_info is None: print('Error: Cannot get data or stock code not correct!') self.finance_table = self.__generate_table_name() + '_finance' self.price_table = self.__generate_table_name() + '_price' price_data = jdk.get_price(self.stock, start_date=self.stock_info.start_date, end_date=datetime.now()) # remove NaN data self.price_data = price_data.dropna() self.price_data.index.name = 'date' print('%s[%s] from %s - %s ' % (self.stock_info.display_name, self.stock, self.stock_info.start_date, self.stock_info.end_date))
def plot_index(index_code, df_, anno_text='', show=True): data = df_ PEs = data['pe'] low = round(PEs.quantile(0.3), 2) high = round(PEs.quantile(0.7), 2) plt.title( '%s-%s' % (index_code, jqdatasdk.get_security_info(index_code).display_name)) #l1, = plt.plot(data.index, data.pe, lw=LINE_W) l1, = plt.plot(data.index, data.pe) #latest day annotation mid_idx = int(data.shape[0] / 2) txt = 'Data: %s, PE: %.2f, %s' % (str( data.index[-1])[:10], PEs.iloc[-1], str(anno_text)) plt.text(data.index[mid_idx], PEs.max() - 1, txt, horizontalalignment='center') plt.axhline(high, ls='--', c='r', label=high) plt.axhline(low, ls='--', c='g', label=low) plt.legend() plt.show()
def getedate(self, c): return jq.get_security_info(c).end_date
def fill_stock_name(l): for stock in l: si = jq.get_security_info(stock.code) stock.name = si.display_name
def get_code_name(code): si = jq.get_security_info(code) return si.display_name
def convert_stk_code_to_ism_id(stk): return jq.get_security_info(stk).name
def run_chan_analysis(stock_code, end_date, stock_days, x_jizhun, stock_frequency, chanK_flag): jqdatasdk.auth('13381719059', 'GoodLuck2018') quotes = jqdatasdk.get_price(stock_code, datetime.datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S")-datetime.timedelta(days=stock_days) , end_date,\ frequency=stock_frequency,skip_paused=False,fq='pre') # print quotes # 缠论k线 quotes = parse2ChanK(quotes, quotes.values) if chanK_flag else quotes # print quotes quotes[quotes['volume'] == 0] = np.nan quotes = quotes.dropna() Close = quotes['close'] Open = quotes['open'] High = quotes['high'] Low = quotes['low'] T0 = quotes.index.values length = len(Close) # ht = HoverTool(tooltips=[ # ("date", "@date"), # ("open", "@open"), # ("close", "@close"), # ("high", "@high"), # ("low", "@low"), # ("volume", "@volume"), # ("money", "@money"),]) # TOOLS = [ht, WheelZoomTool(dimensions=['width']),\ # ResizeTool(), ResetTool(),\ # PanTool(dimensions=['width']), PreviewSaveTool()] fig = plt.figure(figsize=(20, 10)) ax1 = plt.subplot2grid((10, 4), (0, 0), rowspan=10, colspan=4) #fig = plt.figure() #ax1 = plt.axes([0,0,3,2]) X = np.array(range(0, length)) pad_nan = X + np.nan #计算上 下影线 max_clop = Close.copy() max_clop[Close < Open] = Open[Close < Open] min_clop = Close.copy() min_clop[Close > Open] = Open[Close > Open] #上影线 line_up = np.array([High, max_clop, pad_nan]) line_up = np.ravel(line_up, 'F') #下影线 line_down = np.array([Low, min_clop, pad_nan]) line_down = np.ravel(line_down, 'F') #计算上下影线对应的X坐标 pad_nan = np.nan + X pad_X = np.array([X, X, X]) pad_X = np.ravel(pad_X, 'F') #画出实体部分,先画收盘价在上的部分 up_cl = Close.copy() up_cl[Close <= Open] = np.nan up_op = Open.copy() up_op[Close <= Open] = np.nan down_cl = Close.copy() down_cl[Open <= Close] = np.nan down_op = Open.copy() down_op[Open <= Close] = np.nan even = Close.copy() even[Close != Open] = np.nan #画出收红的实体部分 pad_box_up = np.array([up_op, up_op, up_cl, up_cl, pad_nan]) pad_box_up = np.ravel(pad_box_up, 'F') pad_box_down = np.array([down_cl, down_cl, down_op, down_op, pad_nan]) pad_box_down = np.ravel(pad_box_down, 'F') pad_box_even = np.array([even, even, even, even, pad_nan]) pad_box_even = np.ravel(pad_box_even, 'F') #X的nan可以不用与y一一对应 X_left = X - 0.25 X_right = X + 0.25 box_X = np.array([X_left, X_right, X_right, X_left, pad_nan]) # print box_X box_X = np.ravel(box_X, 'F') # print box_X #Close_handle=plt.plot(pad_X,line_up,color='k') vertices_up = np.array([box_X, pad_box_up]).T vertices_down = np.array([box_X, pad_box_down]).T vertices_even = np.array([box_X, pad_box_even]).T handle_box_up = matplt.patches.Polygon(vertices_up, color='r', zorder=1) handle_box_down = matplt.patches.Polygon(vertices_down, color='g', zorder=1) handle_box_even = matplt.patches.Polygon(vertices_even, color='k', zorder=1) ax1.add_patch(handle_box_up) ax1.add_patch(handle_box_down) ax1.add_patch(handle_box_even) handle_line_up = matplt.lines.Line2D(pad_X, line_up, color='k', linestyle='solid', zorder=0) handle_line_down = matplt.lines.Line2D(pad_X, line_down, color='k', linestyle='solid', zorder=0) ax1.add_line(handle_line_up) ax1.add_line(handle_line_down) v = [0, length, Open.min() - 0.5, Open.max() + 0.5] plt.axis(v) T1 = T0[-len(T0):].astype(datetime.date) / 1000000000 # print T1 Ti = [] for i in range(int(len(T0) / x_jizhun)): a = i * x_jizhun d = datetime.date.fromtimestamp(T1[a]) # print d T2 = d.strftime('$%Y-%m-%d$') Ti.append(T2) #print tab d1 = datetime.date.fromtimestamp(T1[len(T0) - 1]) d2 = (d1 + datetime.timedelta(days=1)).strftime('$%Y-%m-%d$') Ti.append(d2) ax1.set_xticks(np.linspace(-2, len(Close) + 2, len(Ti))) ll = Low.min() * 0.97 hh = High.max() * 1.03 ax1.set_ylim(ll, hh) ax1.set_xticklabels(Ti) plt.grid(True) plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') ''' 以上代码拷贝自https://www.joinquant.com/post/1756 感谢alpha-smart-dog K线图绘制完毕 ''' x_date_list = quotes.index.values.tolist() # for x_date in x_date_list: # d = datetime.datetime.fromtimestamp(x_date/1000000000) # print d.strftime("%Y-%m-%d %H:%M:%S.%f") # print x_date_list k_data = quotes k_values = k_data.values # 缠论k线 chanK = quotes if chanK_flag else parse2ChanK(k_data, k_values) fenTypes, fenIdx = parse2ChanFen(chanK) #print "分型", fenTypes, fenIdx biIdx, frsBiType = parse2ChanBi(fenTypes, fenIdx, chanK) #biIdx = con2Cxianduan(stock_code, k_data, chanK, frsBiType, biIdx, end_date, cur_ji) #print chanK print("分笔", biIdx, frsBiType) print('number#', jqdatasdk.get_security_info(stock_code).display_name) # 3.得到分笔结果,计算坐标显示 x_fenbi_seq = [] y_fenbi_seq = [] for i in range(len(biIdx)): if biIdx[i]: fenType = -frsBiType if i % 2 == 0 else frsBiType # dt = chanK['enddate'][biIdx[i]] # 缠论k线 _dt = chanK.index[biIdx[i]] if chanK_flag else chanK['enddate'][ biIdx[i]] # print k_data['high'][dt], k_data['low'][dt] time_long = np.long( time.mktime((_dt + datetime.timedelta(hours=8)).timetuple()) * 1000000000) # print x_date_list.index(time_long) if time_long in x_date_list else 0 if fenType == 1: plt.text(x_date_list.index(time_long), k_data['high'][_dt], \ str(k_data['high'][_dt]), ha='left', fontsize=12) x_fenbi_seq.append(x_date_list.index(time_long)) y_fenbi_seq.append(k_data['high'][_dt]) if fenType == -1: plt.text(x_date_list.index(time_long), k_data['low'][_dt], \ str(k_data['low'][_dt]), va='bottom', fontsize=12) x_fenbi_seq.append(x_date_list.index(time_long)) y_fenbi_seq.append(k_data['low'][_dt]) # bottom_time = None # for k_line_dto in m_line_dto.member_list[::-1]: # if k_line_dto.low == m_line_dto.low: # # get_price返回的日期,默认时间是08:00:00 # bottom_time = k_line_dto.begin_time.strftime('%Y-%m-%d') +' 08:00:00' # break # x_fenbi_seq.append(x_date_list.index(long(time.mktime(datetime.strptime(bottom_time, "%Y-%m-%d %H:%M:%S").timetuple())*1000000000))) # y_fenbi_seq.append(m_line_dto.low) # 在原图基础上添加分笔蓝线 plt.plot(x_fenbi_seq, y_fenbi_seq) #线段画到笔上 xdIdxs, xfenTypes = parse2ChanXD(frsBiType, biIdx, chanK) print('线段:', xdIdxs, xfenTypes) x_xd_seq = [] y_xd_seq = [] for i in range(len(xdIdxs)): if xdIdxs[i]: fenType = xfenTypes[i] # dt = chanK['enddate'][biIdx[i]] # 缠论k线 _dt = chanK.index[xdIdxs[i]] if chanK_flag else chanK['enddate'][ xdIdxs[i]] # print k_data['high'][dt], k_data['low'][dt] time_long = np.long( time.mktime((_dt + datetime.timedelta(hours=8)).timetuple()) * 1000000000) # print x_date_list.index(time_long) if time_long in x_date_list else 0 if fenType == 1: x_xd_seq.append(x_date_list.index(time_long)) y_xd_seq.append(k_data['high'][_dt]) if fenType == -1: x_xd_seq.append(x_date_list.index(time_long)) y_xd_seq.append(k_data['low'][_dt]) # bottom_time = None # for k_line_dto in m_line_dto.member_list[::-1]: # if k_line_dto.low == m_line_dto.low: # # get_price返回的日期,默认时间是08:00:00 # bottom_time = k_line_dto.begin_time.strftime('%Y-%m-%d') +' 08:00:00' # break # x_fenbi_seq.append(x_date_list.index(long(time.mktime(datetime.strptime(bottom_time, "%Y-%m-%d %H:%M:%S").timetuple())*1000000000))) # y_fenbi_seq.append(m_line_dto.low) # 在原图基础上添加分笔蓝线 plt.plot(x_xd_seq, y_xd_seq) high_point = k_data['high'].max() low_point = k_data['low'].min() end_x = max(x_date_list) text_x = max(x_fenbi_seq) high_x = [0, 0] high_y = [0, 0] high_x[1] = end_x high_y[0] = high_point high_y[1] = high_y[0] plt.plot(high_x, high_y) plt.text(text_x, high_point, '100% : ' + str(high_point), ha='left', fontsize=16) low_x = [0, 0] low_y = [0, 0] low_x[1] = end_x low_y[0] = low_point low_y[1] = low_y[0] plt.plot(low_x, low_y) plt.text(text_x, low_point, '0% : ' + str(low_point), ha='left', fontsize=16) increase = high_point - low_point mid_x = [0, 0] mid_y = [0, 0] mid_x[1] = end_x mid_y[0] = low_point + increase / 2 mid_y[1] = mid_y[0] plt.plot(mid_x, mid_y) plt.text(text_x, mid_y[0], '50% : ' + str(mid_y[0]), ha='left', fontsize=16) mid_x_1 = [0, 0] mid_y_1 = [0, 0] mid_x_1[1] = end_x mid_y_1[0] = low_point + increase * 0.618 mid_y_1[1] = mid_y_1[0] plt.plot(mid_x_1, mid_y_1) plt.text(text_x, mid_y_1[0], '61.8% : ' + str(mid_y_1[0]), ha='left', fontsize=16) mid_x_2 = [0, 0] mid_y_2 = [0, 0] mid_x_2[1] = end_x mid_y_2[0] = low_point + increase * 0.382 mid_y_2[1] = mid_y_2[0] plt.plot(mid_x_2, mid_y_2) plt.text(text_x, mid_y_2[0], '61.8% : ' + str(mid_y_2[0]), ha='left', fontsize=16) plt.show()
def getstockname(self, code): return jq.get_security_info(code).display_name