def stock_zh_index_daily_tx(self, stockcode): if stockcode[0:1] == '6': stockcode = 'sh' + stockcode else: stockcode = 'sz' + stockcode stock_zh_index_daily_df = ak.stock_zh_index_daily_tx(symbol=stockcode) return stock_zh_index_daily_df
def index_price_daily(code: str, source: str = None) -> dict: if source == 'tx': df = ak.stock_zh_index_daily_tx(symbol=code) elif source == 'em': df = ak.stock_zh_index_daily_em(symbol=code) else: df = ak.stock_zh_index_daily(symbol=code) df['date'] = pd.to_datetime(df['date']) df = df.rename({'date': '_id'}, axis=1) print(df) return json.loads(df.T.to_json()) # use default date_format='epoch' instead of 'iso'
def index_price_daily(code: str, source: str = None) -> pd.DataFrame: if source == 'tx': df = ak.stock_zh_index_daily_tx(symbol=code) elif source == 'em': df = ak.stock_zh_index_daily_em(symbol=code) else: df = ak.stock_zh_index_daily(symbol=code) df['date'] = pd.to_datetime(df['date']) df = df.rename({'date': '_id'}, axis=1) print(df) return df
def indexStocksCN(idx): print(idx) index_stock_cons_df = ak.index_stock_cons(index=idx[2:]) # print(index_stock_cons_df) index_stock_cons_df.drop_duplicates(subset='品种代码', keep='first', inplace=True) index_stock_cons_df.set_index('品种代码', inplace=True) # 今日全场股票概况(价格、市值等) df = ak.stock_zh_a_spot() df.set_index('symbol', inplace=True) # 按总市值排顺序,只保留指数成份股 df = df.loc[df.index.isin( [dealSymbol(s) for s in index_stock_cons_df.index])].copy() df.sort_values(by='mktcap', ascending=True, inplace=True) df = df.iloc[:int(len(df) / 2) - 1] # 计算因子值 days = 30 sortedDf = pd.DataFrame() tqdmRange = tqdm(range(len(df))) tqdmRange = tqdm([-3, -2, -1]) for i in tqdmRange: symbol = dealSymbol(df.index[i]) tqdmRange.set_description("cauculating factor value for %s" % symbol) factorVaule_1 = [] factorVaule_2 = [] stockK = ak.stock_zh_index_daily_tx(symbol=symbol) stockK['symbol'] = symbol for j in range(0, len(stockK)): if j < days: factorVaule_1.append(None) factorVaule_2.append(None) continue factorVaule_1.append(factor_1(stockK.iloc[j - days:j])) factorVaule_2.append(factor_1(stockK.iloc[j - days:j])) stockK['factor_1'] = factorVaule_1 stockK['factor_2'] = factorVaule_2 stockK.to_csv('Quotation/' + symbol + '.csv') stockK = stockK[['symbol', 'factor_1', 'factor_2']].copy() stockK.reset_index(inplace=True) sortedDf = sortedDf.append(stockK) sortedDf.sort_values(by=['date', 'factor_1'], ascending=True, inplace=True) sortedDf.dropna(subset=['factor_1'], inplace=True) sortedDf.to_csv(idx + 'factor.csv') sortedDf['date'] = pd.to_datetime(sortedDf['date']).date return sortedDf
def get_kline(code, start_date: datetime.date): """ 返回json数据,最新的日期在前面 """ result = [] df = ak.stock_zh_a_daily(symbol=get_type(code) + code, adjust="hfq") # 腾讯,主要是使用amount字段 dftx = ak.stock_zh_index_daily_tx(symbol=get_type(code) + code) if df is None or df.empty: return result if dftx is None or dftx.empty: return result for row in df.itertuples(): w = {} w['datetime'] = getattr(row, 'Index') if w['datetime'] < start_date: continue w['open'] = getattr(row, 'open') w['high'] = getattr(row, 'high') w['low'] = getattr(row, 'low') w['close'] = getattr(row, 'close') w['volume'] = getattr(row, 'volume') result.append(w) return result
def get_60d_kline_data(s_code): df = ak.stock_zh_index_daily_tx(symbol=f"sz{s_code}") df.index = pd.to_datetime(df.index) df_60d = df[-60:] return df_60d
def research(): iK = dict() idx = ['sh000300', 'sz399101', 'sz399102'] for iCode in idx: iK[iCode] = ak.stock_zh_index_daily_tx(symbol=iCode) num = min(len(iK['sh000300']), len(iK['sz399101']), len(iK['sz399102'])) for iCode in iK.keys(): iK[iCode] = iK[iCode].iloc[-num:] iK[iCode][iCode] = [ iK[iCode]['close'][j] / iK[iCode]['close'][0] for j in range(len(iK[iCode]['close'])) ] # 绘制走势 fig = iK[idx[0]][idx[0]].plot(figsize=(20, 5), color='purple') fig.plot(iK[idx[1]][idx[1]], color='green', alpha=1) fig.plot(iK[idx[2]][idx[2]], color='brown', alpha=1) days = 20 i = -days signal = 0 nSeri = [] while i < len(iK[idx[0]]) - days - 1: i += days if i < days: nSeri.extend([1.0 for r in range(days + 1)]) continue # 收益曲线 compare = [ iK[idx[0]][idx[0]][i] / iK[idx[0]][idx[0]][i - days], iK[idx[1]][idx[1]][i] / iK[idx[1]][idx[1]][i - days], iK[idx[2]][idx[2]][i] / iK[idx[2]][idx[2]][i - days] ] m = compare.index(max(compare)) nSeri.extend([ nSeri[-1] * iK[idx[m]][idx[m]][r] / iK[idx[m]][idx[m]][i - days] for r in range(i - days, i) ]) fig.plot(pd.Series(data=nSeri, index=iK[idx[m]].index), color='black', alpha=1) fig.legend() timespans = {'x1': [], 'x2': [], 'o1': [], 'o2': []} colors = {'x1': 'green', 'x2': 'blue', 'o1': 'red', 'o2': 'orange'} cs = iK['sh000300']['close'] i = -1 days = 44 x2 = timespans['x2'] while i < len(cs) - 1 - days: i += 1 c = cs[i:i + days] if c[-1] < c[0] and max(c) == c[0]: i += days - 1 x2.append(c.index) days = 32 spans = [] testnum = 4 for n in tqdm(range(testnum)): nSpan = [] i = -1 while i < len(cs) - 1 - days: i += 1 c = cs[i:i + days] if int(days / testnum * n) <= c.values.argmax() < int( days / testnum * (n + 1)) and c[-1] < c[0]: nSpan.append(c.index) i += days - 1 spans.append(nSpan) minCount = 999 minSpaniK = 0 for si in range(testnum): match = 0 for sp in spans[si]: for ts in timespans['x2']: if ts[0] in sp: match += 1 if len(spans[si]) < minCount and len(spans[si]) != 0 and match > 0: minCount = len(spans[si]) minSpaniK = si timespans['x1'] = spans[minSpaniK] print(len(spans[minSpaniK]), minSpaniK) for k, v in timespans.items(): if len(v) == 0: continue for span in v: if len(span) == 0: continue fig.axvspan(span[0], span[-1], facecolor=colors[k], edgecolor='none', alpha=.2) plt.show()
def stock_zh_index_daily_tx(self): stock_zh_index_daily_tx_df = ak.stock_zh_index_daily_tx( symbol="sh000919") return stock_zh_index_daily_tx_df