예제 #1
0
def backtest(acts, o_R):
    pacts = np.asarray(acts).copy()
    for i in range(1, pacts.shape[0]):
        if pacts[i] == 0:
            if pacts[i - 1] == -1:
                # from short
                pacts[i] = 0.5
            elif pacts[i - 1] == 1:
                pacts[i] = -0.5

    # plt.plot(pacts, '.')
    data = o_R[dep - 1:-3]

    buy = cover = pd.Series(pacts == 1, index=data.index)
    short = sell = pd.Series(pacts == -1, index=data.index)
    cover = pd.Series(pacts > 0, index=data.index)
    sell = pd.Series(pacts < 0, index=data.index)
    # print(np.sum(buy-sell))
    OHLC = data[[('DealPrice', 'close'), ('DealPrice', 'close'), ('DealPrice', 'close'), ('DealPrice', 'close')]]
    OHLC.columns = ['O', 'H', 'L', 'C']

    bt = pb.Backtest(locals())
    return bt
예제 #2
0
    ohlc = tdxday.get_data_pybacktest(start='20110101')
    ohlc.ta.fractals(high='H', low='L', open='O', close='C', append=True)
    ohlc.ta.bottomreversal(high='H', low='L', open='O', close='C', append=True)
    ohlc.ta.topreversal(high='H', low='L', open='O', close='C', append=True)
    scdm = ohlc.scdm
    ohlc.to_csv(f"{scdm}{filename}.csv")

    # buy买入,sell卖出,Buy to Cover 空单补回,Sell Short 卖空
    # 由于融资融券风险较大,在此不做融券策略,也就是不配置cover和short
    # 只配置buy和sell
    # buy
    buy = ohlc['BOTTOM_REVERSAL']
    sell = ohlc['TOP_REVERSAL']

    # locals() 函数会以字典类型返回当前位置的全部局部变量。
    bt = pybacktest.Backtest(locals(), 'hyb_reversal')
    newlist = list(filter(lambda x: not x.startswith('_'), dir(bt)))
    print(newlist)
    print('\n>  bt.signals\n%s' % bt.signals.tail())
    print('\n>  bt.trades\n%s' % bt.trades.tail())
    print('\n>  bt.positions\n%s' % bt.positions.tail())
    print('\n>  bt.equity\n%s' % bt.equity.tail())
    print('\n>  bt.trade_price\n%s' % bt.trade_price.tail())
    bt.summary()

    fig = plt.figure(figsize=(24, 12))
    ax1 = plt.subplot2grid((6, 4), (0, 0), rowspan=3, colspan=4)

    bt.plot_trades(ax=ax1)
    ax1.grid(True)
    plt.ylabel('Price')
예제 #3
0
ml1 = pandas.rolling_mean(hl_diff, lips_sma_period)
mt1 = pandas.rolling_mean(hl_diff, teeth_sma_period)
mj1 = pandas.rolling_mean(hl_diff, jaw_sma_period)

ml = ml1.shift(2)
mt = mt1.shift(4)
mj = mj1.shift(7)

buy = cover = (ml > mt) & (mt > mj) & ((ml.shift() < mt.shift()) | (mt.shift() < mj.shift()))
sell = short = (ml < mt) & (mt < mj) & ((ml.shift() > mt.shift()) | (mt.shift() > mj.shift()))

del cover
del short


bt = pybacktest.Backtest(locals(), 'alligator')
# df = pandas.DataFrame()
# df['ml'] = ml
# df['mt'] = mt
# df['mj'] = mj

# location = '/home/sigmasoft6/Desktop/alligator_test.xlsx'
# df = ohlc.copy()
# df['ml'] = ml
# df['mt'] = mt
# df['mj'] = mj
# df['buy'] = bt.signals['Buy']
# df['sell'] = bt.signals['Sell']
# df.to_excel(location,sheet_name='testing',index=True)

#print bt.signals.tail()
예제 #4
0
    weekclose,
    fastperiod=Week_fastLength,
    slowperiod=Week_slowLength,
    signalperiod=Week_signalLength)

entry_Rsi = ta.RSI(close, rsi_entry_length)
exit_Rsi = ta.RSI(close, rsi_exit_length)

Week_Macdhist_resampled = Week_Macdhist.resample('B').ffill().shift(5)
weekbool = (Week_Macdhist_resampled >= week_macd_filter)
df['W'] = weekbool
weekbool = df['W']
sell = (exit_Macd <
        exit_Macdsignal) & (exit_Macd.shift() >= exit_Macdsignal.shift()) & (
            exit_Macd >= top_Long_filter) & (exit_Rsi > rsi_exit_filter)
buy = (Macd > Macdsignal) & (Macd.shift() <= Macdsignal.shift()) & (
    Macd <= -bot_Long_filter) & (entry_Rsi <= rsi_entry_filter) & weekbool

bt = pybacktest.Backtest(locals(), 'test1')
bt.summary()

matplotlib.rcParams['figure.figsize'] = (15.0, 8.0)
bt.plot_equity()
try:
    bt.plot_trades()

except ValueError:
    pass
