Пример #1
0
def date_accmulation_getall(today):
    ma = [i  for i in range(2,241)]
    df_all = get_his_data('000300', ma=ma,index=True)
    test = hs_300_strategy(df_all)
    for ii in ma:
        print('processing MA_'+str(ii))
        test.backtest(ma_1=str(ii),ma_2=str(ii))
        # return原始是1,100%
        df = pd.concat([test._df.position,test._df['return'],test._df.beta,test._df.drawdown,test._df.long,
                        test._df.short],axis=1)
        write_to_mongo(df, db='Single_MA_testback', collection=today, id='MA_'+str(ii))
        test = hs_300_strategy(df_all)
Пример #2
0
def date_accmulation():
    ma = [i + 1 for i in range(120)]
    print(ma)
    df_all = get_his_data('hs300', ma=ma)
    length = len(df_all)
    for i in range(length-29):
        df = df_all[:i + 30]
        start = df.index[0]
        end = df.index[len(df) - 1]
        print('start calculate :' + str(start) + ' to ' + str(end))
        rr = test_(ma, df)
        write_to_mongo(rr, db='Single_MA_testback', collection='2016-08-31', id=str(end))
Пример #3
0
def fixed_90():
    ma = [i+1 for i in range(120)]
    print(ma)
    df_all = get_his_data('hs300', ma=ma)
    length = len(df_all)
    for i in range(length-89):
        df = df_all[i:i+90]
        start = df.index[0]
        end = df.index[len(df)-1]
        print('start calculate :'+str(start)+' to '+str(end))
        rr = test_(ma, df)
        write_to_mongo(rr,db='MA_testback',collection='Single_MA_90_rolling',id=str(end))
Пример #4
0
 def hist_data_import_to_mongodb(self):
     mongdb = MONGODB(db='ALL_STOCKS')
     for i in self._all_codes[list(self._all_codes).index('600335'):]:
         print('process code:' + i)
         data = get_his_data(i,start='2005-01-01',end='2008-01-01',if_ma=False)
         data2 = get_his_data(i,start='2008-01-01',end='2011-01-01',if_ma=False)
         data3 = get_his_data(i, start='2011-01-01', end='2014-01-01', if_ma=False)
         data4 = get_his_data(i, start='2014-01-01', end='2017-01-01', if_ma=False)
         try:
             mongdb.write_to_mongo(data,collection=i,id='2005-01-01/2008-01-01')
         except Exception as e:
             print(e)
         try:
             mongdb.write_to_mongo(data2, collection=i, id='2008-01-01/2011-01-01')
         except Exception as e:
             print(e)
         try:
             mongdb.write_to_mongo(data3, collection=i, id='2011-01-01/2014-01-01')
         except Exception as e:
             print(e)
         try:
             mongdb.write_to_mongo(data4, collection=i, id='2014-01-01/2016-09-06')
         except Exception as e:
             print(e)
    drawback = []
    Beta = []
    position = []
    for i in range(1, len(ma)):
            print('Process MA'+str(ma[i]))
            test.backtest(ma_1=str(ma[i]), ma_2=str(ma[i]))
            comb.append(str(ma[i]))
# 不变为0,return, drawback,beta 都是 delta%变化
            return_.append(float(test._df[len(test._df)-1:len(test._df)]['return'][0]-1)*100)
            drawback.append(str(max(test._df.drawdown)*100))
            Beta.append((test._df[len(test._df)-1:len(test._df)]['beta'][0]-1)*100)
            position.append(test._df.position[len(test._df)-1])
# test._df.to_csv('1234.csv')
            test = hs_300_strategy(df)

    return pd.DataFrame({'MA':comb,'return':return_,'Beta':Beta,'drawback':drawback,
                         'start':test._df.index[0],'end':test._df.index[len(test._df)-1],
                         'position':position}).set_index('MA')


