代码主要来自于米框官方教程,由于官方教程有很多,且在开源代码上不一定运行成功,因此将试验成功的代码放于此,便于日后查验。
rqalpha取自官方版本3.4.0到3.4.1之间。
获取合约的详细信息
交易列表
上一交易日
下一交易日
获取交易日列表
当日快照
(order_book_id, bar_count, frequency, fields=None, skip_suspended=True, include_now=False, adjust_type=‘pre’)
得到的是一个ndarray序列,这里是前30天的数据集
handle_bar()函数中通过bar_dict[stock].close获取到当日收盘价,最终调用到get_bar()中数据
bar_dict[stock].close调用的BarMap中的__getitem__()函数,然后通过
self._data_proxy.get_bar(order_book_id, self._dt, self._frequency)
获取股票的相关信息,data_proxy.get_bar()调用_data_source.get_bar()函数,这个_data_source是数据源,如果重写了数据源,那么get_bar()也需要重写。我重写成minute_data_source,因此这儿就接管过来了
context.portfolio.positions这个指账户相关信息
# 此例子采用Talib提供的STOCH(Stochastic Oscillator Slow),更直接的理解他就是我们常用的KDJ指标中的KD指标。
# 是由两条线一条是快速确认线,另外一条是慢速主干线组成。
# K线是快速确认线——数值在90以上为超买,数值在10以下为超卖;
# D线是慢速主干线——数值在90以上为超买,数值在10以下为超卖;
import talib
from rqalpha.api import *
def init(context):
# 定义一个全局变量, 保存要操作的证券
context.stocks = ['600048.XSHG', '000002.XSHE', '000024.XSHE', '000031.XSHE', '000040.XSHE']
# 设置我们要操作的股票池
update_universe(context.stocks)
# 初始化此策略
def handle_bar(context, bar_dict):
# 取得当前的现金
cash = context.portfolio.cash
# 循环股票列表
for stock in context.stocks:
# 获取股票的数据
hhigh = history_bars(stock, 30, '1d', 'high')
hlow = history_bars(stock, 30, '1d', 'low')
hclose = history_bars(stock, 30, '1d', 'close')
# 创建STOCH买卖信号,包括最高价,最低价,收盘价和快速线(一般取为9),慢速线
# 注意:STOCH函数使用的price必须是narray
slowk, slowd = talib.STOCH(hhigh,
hlow,
hclose,
fastk_period=9,
slowk_period=3,
slowk_matype=0,
slowd_period=3,
slowd_matype=0)
# 获得最近的kd值
slowk = slowk[-1]
slowd = slowd[-1]
# 获取当前股票的数据
current_position = context.portfolio.positions[stock].quantity
# 获取当前股票价格
current_price = bar_dict[stock].close
# 当slowk > 90 or slowd > 90,且拥有的股票数量>=0时,卖出所有股票
if slowk > 90 or slowd > 90 and current_position >= 0:
order_target_percent(stock, 0)
# 当slowk < 10 or slowd < 10, 且拥有的股票数量<=0时,则全仓买入
elif slowk < 10 or slowd < 10 and current_position <= 0:
number_of_shares = int(cash / current_price)
# logger.info(cash)
# logger.info(current_price)
# 购买量大于0时,下单
if number_of_shares > 0:
# 买入股票
order_shares(stock, number_of_shares)
股票日线原始数据:
股票日线转换后的数据:
股票分钟原始数据:
股票分钟转换后数据
关于分钟数据的datetime列
将datetime替换成原来的date, 然后将datetime*=1000000, 再加上time列的数据