通过改变输入参数来优化脚本的输出

时间:2018-04-18 16:59:33

标签: python optimization scipy mathematical-optimization

我有一个使用下面代码编写的脚本,我想优化rsi_high和rsi_low以获得最佳的sharpe_ratio:

#
import numpy
import talib as ta

global rsi_high, rsi_low

rsi_high = 63
rsi_low = 41


def myTradingSystem(DATE, OPEN, HIGH, LOW, CLOSE, VOL, exposure, equity, settings):
    ''' This system uses trend following techniques to allocate capital into the desired equities'''

    nMarkets = CLOSE.shape[1] # SHAPE OF NUMPY ARRAY

    result, rsi_pos = numpy.apply_along_axis(rsicalc, axis=0, arr=CLOSE)

    pos = numpy.asarray(rsi_pos, dtype=numpy.float64)

    return pos, settings

def rsicalc(num):
    # print rsi_high
    try:
        rsival = ta.RSI(numpy.array(num,dtype='f8'),timeperiod=14)
        if rsival[14] > rsi_high: pos_rsi = 1
        elif rsival[14] < rsi_low: pos_rsi = -1
        else: pos_rsi = 0
    except:
        rsival = 0
        pos_rsi = 0
    return rsival, pos_rsi


def mySettings():
    ''' Define your trading system settings here '''

    settings = {}


    # Futures Contracts
    settings['markets'] = ['CASH','F_AD', 'F_BO', 'F_BP', 'F_C', 'F_CC', 'F_CD',
                           'F_CL', 'F_CT', 'F_DX', 'F_EC', 'F_ED', 'F_ES', 'F_FC', 'F_FV', 'F_GC',
                           'F_HG', 'F_HO', 'F_JY', 'F_KC', 'F_LB', 'F_LC', 'F_LN', 'F_MD', 'F_MP',
                           'F_NG', 'F_NQ', 'F_NR', 'F_O', 'F_OJ', 'F_PA', 'F_PL', 'F_RB', 'F_RU',
                           'F_S', 'F_SB', 'F_SF', 'F_SI', 'F_SM', 'F_TU', 'F_TY', 'F_US', 'F_W',
                           'F_XX', 'F_YM']

    settings['slippage'] = 0.05
    settings['budget'] = 1000000
    settings['beginInSample'] = '19900101'
    settings['endInSample'] = '19931231'
    settings['lookback'] = 504

    return settings

# Evaluate trading system defined in current file.
if __name__ == '__main__':
    import quantiacsToolbox
    results = quantiacsToolbox.runts(__file__, plotEquity=False)
    sharpe_ratio = results['stats']['sharpe']

我怀疑使用像scipy最小化函数的东西可以解决这个问题,但是我无法理解如何打包我的脚本以便它可以处于可用的形式。

我已经尝试将所有内容放在一个函数中,然后通过多个循环运行所有代码,每次递增值但是必须有一种更优雅的方式来执行此操作。

抱歉发布我的所有代码,但我认为如果响应者想要重现我的设置,并且对于那些不熟悉quantacs的人来说,看到面对同样问题的真实例子会有所帮助。

提前感谢您的帮助!

0 个答案:

没有答案