if __name__ == '__main__':
    # df = get_his_data('hs300',ma = [5,12,13,18,20,30,60,120])
    # print(df)
    i=60
    ma = [1,i]
    df_all = get_his_data('hs300', ma=ma)
    result = test_(ma,df_all)
    print(result)


Пример #6
0
        self.if_monkey(longest_period=longest_period)
        self.long_or_short()
        self._equity()
        self._win_lose()
        self._drawdown()
        self._return_rate()
        self.long_short_count()
        self._beta()
        print('最大回撤:' + str(max(self.drawdown) * 100) + '%')
        print('买入信号统计:' + str(self.long_count))
        print('卖出信号统计:' + str(self.short_count))
        print('全仓平仓亏损:' + str(self.lost_rate))
        print('全仓平仓赢: ' + str(self.win_rate))
        print('最大回报:' + str((self._df['return'].max() - 1) * 100) + '%')
        print('最大亏损:' + str((self._df['return'].min() - 1) * 100) + '%')
        print('总回报:' + str(self._df[len(self._df) - 1:len(self._df)]['return']))
        return self._df

if __name__=='__main__':
    df = get_his_data('513100',ma=[3,60,120,250])
    print(df)
    #df = get_his_data('162411',ma=[4,5,13,12,20,30,60,120,18,14])
    print(df)
    test = NSDK(df)
    #print(test._df)
    pgraph = test.backtest()
    print('start date: ' + test.start_date)
    test._df.to_csv('test3.csv')
    #test.coef_find()
    pgraph = get_rid_unchanged_equity(pgraph)
    plot_return_beta(pgraph)
            all_return[str(ma[i]) + ',' + str(ma[k])] = test.backtest(ma_1=str(ma[k]), ma_2=str(ma[i]))
            #test._df.to_csv('test!!!'+str(i)+'.csv')
            comb.append(str(ma[i]) + ',' + str(ma[k]))
            return_.append(str((test._df[len(test._df)-1:len(test._df)]['return'][0]-1)*100)+'%')
            drawback.append(str(max(test._df.drawdown)*100)+'%')
            Beta.append(test._df[len(test._df)-1:len(test._df)]['beta'][0])
            test = hs_300_strategy(df)
            print('Get result of (' + str(ma[i]) + ',' + str(ma[k]) + '):', end='')
            print(all_return[str(ma[i]) + ',' + str(ma[k])])
    return pd.DataFrame({'comb':comb,'return':return_,'Beta':Beta,'drawback':drawback,
                         'start':test._df.index[0],'end':test._df.index[len(test._df)-1]})


if __name__=='__main__':
    ma = [1,2,3,4,5,6,7,8,9,10]+[i for i in range(20,40)]+[j for j in range(100, 120)]+[seg for seg in range(230,251)]
    df = get_his_data('hs300',ma=ma,start='2014-08-01')
    test_1 = hs_300_strategy(df)
    all_return_1 = {}
    resu = test_(ma,all_return_1,test_1)
    resu.to_csv('20_to_40_results_3years',mode='w')

    """
#
    df = get_his_data('hs300', ma=ma, start='2015-01-01', end='2015-03-31')
    test_2 = hs_300_strategy(df)
    all_return_2 = {}
    resu = test_(ma, all_return_2, test_2)
    resu.to_csv('ma_test_result.csv', mode='a')
#
    df = get_his_data('hs300', ma=ma, start='2015-04-01', end='2015-06-31')
    test_3 = hs_300_strategy(df)
Пример #8
0
            print(all_return[str(ma[i]) + ',' + str(ma[k])])
    return pd.DataFrame({
        'comb': comb,
        'return': return_,
        'Beta': Beta,
        'drawback': drawback,
        'start': test._df.index[0],
        'end': test._df.index[len(test._df) - 1]
    })


if __name__ == '__main__':
    ma = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + [i for i in range(20, 40)] + [
        j for j in range(100, 120)
    ] + [seg for seg in range(230, 251)]
    df = get_his_data('hs300', ma=ma, start='2014-08-01')
    test_1 = hs_300_strategy(df)
    all_return_1 = {}
    resu = test_(ma, all_return_1, test_1)
    resu.to_csv('20_to_40_results_3years', mode='w')
    """
