聚宽常用函数汇总

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()
原文地址:https://www.cnblogs.com/figo-studypath/p/10935666.html