def initialize(context):
run_daily(period,time='every_bar')
g.security1 = '000001.XSHE'
g.security2 = '000002.XSHE'
def period(context):
order(g.security1, 100)
order(g.security2, 100)
def initialize(context):
run_daily(period,time='every_bar')
# 把两个股票代码作为list存入g.security中
g.security = ['000001.XSHE','000002.XSHE']
def period(context):
# 每个股票买100股
for stk in g.security:
order(stk,100)
def initialize(context):
run_daily(period,time='every_bar')
# 把两个股票代码作为list存入g.security中
g.security = ['000001.XSHE','000002.XSHE']
def period(context):
for stk in g.security:
order(stk,100)
# 获得股票持仓成本
cost=context.portfolio.positions[stk].avg_cost
# 获得股票现价
price=context.portfolio.positions[stk].price
# 计算收益率
ret=price/cost-1
# 如果收益率小于-0.01,即亏损达到1%则卖出股票,幅度可以自己调,一般10%
if ret<-0.01:
order_target(stk,0)
print('触发止损')
-获取指数成分股需要用到的API为get_index_stocks
获取所有沪深300的股票
#获取所有沪深300股票
stocks = get_index_stocks('000300.XSHG')
log.info(stocks)
# 获取20180301时,上证50指数(000016.XSHG)成分股
t=get_index_stocks("000016.XSHG","2018-03-01")
print(t[0])
print(t)
# 打印日志如下。股票代码在list中被打印出来前面会带有的u代表是对字符串进行unicode编码(略复杂,不懂没关系),只是显示效果,单独打印t[0]时就没有u。
# 600000.XSHG
# [u'600000.XSHG', u'600016.XSHG', u'600019.XSHG', u'600028.XSHG', u'600029.XSHG', u'600030.XSHG', u'600036.XSHG', u'600048.XSHG', u'600050.XSHG', u'600104.XSHG', u'600111.XSHG', u'600309.XSHG', u'600340.XSHG', u'600518.XSHG', u'600519.XSHG', u'600547.XSHG', u'600606.XSHG', u'600837.XSHG', u'600887.XSHG', u'600919.XSHG', u'600958.XSHG', u'600999.XSHG', u'601006.XSHG', u'601088.XSHG', u'601166.XSHG', u'601169.XSHG', u'601186.XSHG', u'601211.XSHG', u'601229.XSHG', u'601288.XSHG', u'601318.XSHG', u'601328.XSHG', u'601336.XSHG', u'601390.XSHG', u'601398.XSHG', u'601601.XSHG', u'601628.XSHG', u'601668.XSHG', u'601669.XSHG', u'601688.XSHG', u'601766.XSHG', u'601800.XSHG', u'601818.XSHG', u'601857.XSHG', u'601878.XSHG', u'601881.XSHG', u'601985.XSHG', u'601988.XSHG', u'601989.XSHG', u'603993.XSHG']
# 例子 df=True,返回dataframe类型
w=history(count=3, field='money', security_list=['000001.XSHE','000002.XSHE'])
print(w)
# 结果如下:
# 000001.XSHE 000002.XSHE
# 2016-08-29 5.322954e+08 1.796321e+09
# 2016-08-30 5.618541e+08 2.072873e+09
# 2016-08-31 4.638758e+08 5.748581e+09
# 例子 df=False,返回dict类型
w=history(count=3, field='money', security_list=['000001.XSHE','000002.XSHE'],df=False)
print(w)
# 结果如下:
# {'000001.XSHE': array([ 5.32295362e+08, 5.61854066e+08, 4.63875763e+08]), '000002.XSHE': array([ 1.79632055e+09, 2.07287325e+09, 5.74858107e+09])}