时间止损

这篇文章我来介绍一下什么是时间止损, 和具体的实现方法。

止损, 一般来说有两种方法, 一种是空间止损, 一种是时间止损。
空间止损: 股价在买入后股价跌到某预先设定的价格,就清仓止损.
时间止损: 股价在买入后一直在一个区间内徘徊, X天以后 若涨幅没超过 Y% 就清仓。

为方便用户使用, 已集成模板, 只需要 Ctrl C 和Ctrl+ V 就能使用。
使用方法已在开头注释内写出。

'''
止损描述: 持股大于 X 天,且区间内回报少于 Y % 止损 

使用方法: 
0:  设置持股天数 X,  在 init 中 : context.period= X ; 设置区间内回报 Y context.total_return = Y (单位为比例, 非百分比。)
1: 复制  def  record 和 def stoploss 至script 
2: 在下单前 插入 ‘record(context,bar_dict,stock)’ (必须使用for loop 下单)
3: 设置 scheduler.run_daily(stopless)

'''


# 可以自己import我们平台支持的第三方python模块,比如pandas、numpy等。
import pandas as pd 
import numpy as np 
import time 
import datetime 
import math
import itertools

# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
def init(context):
    context.to_buy = ('300033.XSHE','000025.XSHE')
    context.period=10 # 持股天数X 
    context.total_return=0.05 # 持股天数内的回报率 
    # 实时打印日志
    #scheduler.run_daily(stoploss)
    logger.info("Interested at stock: " + str(context.to_buy))
    context.time=pd.DataFrame()
    scheduler.run_monthly(rebalance,1)
    scheduler.run_daily(stoploss)



# 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新
def handle_bar(context, bar_dict):
    # 开始编写你的主要的算法逻辑
    # bar_dict[order_book_id] 可以拿到某个证券的bar信息
    # context.portfolio 可以拿到现在的投资组合状态信息

    # 使用order_shares(id_or_ins, amount)方法进行落单

    # TODO: 开始编写你的算法吧!

    pass 



def stoploss( context,bar_dict):
    # 根据时间 清仓
    print(context.time)
    for stock in  context.portfolio.positions: 
        if stock in context.time.columns:
            buytime=context.time[stock][0] # 获取买入时间
            currenttime=context.now.replace(tzinfo=None) # 获取当前时间
            print ('buytime='+str(buytime))
            print('currenttime='+str(currenttime))

            total_return=context.portfolio.positions[stock].market_value/context.portfolio.positions[stock].bought_value # 计算回报
            escape=(currenttime-buytime).days # 计算持有天数
            if escape>context.period and total_return<1+context.total_return:
                print(str(stock)+ '大于' + str (context.period)+'天 且回报过小, 卖出')
                order_target_percent(stock, 0)
                del context.time[stock]

            elif total_return>1+context.total_return: 
                print(str(stock)+'回报为: ' +str(total_return)+'大于预设值'+str(1+context.total_return))
            else:
                print(str(stock)+ '持仓未到' +str(context.period)+'天,继续持有')

def record(context,bar_dict,stock):
    if stock not in context.time.columns:
        temp=pd.DataFrame({str(stock):[context.now.replace(tzinfo=None)]})
        logger.info (temp)
        context.time = pd.concat([context.time, temp], axis=1, join='inner')


def rebalance(context,bar_dict):
    #time=pd.DataFrame() #在买入的同时 创建一个Dataframe 储存买入的时间。 
    if len(context.to_buy)!=0:
        for stock in context.to_buy:
            record(context,bar_dict,stock)
            order_target_percent(stock,1/len(context.to_buy))
            #temp=pd.DataFrame({str(stock):[context.now.replace(tzinfo=None)]})
            #logger.info (temp)
            #time = pd.concat([time, temp], axis=1, join='inner')
        #context.time=time

    else: 
        order_target_percent(stock,0)

results matching ""

    No results matching ""