def insert_index_value(testType, startDate, endDate, accounts): code = db_config._index[testType] indexDatas = data_api.KData() indexDatas.fileDir = db_config.config_path if indexDatas.init_data(code, index=True, fromDB=True, end=endDate) == False: print('error') return current_date = datetime.datetime.strptime(str(startDate), "%Y-%m-%d") while current_date.strftime('%Y-%m-%d') <= endDate: dateStr = current_date.strftime('%Y-%m-%d') startIndex = indexDatas.get_index_of_date(dateStr) if startIndex >= 0: initValue = indexDatas.close(startIndex) lastValue = initValue break current_date += datetime.timedelta(days=1) for account in accounts: if account.current_date < current_date.strftime('%Y-%m-%d'): account.index_price = 0 else: index = indexDatas.get_index_of_date(account.current_date) if index >= 0: account.index_price = indexDatas.close( index) * 10000000 / initValue lastValue = indexDatas.close(index) else: account.index_price = lastValue * 10000000 / initValue
def simulate_all_once(codes, N): #对每个进行仿真运算 accounts = [] sts = simu_stat.statistics() for code in codes: datas = data_api.KData() datas.fileDir = db_config.config_path if datas.init_data(code, fromDB=False, start='2012-01-01', end='2017-01-01') == False: #print('init code error') continue #print(datetime.datetime.now()) doncainSTG = donchain_strategy.Strategy(N, 20, True) percentSTG = percent_strategy.Strategy(0.8) timeSTG = time_strategy.Strategy(60) randomSTG = random_strategy.Strategy(0.8) randomSTG1 = random_strategy.Strategy(0) mvSTG = mv_strategy.Strategy(N, 0.05, 0.05) STG = test_strategy.Strategy([doncainSTG], [doncainSTG, percentSTG, timeSTG]) account = simulate(datas, STG, Trade.Trade) accounts.append(account) sts.acc(account.statistics) print("%s,%0.2f,%0.2f,%0.2f" % (code, account.cash, account.statistics.mfeToMae, sts.mfeToMae)) #统计 print("%4d--> succ %0.2f,profit %0.2f,mfe/mae %0.2f" % (N, sts.succRatio, sts.profit * 100 / (sts.accountNum * config.config.cash), sts.mfeToMae))
obj = json.loads(jsonString) return Strategy.init_from_ast(obj) @staticmethod def create_strategy(params): stgName = params[0] if stgName == 'random': return random_strategy.Strategy(params[1]) elif stgName == 'donchain': return donchain_strategy.Strategy(params[1], params[2]) else: raise (Exception('not surportted strategy')) #real run if __name__ == "__main__": exitSTG = Strategy.init_from_json(_test_json) datas = data_api.KData() datas.init_data('300017') s = Strategy(exitSTG, donchain_strategy.Strategy(50, 20)) account = simulate(datas, s, Trade.Trade) sts = simu_stat.statistics() sts.acc(account.statistics) print("%4d--> succ %0.2f,profit %0.2f,mfe/mae %0.2f" % (0, sts.succRatio, sts.profit * 100 / (sts.accountNum * config.config.cash), sts.mfeToMae))
def real_main(indexDatas, table, startDate, endDate, typeStr): current_date = datetime.datetime.strptime(str(startDate), "%Y-%m-%d") end_date = datetime.datetime.strptime(str(endDate), "%Y-%m-%d") while current_date <= end_date: dateStr = current_date.strftime('%Y-%m-%d') weekday = current_date.strftime("%w") current_date += datetime.timedelta(days=1) if weekday == '0' or weekday == '6': print('weekday %s' % dateStr) continue yestoday = get_latest_trade_day_from_db(table) if indexDatas.get_index_of_date(dateStr) < 0: continue if yestoday == None: account = Account.MarketDayStat() account.cash = 10000000 else: jsonData = get_account_from_db(yestoday, table) tmpAccount = json.loads(jsonData) account = Account.MarketDayStat() for name, value in vars(account).items(): exec('account.%s = tmpAccount["%s"]' % (name, name)) mySTG = my_strategy.Strategy(35) testStg = test_strategy.Strategy([mySTG], [mySTG]) pool = movement_pool.StockPool(5, 60, asc=True) poolOut = movement_pool.StockPool(1, 20, asc=False) min_start = max(pool.min_start(), poolOut.min_start()) min_start = max(min_start, testStg.min_start()) if True: #if dateStr == startDate: cc = Code() codes = cc.getAllCodes() #获取数据 dataApiList = {} for code in codes: if code[:1] == typeStr or False: datas = data_api.KData() datas.fileDir = db_config.config_path fromDB = True datas.init_data(code, fromDB=fromDB, end=dateStr, Num=min_start + 2) dataApiList[code] = datas #print(datetime.datetime.now()) #test dailyAccount = concurrent_simulate.concurrent_simulate( dataApiList, testStg, pool, poolOut, dateStr, dateStr, account) index_value = 10000000 if yestoday != None: start0 = get_start_trade_day_from_db(table) index_value *= get_index_value(indexDatas, start0, dateStr) dailyAccount[-1].index_price = index_value save_account_to_db(dailyAccount[-1], dateStr, table) print('finish') return dailyAccount[-1]
startDate = '2017-01-03' endDate = '2017-03-18' real_main(indexDatas, table, startDate, endDate, typeStr) #real run if __name__ == "__main__": #start0 = get_start_trade_day_from_db('random_3') #print(get_index_value('399006', start0, '2017-02-14')) #exit() accounts = [] for i in range(3): code = db_config._index[i] indexDatas = data_api.KData() indexDatas.fileDir = db_config.config_path indexDatas.init_data(code, index=True, fromDB=True) TEST = False if TEST: test(indexDatas, db_config._type[i]) else: table = 'random_' + db_config._type[i] today = datetime.datetime.now().strftime('%Y-%m-%d') startDate = today endDate = today accounts.append( real_main(indexDatas, table, startDate, endDate, db_config._type[i]))