#
    df = get_his_data('hs300', ma=ma, start='2015-01-01', end='2015-03-31')
    test_2 = hs_300_strategy(df)
    all_return_2 = {}
    resu = test_(ma, all_return_2, test_2)
    resu.to_csv('ma_test_result.csv', mode='a')
#
    df = get_his_data('hs300', ma=ma, start='2015-04-01', end='2015-06-31')
    test_3 = hs_300_strategy(df)
    all_return_3 = {}
Пример #9
0
        elif self._df.bear[i] ==1 and \
            self._df.ma_5_close[i] < self._df.ma_5_close[i - 1] and \
            self._df.ma_5_close[i - 1] > self._df.ma_5_close[i - 2]:
            self._df.loc[i:i + 1, 'short'] = 1
            return True, 1, 1
        # 猴市---------->
        elif self._df.monkey[i] ==1 and \
            self._df.ma_5_close[i] < self._df.ma_13_close[i] and \
            self._df.ma_5_close[i-1] > self._df.ma_13_close[i-1]:
            self._df.loc[i:i + 1, 'short'] = 1
            return True, 1, 1
        else:
            return False, 1, 1


if __name__ == '__main__':
    df = get_his_data('hs300',
                      start='2014-01-01',
                      ma=[5, 12, 13, 18, 20, 30, 60, 120],
                      index=True)
    #print(df)
    #df = read_csv_excel('/Users/leotao/Downloads/沪深300回测.xlsx', '择时分析-创')
    #df = MA_CALCULATOR(df)
    #df = df.get_ma(ll = [5,12,13,18,20,30,60,120])
    test = hs_300_strategy(df)
    pgraph = test.backtest()
    print('start date: ' + test.start_date)
    #test._df.to_csv('test2.csv')
    #test.coef_find()
    pgraph = get_rid_unchanged_equity(pgraph)
    plot_return_beta(pgraph)
Пример #10
0
                return True, 1, 1
            else:
                return False,1,1
        # 猴市---------->
        elif self._df.monkey[i] == 1:
            if self._df.ma_5_close[i] < self._df.ma_10_close[i] and \
                        self._df.ma_5_close[i - 1] > self._df.ma_10_close[i - 1]:
                self._df.loc[i:i + 1, 'short'] = 1
                return True, 1, 1
            elif self._df.bull[i-1] ==1 and self._df.ma_5_close[i] < self._df.ma_10_close[i]:
                self._df.loc[i:i + 1, 'short'] = 1
                return True, 1, 1
            else:
                return False, 1, 1
        else:
            return False, 1, 1

if __name__=='__main__':
    #df = read_csv_excel('/Users/leotao/Downloads/创业板回测(1).xlsx','择时分析-创')
    df = get_his_data('cyb',ma=[4,5,13,20,30,60,120,18,10])
    #df = MA_CALCULATOR(df)
    #df = df.get_ma(ll =[4,5,13,12,20,30,60,120,18,14])
    print(df)
    test = CYB(df)
    #print(test._df)
    pgraph = test.backtest()
    print('start date: ' + test.start_date)
    test._df.to_csv('test3.csv')
    #test.coef_find()
    pgraph = get_rid_unchanged_equity(pgraph)
    plot_return_beta(pgraph)
from Models.Closed_Price_Prediction_model import arbitrary_prediction
from Strategys.INDEX_STRATEGY.CYB import CYB
from Strategys.INDEX_STRATEGY.Gold_ETF import GOLD_ETF
from Strategys.INDEX_STRATEGY.NSDK import NSDK
from Strategys.INDEX_STRATEGY.hs_300_strategy import hs_300_strategy
from Strategys.INDEX_STRATEGY.petro_ETF import PETRO_ETF
from pitcher import get_his_data

