问答交流

没法买回上个交易日卖空的股票?中途打印出来是没问题的。

由nusfighter创建,最终由nusfighter 被浏览 32 用户

每次交易先清空持仓,买入排名前三股票,卖空排名最后三只股票。
运行的时候发现没法买回上次卖空的股票,请帮忙看一下为什么呢?中途打印出来是没问题的。

stock_hold_now = {e.symbol: p.amount
             for e, p in context.perf_tracker.position_tracker.positions.items()}
print(today, context.portfolio.cash, stock_hold_now)
 
#先把已有的持仓清掉
# 如果该股票停牌,则没法成交。因此需要用can_trade方法检查下该股票的状态
# 如果返回真值,则可以正常下单,否则会出错
# 因为stock是字符串格式,我们用symbol方法将其转化成平台可以接受的形式:Equity格式
for e,p in stock_hold_now.items():
    if data.can_trade(context.symbol(e)):
        context.order(context.symbol(e), -p)
        print(e,-p)  #打印清空持仓的情况

print(today, context.portfolio.cash)        
cash_for_buy = 5000000
cash_for_sell = 5000000
# 获取当日符合买入/卖出条件的股票列表
stock_to_buy = list(ranker_cond1.instrument[:3])
stock_to_sell = list(ranker_cond1.instrument[-3:])

# 卖出,融券卖出,amout取负值
for instrument in stock_to_sell:
    cash = cash_for_buy / len(stock_to_sell)
    if data.can_trade(context.symbol(instrument)):
        current_price = data.current(context.symbol(instrument), 'price')
        amount = math.floor(cash / current_price / 100) * 100
        context.order(context.symbol(instrument), -amount)
        print(instrument, -amount) #打印融券卖出
# 买入
#stock_to_buy = [i for i in buy_stock]
for instrument in stock_to_buy:
    # 利用当日可用现金使用等资金比例下单买入
    cash = cash_for_buy / len(stock_to_buy)
    if data.can_trade(context.symbol(instrument)):
        current_price = data.current(context.symbol(instrument), 'price')
        amount = math.floor(cash / current_price / 100) * 100
        context.order(context.symbol(instrument), amount)
        print(instrument, amount) #打印买入股票

运行结果打印如下

2020-01-02 10000000.0 {} 2020-01-02 10000000.0 688357.SHA -34200 688358.SHA -32700 688399.SHA -28700 601857.SHA 283900 601288.SHA 446800 601988.SHA 448000 2020-01-17 9988315.96112215 {'688357.SHA': -34200, '688358.SHA': -32700, '688399.SHA': -28700, '601857.SHA': 283900, '601288.SHA': 446800, '601988.SHA': 448000} 688357.SHA 34200 688358.SHA 32700 688399.SHA 28700 601857.SHA -283900 601288.SHA -446800 601988.SHA -448000 2020-01-17 9988315.96112215 688258.SHA -16900 688268.SHA -22200 688278.SHA -47200 601988.SHA 456600 600236.SHA 350100 601288.SHA 460400 2020-02-11 15975298.722390814 {'688357.SHA': -34200, '688358.SHA': -32700, '688399.SHA': -28700, '601288.SHA': 460400, '601988.SHA': 456600, '688258.SHA': -16900, '688268.SHA': -22200, '688278.SHA': -47200, '600236.SHA': 83600} 688357.SHA 34200 688358.SHA 32700 688399.SHA 28700 601288.SHA -460400 601988.SHA -456600 688258.SHA 16900 688268.SHA 22200 688278.SHA 47200 600236.SHA -83600 2020-02-11 15975298.722390814 688278.SHA -40500 688298.SHA -16900 688398.SHA -19600 601988.SHA 472100 601998.SHA 298600 600236.SHA 359100

标签

投资策略股票交易
评论
  • 融券的功能,还不完善,存在一些问题,可以试试order*_target_percent呢?*
  • 第一天,买入股票和融券卖出股票都是正常的。第二天,分为两个操作,先平仓。卖出昨天买入的股票(成功),买入昨天卖出的股票(不成功)。这里买入和卖出是一条代码。context.order(context.symbol(e), -p)。按计划买入股票和融资卖出股票(都成功)。就很奇怪为什么一条代码里面,有的交易成交,有的交易不成交呢?
  • 我明早测试一下。
  • 请问测试了吗?