# finally:
#     plt.legend(loc='upper right')
예제 #5
0
def test_1():
    #### 登陆系统 ####
    lg = bs.login()
    # 显示登陆返回信息
    # print('login respond error_code:' + lg.error_code)
    # print('login respond  error_msg:' + lg.error_msg)

    #### 获取沪深A股历史K线数据 ####
    # 详细指标参数,参见“历史行情指标参数”章节;“分钟线”参数与“日线”参数不同。
    # 分钟线指标:date,time,code,open,high,low,close,volume,amount,adjustflag
    rs = bs.query_history_k_data_plus(
        "sz.000001",
        "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,isST",
        start_date='2018-04-01',
        end_date='2020-04-18',
        frequency="d",
        adjustflag="3")
    # print('query_history_k_data_plus respond error_code:' + rs.error_code)
    # print('query_history_k_data_plus respond  error_msg:' + rs.error_msg)

    #### 打印结果集 ####
    data_list = []
    while (rs.error_code == '0') & rs.next():
        # 获取一条记录,将记录合并在一起
        data_list.append(rs.get_row_data())
    result = pd.DataFrame(data_list, columns=rs.fields)

    #### 结果集输出到csv文件 ####
    # result.to_csv("D:\\history_A_stock_k_data.csv", index=False)
    # print(result)

    #### 登出系统 ####
    bs.logout()

    ohlc = result.rename(
        columns={
            'date': 'Date',
            'open': 'O',
            'high': 'H',
            'low': 'L',
            'close': 'C',  #'Adj Close': 'AC',
            'volume': 'V'
        })
    ohlc['Date'] = pd.to_datetime(ohlc['Date'])
    ohlc.set_index("Date", inplace=True)
    ohlc["O"] = ohlc["O"].astype("float")
    ohlc["H"] = ohlc["H"].astype("float")
    ohlc["L"] = ohlc["L"].astype("float")
    ohlc["C"] = ohlc["C"].astype("float")
    ohlc["V"] = ohlc["V"].astype("int")
    ohlc.info()
    # ohlc = ohlc.set_index('Date', drop=False)
    # ohlc = pybacktest.load_from_yahoo('GOOG')
    ohlc.tail()

    short_ma = 10
    long_ma = 20

    ms = ohlc.C.rolling(short_ma).mean()
    ml = ohlc.C.rolling(long_ma).mean()

    buy = cover = (ms > ml) & (ms.shift() < ml.shift())  # ma cross up
    sell = short = (ms < ml) & (ms.shift() > ml.shift())  # ma cross down

    print('>  Short MA\n%s\n' % ms.tail())
    print('>  Long MA\n%s\n' % ml.tail())
    print('>  Buy/Cover signals\n%s\n' % buy.tail())
    print('>  Short/Sell signals\n%s\n' % sell.tail())

    bt = pybacktest.Backtest(locals(), 'ma_cross')

    print(list(filter(lambda x: not x.startswith('_'), dir(bt))))
    print('\n>  bt.signals\n%s' % bt.signals.tail())
    print('\n>  bt.trades\n%s' % bt.trades.tail())
    print('\n>  bt.positions\n%s' % bt.positions.tail())
    print('\n>  bt.equity\n%s' % bt.equity.tail())
    print('\n>  bt.trade_price\n%s' % bt.trade_price.tail())

    bt.summary()

    import matplotlib
    import matplotlib.pyplot as plt
    matplotlib.rcParams['figure.figsize'] = (15.0, 8.0)

    bt.plot_equity()

    bt.plot_trades()
    ohlc.C.rolling(short_ma).mean().plot(c='green')
    ohlc.C.rolling(long_ma).mean().plot(c='blue')
    plt.legend(loc='upper left')

    # bt.trdplot['2018':'2020']
    # ohlc.C['2018':'2020'].rolling(short_ma).mean().plot(c='green')
    # ohlc.C['2018':'2020'].rolling(long_ma).mean().plot(c='blue')
    #
    plt.show()
예제 #6
0
import pybacktest  # obviously, you should install pybacktest before importing it
import pandas as pd

ohlc = pybacktest.load_from_csv('btc_etc.csv')
ohlc.tail()

short_ma = 50
long_ma = 200

ms = ohlc.C.rolling(short_ma).mean()
ml = ohlc.C.rolling(long_ma).mean()

buy = cover = (ms > ml) & (ms.shift() < ml.shift())  # ma cross up
sell = short = (ms < ml) & (ms.shift() > ml.shift())  # ma cross down

bt = pybacktest.Backtest(locals(), 'ma_cross')

bt.summary()
예제 #7
0
ohlc1.index = ohlc1['Date']
del ohlc1['Date']
start = ohlc1.index.searchsorted(dt.datetime(2007, 01, 01))
ohlc = ohlc1[start:]

#supertrand===========================
moving_small = sptd.supertrand(ohlc)
buy = cover = (ohlc.C > moving_small) & (ohlc.C.shift() < moving_small.shift())
sell = short = (ohlc.C < moving_small) & (ohlc.C.shift() >
                                          moving_small.shift())
del cover
del short
#=====================================

#===========excel export=============
bt = pbt.Backtest(locals(), 'suprtrand')
location = '/home/sigmasoft6/Desktop/traded_sheet_output/suptndss.xlsx'
df = ohlc.copy()
df['ms'] = moving_small
# df['ml'] = moving_long
df['buy'] = bt.signals['Buy']
df['sell'] = bt.signals['Sell']
df.to_excel(location, sheet_name='testing', index=True)
#====================================

#==========graph ploat===============
# del cover
# del short
# bt = pbt.Backtest(locals(), 'aj')
# import json
# json.dump(bt.report, open(script + '-output.json', 'w'))