today = datetime.datetime.today()-datetime.timedelta(1)
yesterday = str(today)[0:10]
def tree_predict(df):
    xx = arbitrary_prediction(df)
    return [xx.one_day_gradient_change()]

start = '2015-10-10'
gold_index = get_his_data('159934',start=start,ma=[4,5,12,13,16,18,20,30,60,120,14],index=True)
gold_index = tree_predict(gold_index)




petro_index = get_his_data('162411',ma=[4,5,12,13,16,18,20,30,60,120,14],start=start,index=True)
petro_index = tree_predict(petro_index)



hs300_index = get_his_data('000300',ma = [5,12,13,16,18,20,30,60,120,14],start=start,index=True)
hs300_index = tree_predict(hs300_index)


Пример #12
0
                return False, 1, 1
        # 猴市---------->
        elif self._df.monkey[i] == 1:
            if self._df.ma_5_close[i] < self._df.ma_10_close[i] and \
                        self._df.ma_5_close[i - 1] > self._df.ma_10_close[i - 1]:
                self._df.loc[i:i + 1, 'short'] = 1
                return True, 1, 1
            elif self._df.bull[i - 1] == 1 and self._df.ma_5_close[
                    i] < self._df.ma_10_close[i]:
                self._df.loc[i:i + 1, 'short'] = 1
                return True, 1, 1
            else:
                return False, 1, 1
        else:
            return False, 1, 1


if __name__ == '__main__':
    #df = read_csv_excel('/Users/leotao/Downloads/创业板回测(1).xlsx','择时分析-创')
    df = get_his_data('cyb', ma=[4, 5, 13, 20, 30, 60, 120, 18, 10])
    #df = MA_CALCULATOR(df)
    #df = df.get_ma(ll =[4,5,13,12,20,30,60,120,18,14])
    print(df)
    test = CYB(df)
    #print(test._df)
    pgraph = test.backtest()
    print('start date: ' + test.start_date)
    test._df.to_csv('test3.csv')
    #test.coef_find()
    pgraph = get_rid_unchanged_equity(pgraph)
    plot_return_beta(pgraph)
Пример #13
0
        self._equity()
        self._win_lose()
        self._drawdown()
        self._return_rate()
        self.long_short_count()
        self._beta()
        print('最大回撤:' + str(max(self.drawdown) * 100) + '%')
        print('买入信号统计:' + str(self.long_count))
        print('卖出信号统计:' + str(self.short_count))
        print('全仓平仓亏损:' + str(self.lost_rate))
        print('全仓平仓赢: ' + str(self.win_rate))
        print('最大回报:' + str((self._df['return'].max() - 1) * 100) + '%')
        print('最大亏损:' + str((self._df['return'].min() - 1) * 100) + '%')
        print('总回报:' +
              str(self._df[len(self._df) - 1:len(self._df)]['return']))
        return self._df


if __name__ == '__main__':
    df = get_his_data('513100', ma=[3, 60, 120, 250])
    print(df)
    #df = get_his_data('162411',ma=[4,5,13,12,20,30,60,120,18,14])
    print(df)
    test = NSDK(df)
    #print(test._df)
    pgraph = test.backtest()
    print('start date: ' + test.start_date)
    test._df.to_csv('test3.csv')
    #test.coef_find()
    pgraph = get_rid_unchanged_equity(pgraph)
    plot_return_beta(pgraph)
Пример #14
0
        # 不变为0,return, drawback,beta 都是 delta%变化
        return_.append(
            float(test._df[len(test._df) - 1:len(test._df)]['return'][0] - 1) *
            100)
        drawback.append(str(max(test._df.drawdown) * 100))
        Beta.append(
            (test._df[len(test._df) - 1:len(test._df)]['beta'][0] - 1) * 100)
        position.append(test._df.position[len(test._df) - 1])
        # test._df.to_csv('1234.csv')
        test = hs_300_strategy(df)

    return pd.DataFrame({
        'MA': comb,
        'return': return_,
        'Beta': Beta,
        'drawback': drawback,
        'start': test._df.index[0],
        'end': test._df.index[len(test._df) - 1],
        'position': position
    }).set_index('MA')


