示例#1
0
def IntradayFryWin(symbolinfo, rawdata, paraSet):
    setname = paraSet['Setname']
    MACD_S = paraSet['MACD_S']
    MACD_L = paraSet['MACD_L']
    MACD_M = paraSet['MACD_M']
    MA_N = paraSet['MA_N']
    # print setname
    rawdata['Unnamed: 0'] = range(rawdata.shape[0])
    #beginindex = rawdata.ix[0, 'Unnamed: 0']
    # 计算MACD
    macd = MA.calMACD(rawdata['close'], MACD_S, MACD_L, MACD_M)
    rawdata['DIF'] = macd[0]
    rawdata['DEA'] = macd[1]
    rawdata['MA'] = MA.calEMA(rawdata['close'], MA_N)

    # 计算MACD的金叉和死叉
    rawdata['MACD_True'], rawdata['MACD_Cross'] = MA.dfCross(rawdata, 'DIF', 'DEA')

    # ================================ 找出买卖点================================================
    # 1.先找出SAR金叉的买卖点
    # 2.找到结合判决条件的买点
    # 3.从MA买点中滤出真实买卖点
    # 取出金叉点
    goldcrosslist = pd.DataFrame({'goldcrosstime': rawdata.loc[rawdata['MACD_Cross'] == 1, 'strtime']})
    goldcrosslist['goldcrossutc'] = rawdata.loc[rawdata['MACD_Cross'] == 1, 'utc_time']
    goldcrosslist['goldcrossindex'] = rawdata.loc[rawdata['MACD_Cross'] == 1, 'Unnamed: 0']
    goldcrosslist['goldcrossprice'] = rawdata.loc[rawdata['MACD_Cross'] == 1, 'close']

    # 取出死叉点
    deathcrosslist = pd.DataFrame({'deathcrosstime': rawdata.loc[rawdata['MACD_Cross'] == -1, 'strtime']})
    deathcrosslist['deathcrossutc'] = rawdata.loc[rawdata['MACD_Cross'] == -1, 'utc_time']
    deathcrosslist['deathcrossindex'] = rawdata.loc[rawdata['MACD_Cross'] == -1, 'Unnamed: 0']
    deathcrosslist['deathcrossprice'] = rawdata.loc[rawdata['MACD_Cross'] == -1, 'close']
    goldcrosslist = goldcrosslist.reset_index(drop=True)
    deathcrosslist = deathcrosslist.reset_index(drop=True)

    # 生成多仓序列(金叉在前,死叉在后)
    if goldcrosslist.ix[0, 'goldcrossindex'] < deathcrosslist.ix[0, 'deathcrossindex']:
        longcrosslist = pd.concat([goldcrosslist, deathcrosslist], axis=1)
    else:  # 如果第一个死叉的序号在金叉前,则要将死叉往上移1格
        longcrosslist = pd.concat([goldcrosslist, deathcrosslist.shift(-1).fillna(0)], axis=1)
    longcrosslist = longcrosslist.set_index(pd.Index(longcrosslist['goldcrossindex']), drop=True)

    # 生成空仓序列(死叉在前,金叉在后)
    if deathcrosslist.ix[0, 'deathcrossindex'] < goldcrosslist.ix[0, 'goldcrossindex']:
        shortcrosslist = pd.concat([deathcrosslist, goldcrosslist], axis=1)
    else:  # 如果第一个金叉的序号在死叉前,则要将金叉往上移1格
        shortcrosslist = pd.concat([deathcrosslist, goldcrosslist.shift(-1).fillna(0)], axis=1)
    shortcrosslist = shortcrosslist.set_index(pd.Index(shortcrosslist['deathcrossindex']), drop=True)

    # 取出开多序号和开空序号
    openlongindex = rawdata.loc[
        (rawdata['MACD_Cross'] == 1) & (rawdata['close'] > rawdata['MA']) & (rawdata['ATR'] > 6)].index
    openshortindex = rawdata.loc[
        (rawdata['MACD_Cross'] == -1) & (rawdata['close'] < rawdata['MA']) & (rawdata['ATR'] > 6)].index
    # 从多仓序列中取出开多序号的内容,即为开多操作
    longopr = longcrosslist.loc[openlongindex]
    longopr['tradetype'] = 1
    longopr.rename(columns={'goldcrosstime': 'opentime',
                            'goldcrossutc': 'openutc',
                            'goldcrossindex': 'openindex',
                            'goldcrossprice': 'openprice',
                            'deathcrosstime': 'closetime',
                            'deathcrossutc': 'closeutc',
                            'deathcrossindex': 'closeindex',
                            'deathcrossprice': 'closeprice'}, inplace=True)

    # 从空仓序列中取出开空序号的内容,即为开空操作
    shortopr = shortcrosslist.loc[openshortindex]
    shortopr['tradetype'] = -1
    shortopr.rename(columns={'deathcrosstime': 'opentime',
                             'deathcrossutc': 'openutc',
                             'deathcrossindex': 'openindex',
                             'deathcrossprice': 'openprice',
                             'goldcrosstime': 'closetime',
                             'goldcrossutc': 'closeutc',
                             'goldcrossindex': 'closeindex',
                             'goldcrossprice': 'closeprice'}, inplace=True)

    # 结果分析
    result = pd.concat([longopr, shortopr])
    result = result.sort_index()
    result = result.reset_index(drop=True)
    # result.drop(result.shape[0] - 1, inplace=True)
    result = result.dropna()
    # 去掉跨合约的操作
    # 使用单合约,不用再去掉跨合约
    # result = removeContractSwap(result, contractswaplist)

    slip = symbolinfo.getSlip()
    result['ret'] = ((result['closeprice'] - result['openprice']) * result['tradetype']) - slip
    result['ret_r'] = result['ret'] / result['openprice']
    results = {}

    '''
    # 使用单合约,策略核心内不再计算结果
    if calcResult:
        result['commission_fee'], result['per earn'], result['own cash'], result['hands'] = RS.calcResult(result,
                                                                                                          symbolinfo,
                                                                                                          initialCash,
                                                                                                          positionRatio)

        endcash = result['own cash'].iloc[-1]
        Annual = RS.annual_return(result)
        Sharpe = RS.sharpe_ratio(result)
        DrawBack = RS.max_drawback(result)[0]
        SR = RS.success_rate(result)
        max_single_loss_rate = abs(result['ret_r'].min())

        results = {
            'Setname':setname,
            'opentimes': result.shape[0],
            'end_cash': endcash,
            'SR': SR,
            'Annual': Annual,
            'Sharpe': Sharpe,
            'DrawBack': DrawBack,
            'max_single_loss_rate': max_single_loss_rate
        }
    closeopr = result.loc[:, 'closetime':'tradetype']
    return result, rawdata, closeopr, results
    '''
    return result
