1、過濾停牌
def set_feasible_stocks(stock_list,days,context): # 得到是否停牌信息的dataframe,停牌的1,未停牌得0 suspened_info_df = get_price(list(stock_list), start_date=context.current_dt, end_date=context.current_dt, frequency='daily', fields='paused' )['paused'].T # 過濾停牌股票 返回dataframe unsuspened_index = suspened_info_df.iloc[:,0]<1 # 得到當日未停牌股票的代碼list: unsuspened_stocks = suspened_info_df[unsuspened_index].index # 進一步,篩選出前days天未曾停牌的股票list: feasible_stocks = [] current_data = get_current_data() for stock in unsuspened_stocks: if sum(attribute_history(stock, days, unit = '1d',fields = ('paused'), skip_paused = False))[0] == 0: feasible_stocks.append(stock) return feasible_stocks
2、交易日遷移
def shift_trading_day(date,shift): # 獲取所有的交易日,返回一個包含所有交易日的 list,元素值為 datetime.date 類型. tradingday = get_all_trade_days() # 得到date之后shift天那一天在列表中的行標號 返回一個數 shiftday_index = list(tradingday).index(date)+shift # 根據行號返回該日日期 為datetime.date類型 return tradingday[shiftday_index]
3、選取多頭排列的股票
def sel_duotou_list(security,date): sel_list = [] for stock in security: try: ma5 = MA(stock, date, timeperiod=5)[stock] ma21 = MA(stock, date, timeperiod=21)[stock] ma30 = MA(stock, date, timeperiod=30)[stock] ma55 = MA(stock, date, timeperiod=55)[stock] ma89 = MA(stock, date, timeperiod=89)[stock] ma120 = MA(stock, date, timeperiod=120)[stock] if (ma5>ma21) & (ma21>ma30) & (ma30>ma55): sel_list.append(stock) except: continue return sel_list
4.畫k線圖
import matplotlib.pyplot as plt import mpl_finance from matplotlib.pylab import date2num import datetime quotes=attribute_history('000099.XSHE', 50, unit='1d', fields=['open', 'high', 'low', 'close'], skip_paused=True, df=True, fq='pre') data_list = [] for dates, row in quotes.iterrows(): #dates為Datafrema數據,強制轉換為str方可使用 date_time = datetime.datetime.strptime(str(dates), '%Y-%m-%d %H:%M:%S') #接收datetime.datetime數據 t = date2num(date_time) open, high, low, close = row[:4] datas = (t, open, high, low, close) data_list.append(datas) fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) # 設置x軸為日期 ax.xaxis_date() plt.xticks(rotation=45) plt.yticks() plt.title('000001.XSHE: 2016/01/01-2019/02/01') plt.xlabel("時間") plt.ylabel("股價(元)") mpl_finance.candlestick_ohlc(ax=ax, quotes=data_list, width=0.6, colorup='b', colordown='r') plt.grid(True) plt.show()