if __name__ == '__main__':
    # df = get_his_data('hs300',ma = [5,12,13,18,20,30,60,120])
    # print(df)
    i = 60
    ma = [1, i]
    df_all = get_his_data('hs300', ma=ma)
    result = test_(ma, df_all)
    print(result)
Пример #15
0
            self._df.loc[i:i + 1, 'short'] = 1
            return True,1,1
        # 熊市---------->
        elif self._df.bear[i] ==1 and \
            self._df.ma_5_close[i] < self._df.ma_5_close[i - 1] and \
            self._df.ma_5_close[i - 1] > self._df.ma_5_close[i - 2]:
            self._df.loc[i:i + 1, 'short'] = 1
            return True,1,1
        # 猴市---------->
        elif self._df.monkey[i] ==1 and \
            self._df.ma_5_close[i] < self._df.ma_13_close[i] and \
            self._df.ma_5_close[i-1] > self._df.ma_13_close[i-1]:
            self._df.loc[i:i + 1, 'short'] = 1
            return True,1,1
        else:
            return False,1,1


if __name__=='__main__':
    df = get_his_data('hs300',start='2014-01-01',ma = [5,12,13,18,20,30,60,120],index=True)
    #print(df)
    #df = read_csv_excel('/Users/leotao/Downloads/沪深300回测.xlsx', '择时分析-创')
    #df = MA_CALCULATOR(df)
    #df = df.get_ma(ll = [5,12,13,18,20,30,60,120])
    test = hs_300_strategy(df)
    pgraph = test.backtest()
    print('start date: ' + test.start_date)
    #test._df.to_csv('test2.csv')
    #test.coef_find()
    pgraph = get_rid_unchanged_equity(pgraph)
    plot_return_beta(pgraph)
Пример #16
0
            all_return[str(ma[i]) + ',' + str(ma[k])] = test.backtest(ma_1=str(ma[k]), ma_2=str(ma[i]))
            #test._df.to_csv('test!!!'+str(i)+'.csv')
            comb.append(str(ma[i]) + ',' + str(ma[k]))
            return_.append(str((test._df[len(test._df)-1:len(test._df)]['return'][0]-1)*100)+'%')
            drawback.append(str(max(test._df.drawdown)*100)+'%')
            Beta.append(test._df[len(test._df)-1:len(test._df)]['beta'][0])
            test = hs_300_strategy(df)
            #print('Get result of (' + str(ma[i]) + ',' + str(ma[k]) + '):', end='')
            #print(all_return[str(ma[i]) + ',' + str(ma[k])])
    return pd.DataFrame({'comb':comb,'return':return_,'Beta':Beta,'drawback':drawback,
                         'start':test._df.index[0],'end':test._df.index[len(test._df)-1]})


if __name__=='__main__':
    ma = [5, 7, 10, 20, 30, 60, 120, 240]
    df = get_his_data('hs300',ma=ma,start='2014-08-01',end='2014-12-31')
    test_1 = hs_300_strategy(df)
    all_return_1 = {}
    resu = test_(ma,all_return_1,test_1)
    resu.to_csv('ma_test_result.csv',mode='a')
#
    df = get_his_data('hs300', ma=ma, start='2015-01-01', end='2015-03-31')
    test_2 = hs_300_strategy(df)
    all_return_2 = {}
    resu = test_(ma, all_return_2, test_2)
    resu.to_csv('ma_test_result.csv', mode='a')
#
    df = get_his_data('hs300', ma=ma, start='2015-04-01', end='2015-06-31')
    test_3 = hs_300_strategy(df)
    all_return_3 = {}
    resu = test_(ma, all_return_3, test_3)