示例#2
0
def HopeMACDWin(symbolInfo,setname,K_MIN_MACD,startdate,enddate,macdParaSet,contractswaplist,calcResult=True):
    print setname
    rawdata_macd = DC.getBarData(symbolInfo.symbol, K_MIN_MACD, startdate + " 00:00:00", enddate + " 23:59:59")
    MACD_S=macdParaSet['MACD_S']
    MACD_L = macdParaSet['MACD_L']
    MACD_M = macdParaSet['MACD_M']

    macd = MA.calMACD(rawdata_macd['close'], MACD_S, MACD_L, MACD_M)
    rawdata_macd['DIF'] = macd[0]
    rawdata_macd['DEA'] = macd[1]
    rawdata_macd['DIF_F']=-1
    rawdata_macd['DEA_F']=-1
    rawdata_macd.loc[rawdata_macd['DIF']>=0,'DIF_F'] = 1
    rawdata_macd.loc[(rawdata_macd['DIF']>=rawdata_macd['DEA']) , 'DEA_F'] = 1
    rawdata_macd['OpenF']=rawdata_macd['DIF_F']+rawdata_macd['DEA_F']
    rawdata_macd['OpenF1']=rawdata_macd['OpenF'].shift(1).fillna(0)
    # ================================ 找出买卖点================================================
    # 1.OpenF==2 & (OpenF1 ==-2/0):开多
    # 2.OpenF==-2/0& (OpenfF1==2):平多
    # 3.OpenF==-2 & (OpenF1 == 2/0):开空
    # 4.OpenF==2/0 & OpenF1==-2 :平空
    #开多
    openlonglist = pd.DataFrame({'opentime': rawdata_macd.loc[(rawdata_macd['OpenF'] == 2) & (rawdata_macd['OpenF1'] < 2 ), 'strtime']})
    openlonglist['openutc'] = rawdata_macd.loc[(rawdata_macd['OpenF'] == 2) & (rawdata_macd['OpenF1'] < 2 ), 'utc_time']
    openlonglist['openindex'] = rawdata_macd.loc[(rawdata_macd['OpenF'] == 2) & (rawdata_macd['OpenF1'] < 2 ), 'Unnamed: 0']
    openlonglist['openprice'] = rawdata_macd.loc[(rawdata_macd['OpenF'] == 2) & (rawdata_macd['OpenF1'] < 2 ), 'close']
    # 平多
    closelonglist = pd.DataFrame(
        {'closetime': rawdata_macd.loc[(rawdata_macd['OpenF1'] == 2) & (rawdata_macd['OpenF'] < 2), 'strtime']})
    closelonglist['closeutc'] = rawdata_macd.loc[
        (rawdata_macd['OpenF1'] == 2) & (rawdata_macd['OpenF'] < 2), 'utc_time']
    closelonglist['closeindex'] = rawdata_macd.loc[
        (rawdata_macd['OpenF1'] == 2) & (rawdata_macd['OpenF'] < 2), 'Unnamed: 0']
    closelonglist['closeprice'] = rawdata_macd.loc[
        (rawdata_macd['OpenF1'] == 2) & (rawdata_macd['OpenF'] < 2), 'close']

    #开空
    openshortlist = pd.DataFrame({'opentime': rawdata_macd.loc[(rawdata_macd['OpenF'] == -2) & (rawdata_macd['OpenF1'] > -2 ), 'strtime']})
    openshortlist['openutc'] = rawdata_macd.loc[(rawdata_macd['OpenF'] == -2) & (rawdata_macd['OpenF1'] > -2 ), 'utc_time']
    openshortlist['openindex'] = rawdata_macd.loc[(rawdata_macd['OpenF'] == -2) & (rawdata_macd['OpenF1'] > -2 ), 'Unnamed: 0']
    openshortlist['openprice'] = rawdata_macd.loc[(rawdata_macd['OpenF'] == -2) & (rawdata_macd['OpenF1'] > -2 ), 'close']
    # 平空
    closeshortlist = pd.DataFrame(
        {'closetime': rawdata_macd.loc[(rawdata_macd['OpenF1'] == -2) & (rawdata_macd['OpenF'] > -2), 'strtime']})
    closeshortlist['closeutc'] = rawdata_macd.loc[
        (rawdata_macd['OpenF1'] == -2) & (rawdata_macd['OpenF'] > -2), 'utc_time']
    closeshortlist['closeindex'] = rawdata_macd.loc[
        (rawdata_macd['OpenF1'] == -2) & (rawdata_macd['OpenF'] > -2), 'Unnamed: 0']
    closeshortlist['closeprice'] = rawdata_macd.loc[
        (rawdata_macd['OpenF1'] == -2) & (rawdata_macd['OpenF'] > -2), 'close']

    openlonglist.reset_index(drop=True,inplace=True)
    closelonglist.reset_index(drop=True,inplace=True)
    openshortlist.reset_index(drop=True,inplace=True)
    closeshortlist.reset_index(drop=True,inplace=True)
    # 生成多仓序列(金叉在前,死叉在后)
    if openlonglist.ix[0, 'openindex'] < closelonglist.ix[0, 'closeindex']:
        longlist = pd.concat([openlonglist, closelonglist], axis=1)
    else:  # 如果第一个死叉的序号在金叉前,则要将死叉往上移1格
        longlist = pd.concat([openlonglist, closelonglist.shift(-1).fillna(0)], axis=1)
    #longlist.set_index('openindex', inplace=True)
    longlist['tradetype']=1

    # 生成空仓序列(死叉在前,金叉在后)
    if openshortlist.ix[0, 'openindex'] < closeshortlist.ix[0, 'closeindex']:
        shortlist = pd.concat([openshortlist, closeshortlist], axis=1)
    else:  # 如果第一个金叉的序号在死叉前,则要将金叉往上移1格
        shortlist = pd.concat([openshortlist, closeshortlist.shift(-1).fillna(0)], axis=1)
    #shortlist.set_index('openindex', drop=True)
    shortlist['tradetype']=-1

    # 结果分析
    result = pd.concat([longlist, shortlist])
    result = result.set_index(pd.Index(result['openindex']), drop=True)
    result = result.sort_index()
    result = result.reset_index(drop=True)
    result.drop(result.shape[0] - 1, inplace=True)
    # 去掉跨合约的操作
    result = removeContractSwap(result, contractswaplist)
    initial_cash = 20000
    margin_rate = 0.2
    slip = symbolInfo.getSlip()
    multiplier = symbolInfo.getMultiplier()
    poundgeType, poundgeFee, poundgeRate = symbolInfo.getPoundage()

    result['ret'] = ((result['closeprice'] - result['openprice']) * result['tradetype']) - slip
    result['ret_r'] = result['ret'] / result['openprice']
    results={}
    if calcResult:
        firsttradecash = initial_cash / margin_rate
        result['commission_fee'] = 0
        if poundgeType == symbolInfo.POUNDGE_TYPE_RATE:
            result.ix[0, 'commission_fee'] = firsttradecash * poundgeRate * 2
        else:
            result.ix[0, 'commission_fee'] = firsttradecash / (multiplier * result.ix[0, 'openprice']) * poundgeFee * 2
        result['per earn'] = 0  # 单笔盈亏
        result['own cash'] = 0  # 自有资金线
        result['trade money'] = 0  # 杠杆后的可交易资金线

        result.ix[0, 'per earn'] = firsttradecash * result.ix[0, 'ret_r']
        result.ix[0, 'own cash'] = initial_cash + result.ix[0, 'per earn'] - result.ix[0, 'commission_fee']
        result.ix[0, 'trade money'] = result.ix[0, 'own cash'] / margin_rate
        oprtimes = result.shape[0]
        for i in np.arange(1, oprtimes):
            # 根据手续费类型计算手续费
            if poundgeType == symbolInfo.POUNDGE_TYPE_RATE:
                commission = result.ix[i - 1, 'trade money'] * poundgeRate * 2
            else:
                commission = result.ix[i - 1, 'trade money'] / (multiplier * result.ix[i, 'openprice']) * poundgeFee * 2
            perearn = result.ix[i - 1, 'trade money'] * result.ix[i, 'ret_r']
            owncash = result.ix[i - 1, 'own cash'] + perearn - commission
            result.ix[i, 'own cash'] = owncash
            result.ix[i, 'commission_fee'] = commission
            result.ix[i, 'per earn'] = perearn
            result.ix[i, 'trade money'] = owncash / margin_rate

        endcash = result.ix[oprtimes - 1, 'own cash']
        Annual = RS.annual_return(result)
        Sharpe = RS.sharpe_ratio(result)
        DrawBack = RS.max_drawback(result)[0]
        SR = RS.success_rate(result)
        max_single_loss_rate = abs(result['ret_r'].min())

        results = {
            'Setname':setname,
            'MACD_S':MACD_S,
            'MACD_L':MACD_L,
            'MACD_M':MACD_M,
            'opentimes': oprtimes,
            'end_cash': endcash,
            'SR': SR,
            'Annual':Annual,
            'Sharpe':Sharpe,
            'DrawBack':DrawBack,
            'max_single_loss_rate': max_single_loss_rate
        }
        print results
    filename = ("%s%d %s result.csv" % (symbolInfo.symbol, K_MIN_MACD,setname))
    result.to_csv(filename)
    rawdata_macd.to_csv('macd '+filename)
    del rawdata_macd
    return results