def __init__(self, _good_list): index.TurtleArgs.__init__(self) self.sdsr = data.StockData_SQLite(self.files[0]) self.long_list, self.short_list = [], [] for _row in _good_list: for _idx in range(0, len(_row['codes'])): self.statis_fut(_row['codes'][_idx], _row['index'][_idx], _row['names'][_idx]) long_turtle = pandas.DataFrame(self.long_list, columns=[ 'ts_code', 'date', 'state', 'close', 'high', 'low', 'rise', 'drop', 'wave', 'ts_name' ]) short_turtle = pandas.DataFrame(self.short_list, columns=[ 'ts_code', 'date', 'state', 'close', 'high', 'low', 'rise', 'drop', 'wave', 'ts_name' ]) long_turtle.to_csv("fut_turtle.csv") # long_turtle = pandas.DataFrame(self.long_list, columns=[ 'ts_code', 'index', 'date', 'close', # 'high', 'low', 'ts_name' ]) # print( long_turtle ) print(long_turtle[long_turtle['state'] > 0]) print(short_turtle[short_turtle['state'] > 0]) print(long_turtle[long_turtle['rise'] < 5]) print(short_turtle[short_turtle['drop'] > -5])
def __init__(self): utils.TradeTest.__init__(self) sdsr = data.StockData_SQLite(self.files[0]) self.curr_closes = {} self.float_str = StockDataSource.float_date(self.dates[0]) self.float_end = StockDataSource.float_date(self.dates[1]) for code in self.codes: sdsr.read_stock(code, self.dates[0], self.dates[1]) if not len(sdsr.stocks): sdsr.load(code, self.dates[0], self.dates[1], self.params[0]) if not len(sdsr.stocks): continue data_list, _dates = sdsr.parse_price() _data_vec = numpy.transpose(data_list) turtle = index.TurtleIndex() index_long = index.LongTurtleIndex(turtle, _data_vec, self.turtle_args[2], self.turtle_args[3], self.turtle_args[0], self.turtle_args[1]) self.fixed_invest(code, _data_vec, index_long) print("%s %s, use time %.02f seconds." % ('single_turtle', code, time.time() - self.start)) self.account.save_records(code, self.files[2]) self.plot(data_list, index_long, code)
def calc_index(self, data_db, _index_code, stock_count = 300): sdsr = data.StockData_SQLite( data_db ) y, m, count = 2005, 7, 0 sttdate, enddate = '20000101', '20190601' delta1, delta2 = (self.cycle_month[0]/12.)*365., (self.cycle_month[1]/12.)*365. for i in range(0, 56): _end = dt.datetime(y, m, 1) _stt = _end + dt.timedelta(days=-30) _stt = StockDataSource.str_date(_stt) _end = StockDataSource.str_date(_end) m += 3 if m > 12: y, m = y+1, 1 df = StockData_Tushare.ts_api.index_weight(index_code=_index_code, start_date = _stt, end_date = _end) if len(df) < stock_count: continue consts = df.head(stock_count) for index, row in consts.iterrows(): code = row['con_code'] _sql = 'select ts_code, count(*) as rows from strong_indexs where ts_code = "%s";'%code _data_row = pd_sql.read_sql(_sql, self.conn) if _data_row.iloc[0, 1] > 0: continue sdsr.read_stock(code, sttdate, enddate) _len = len(sdsr.stocks) if not _len: continue data_list, _dates = sdsr.parse_price() data_vect = numpy.transpose(data_list) data_vect[4] = list(map(lambda x: math.log(x), data_vect[4])) chgs1, ks1, bs1 = self.calc_index(data_vect[0], data_vect[4], delta1) chgs2, ks2, bs2 = self.calc_index(data_vect[0], data_vect[4], delta2) _sql = 'INSERT INTO strong_indexs (ts_code, trade_date, close, chg1, k1, b1, chg2, k2, b2)\ VALUES (?,?,?,?,?,?,?,?,?);' _codes = [code for _ in range(_len)] _vect = [_codes, _dates, data_vect[4], chgs1, ks1, bs1, chgs2, ks2, bs2] self.curs.executemany( _sql, numpy.transpose( _vect ) ) # count = self.calc(df.head(30), sdsr) print( 'calc %d stocks\' index on %s.'%(count, _end) )
def __init__(self): index.TurtleArgs.__init__(self) title = 'plot[' for code in self.codes: title = '%s%s' % (title, code) title = '%s]' % title plot = utils.StockDisp(title, 1) sdsr = data.StockData_SQLite(self.files[0]) turtle = index.TurtleIndex() for code in self.codes: sdsr.load(code, self.dates[0], self.dates[1], self.params[0], self.params[1]) if not len(sdsr.stocks): continue data_list, _dates = sdsr.parse_price() _data_vec = numpy.transpose(data_list) if self.params[2] == 'long': long_index = index.LongTurtleIndex(turtle, _data_vec, self.turtle_args[2], self.turtle_args[3], self.turtle_args[0], self.turtle_args[1]) # short_index = index.LongTurtleIndex(turtle, _data_vec, self.turtle_args[4], # self.turtle_args[5], self.turtle_args[0], self.turtle_args[1]) else: long_index = index.ShortTurtleIndex(turtle, _data_vec, self.turtle_args[2], self.turtle_args[3], self.turtle_args[0], self.turtle_args[1]) # short_index = index.ShortTurtleIndex(turtle, _data_vec, self.turtle_args[4], # self.turtle_args[5], self.turtle_args[0], self.turtle_args[1]) info_list = self.list_info1(_data_vec, long_index) # info_list = self.list_info2(_data_vec, long_index, short_index['state'] ) # print( info_list[-80:-40] ) print(info_list.tail(40)) info_list.to_csv('%s/%s.csv' % (self.files[2], code)) plot.LogKDisp(plot.ax1, data_list) # plot.LogPlot(plot.ax1, _data_vec[0], turtle_index['long'], 'r') # plot.LogPlot(plot.ax1, _data_vec[0], turtle_index['short'], 'y') # plot.Plot(plot.ax1, _data_vec[0], self.stim.data['average'], 'b') plot.save(title, self.files[3])
def __init__(self): utils.TradeTest.__init__(self) sdsr = data.StockData_SQLite(self.files[0]) self.curr_closes = {} self.float_str = StockDataSource.float_date(self.dates[0]) self.float_end = StockDataSource.float_date(self.dates[1]) for code in self.codes: sdsr.read_stock(code, self.dates[0], self.dates[1]) if not len(sdsr.stocks): sdsr.load(code, self.dates[0], self.dates[1], self.params[0]) if not len(sdsr.stocks): continue data_list, _dates = sdsr.parse_price() _data_vec = numpy.transpose(data_list) pe_table = sdsr.index_daaily(code, self.dates[0], self.dates[1])
#!/usr/bin/env python #-*- coding: utf8 -*- import numpy, pandas, datetime as dt, time from turtle import trade, index, data, utils from turtle.data import StockDataSource if __name__ == "__main__": args = index.TurtleArgs() sdsr = data.StockData_SQLite(args.files[0]) for code in args.codes: sdsr.load(code, args.dates[0], args.dates[1], args.params[0], args.params[1]) if not len(sdsr.stocks): continue data_list, _dates = sdsr.parse_price() _data_vec = numpy.transpose(data_list) turtle = index.TurtleIndex() if args.params[2] == 'long': long_index = index.LongTurtleIndex(turtle, _data_vec, args.turtle_args[2], args.turtle_args[3], args.turtle_args[0], args.turtle_args[1]) else: long_index = index.ShortTurtleIndex(turtle, _data_vec, args.turtle_args[2], args.turtle_args[3], args.turtle_args[0], args.turtle_args[1])
print( pandas.DataFrame( self.records, columns=['date', 'price', 'total', 'cash', 'profit', 'ratio'])) self.account.status_info() print('all day %d, long day %d. %s %s, use time %.02f seconds.' % (all_days, long_days, 'single_turtle', code, time.time() - self.start)) self.account.save_records(code, self.files[2]) self.plot(data_list, index_long, code) if __name__ == "__main__": test = DauLTurtleTrade() sdsr = data.StockData_SQLite(test.files[0]) for code in test.codes: sdsr.read_stock(code, test.dates[0], test.dates[1]) if not len(sdsr.stocks): sdsr.load(code, test.dates[0], test.dates[1], test.params[0], test.params[1]) if not len(sdsr.stocks): continue data_list, _dates = sdsr.parse_price() print(len(data_list)) test.start_test(test.turtle_args[2], 1000 * 10000) test.long_turtle(code, data_list) # test.short_turtle( code, data_list )
def __init__(self): index.TurtleArgs.__init__(self) if self.files[1] != ':memory:': self.csv_file = self.files[1] else: self.csv_file = 'fund_pos.csv' self.positions = PositionCSV.read_csv(self.csv_file) sdsr = data.StockData_SQLite(self.files[0]) pos_list = self.positions.values.tolist() prev_closes, total_values, profits, may_loss, stop_prices, loss_ratios = [], [], [], [], [], [] total_invest, total_value, total_profit, total_loss = 0, 0, 0, 0 for row in pos_list: code, volume, cost_price, good_type = row[0:4] sdsr.load(code, self.dates[0], self.dates[1], good_type) if not len(sdsr.stocks): continue data_list, _dates = sdsr.parse_price() _data_vec = numpy.transpose(data_list) turtle = index.TurtleIndex() turtle_index = index.LongTurtleIndex(turtle, _data_vec, self.turtle_args[2], self.turtle_args[3], self.turtle_args[0], self.turtle_args[1]) # info_list = self.list_info(_data_vec, turtle_index ) list_len = len(turtle_index['key_price']) _last = list_len - 1 _prev_close = _data_vec[4][_last] _key_price, _profit_price, _wave = turtle_index['key_price'][ _last], turtle_index['short'][_last], turtle_index['wave'][ _last] _value = volume * _prev_close _cost = volume * cost_price _stop_price = _key_price - _wave * self.turtle_args[0] if cost_price > _key_price: _stop_price = cost_price - _wave * self.turtle_args[0] _mayloss = volume * (_stop_price - cost_price) _stop_price = max(_stop_price, _profit_price) total_invest += _cost total_value += _value total_profit += _value - _cost total_loss += _mayloss prev_closes.append(_prev_close) total_values.append(_value) stop_prices.append(_stop_price) loss_ratios.append(100 * _stop_price / _prev_close - 100) profits.append(_value - _cost) # profit_prices.append( _profit_price ) may_loss.append(_mayloss) self.positions['prev'] = prev_closes self.positions['stop'] = stop_prices self.positions['ratio'] = loss_ratios self.positions['value'] = total_values self.positions['profit'] = profits # self.positions['profit_price'] = profit_prices self.positions['may_loss'] = may_loss self.positions.drop('type', axis=1, inplace=True) print(self.positions) print( 'SUM invest: %.03f, value: %.03f, profit: %.03f, mayloss: %.03f.' %\ (total_invest*0.0001, total_value*0.0001, total_profit*0.0001, total_loss*.0001) )
def __init__(self): index.TurtleArgs.__init__(self) sdsr = data.StockData_SQLite(self.files[0]) turtle_list = [] for code in self.codes: sdsr.load(code, self.dates[0], self.dates[1], self.params[0]) if not len(sdsr.stocks): continue data_list, _dates = sdsr.parse_price() _data_vec = numpy.transpose(data_list) turtle = index.TurtleIndex() index_long = index.LongTurtleIndex(turtle, _data_vec, self.turtle_args[2], self.turtle_args[3], self.turtle_args[0], self.turtle_args[1]) Hl = turtle.high_prices[self.turtle_args[2]] # print( Hl ) turtle = index.TurtleIndex() index_short = index.LongTurtleIndex(turtle, _data_vec, self.turtle_args[3], self.turtle_args[4], self.turtle_args[0], self.turtle_args[1]) long_list = self.list_info(_data_vec, index_long) long_list.tail(30).to_csv('long.csv') print(long_list.tail(5)) short_list = self.list_info(_data_vec, index_short) short_list.tail(30).to_csv('short.csv') print(short_list.tail(5)) _last = len(_data_vec[0]) - 1 _price, _wave = index_long['key_price'][_last], index_long['wave'][ _last] if index_long['state'][_last]: _append = _price + _wave _stoploss = _price - _wave * self.turtle_args[0] _pos_unit = int(1000 / _wave) else: _append, _stoploss, _pos_unit = 0, 0, 0 turtle_list.append([ code, _dates[_last], index_long['state'][_last], _price, _append, _stoploss, _pos_unit, index_long['short'][_last], _wave, _data_vec[4][_last] ]) print( pandas.DataFrame(turtle_list, columns=[ 'ts_code', 'date', 'state', 'key_price', 'append', 'stop_loss', 'pos_unit', 'valley', 'wave', 'close' ]))