def runStrategy(in_prices): global prices, ps, phs, pls, rsis log.debug('beginning s6 strategy ...') prices = in_prices ps = [p['close'] for p in prices] phs = [p['high'] for p in prices] pls = [p['low'] for p in prices] rsis = rsi.calc_rsi(prices, 14) pool = StrategyPool(50) #doTrade(pool, -1, 140, 7, 1.0, -1.0) #pool.showStrategies() #return direction = -1 starttime = time.time() for i in range(50, 200)[::10]: for j in range(2, 20)[::3]: if i < j: continue elapsed = long(time.time() - starttime) log.debug('== ' + str(elapsed) + ', ' + str(i) + ',' + str(j) + ' ==') for kp in [0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3]: for kl in [0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3]: doTrade(pool, direction, i, j, kp, -kl) pool.showStrategies() return
def runStrategy(in_prices): global prices, ps, phs, pls log.debug('beginning s4 strategy ...') prices = in_prices ps = [p['close'] for p in prices] phs = [p['high'] for p in prices] pls = [p['low'] for p in prices] pool = StrategyPool(100) doTrade(pool, 110, 17, 17) pool.showStrategies() return starttime = time.time() for i in range(10, 250)[::10]: for j in range(2, 50)[::5]: if i < j: continue elapsed = long(time.time() - starttime) log.debug('== ' + str(elapsed) + ', ' + str(i) + ',' + str(j) + ' ==') for k in range (2, 50)[::5]: if i < k: continue doTrade(pool, i, j, k) pool.showStrategies() return
def sinaAgg(): # fetch price of London f = urllib2.urlopen('http://hq.sinajs.cn/?_=1386077085140/&list=hf_XAG', timeout=20) html = f.read() html = html[19:len(html) - 3] xagArr = re.split(',', html) price = {} price['dt'] = datetime.datetime.strptime(xagArr[12] + ' ' + xagArr[6], '%Y-%m-%d %H:%M:%S') xag = float(xagArr[0]) xag0 = float(xagArr[7]) log.debug('XAG: ' + xagArr[0] + ', XAG0: ' + xagArr[2]) # fetch USD price fusd = urllib2.urlopen('http://hq.sinajs.cn/rn=13860770561347070422433316708&list=USDCNY', timeout=20) htmlusd = fusd.read() htmlusd = htmlusd[19:len(htmlusd) - 3] usdArr = re.split(',', htmlusd) usd = float(usdArr[1]) log.debug('USD: ' + usdArr[0]) # calculate price in RMB price['p'] = round(usd * xag / 31.1035, 3) price['p0'] = round(usd * xag0 / 31.1035, 3) price['per'] = float(xagArr[1]) log.info('sina agg: ' + str(price['dt']) + ', ' + str(price['p']) + ', ' + str(price['p0']) + ', ' + str(price['per'])) return price
def importToArray(table): log.debug('loading ' + table + ' ...') prices = [] prec = 0 with open(os.path.join(path, '../trader_data/' + table + '.csv'), 'rb') as csvfile: rdr = csv.reader(csvfile) for row in rdr: p = {} p['open'] = float(row[2]) p['high'] = float(row[3]) p['low'] = float(row[4]) p['close'] = float(row[5]) p['vol'] = float(row[6]) p['rmb'] = round(p['close'] * 6.1 / 31.1035, 3) p['dt'] = datetime.datetime.strptime( row[0] + ' ' + row[1], '%Y.%m.%d %H:%M') #2009.06.01,00:00 p['dtlong'] = time.mktime(p['dt'].timetuple()) p['date'] = p['dt'].strftime('%Y-%m-%d') p['time'] = p['dt'].strftime('%H:%M:%S') p['chan'] = p['close'] - prec if prec == 0: p['per'] = 0 else: p['per'] = round((p['close'] - prec) * 100 / prec, 3) prec = p['close'] prices.append(p) return prices
def sinaAgg(): # fetch price of London f = urllib2.urlopen('http://hq.sinajs.cn/?_=1386077085140/&list=hf_XAG', timeout=20) html = f.read() html = html[19:len(html) - 3] xagArr = re.split(',', html) price = {} price['dt'] = datetime.datetime.strptime(xagArr[12] + ' ' + xagArr[6], '%Y-%m-%d %H:%M:%S') xag = float(xagArr[0]) xag0 = float(xagArr[7]) log.debug('XAG: ' + xagArr[0] + ', XAG0: ' + xagArr[2]) # fetch USD price fusd = urllib2.urlopen( 'http://hq.sinajs.cn/rn=13860770561347070422433316708&list=USDCNY', timeout=20) htmlusd = fusd.read() htmlusd = htmlusd[19:len(htmlusd) - 3] usdArr = re.split(',', htmlusd) usd = float(usdArr[1]) log.debug('USD: ' + usdArr[0]) # calculate price in RMB price['p'] = round(usd * xag / 31.1035, 3) price['p0'] = round(usd * xag0 / 31.1035, 3) price['per'] = float(xagArr[1]) log.info('sina agg: ' + str(price['dt']) + ', ' + str(price['p']) + ', ' + str(price['p0']) + ', ' + str(price['per'])) return price
def importToArray(table): log.debug('loading ' + table + ' ...') prices = [] prec = 0 with open(os.path.join(path, '../trader_data/' + table + '.csv'), 'rb') as csvfile: rdr = csv.reader(csvfile) for row in rdr: p = {} p['open'] = float(row[2]) p['high'] = float(row[3]) p['low'] = float(row[4]) p['close'] = float(row[5]) p['vol'] = float(row[6]) p['rmb'] = round(p['close'] * 6.1 * 1000 / 31.1035, 2) p['dt'] = datetime.datetime.strptime(row[0] + ' ' + row[1], '%Y.%m.%d %H:%M') #2009.06.01,00:00 p['dtlong'] = time.mktime(p['dt'].timetuple()) p['date'] = p['dt'].strftime('%Y-%m-%d') p['time'] = p['dt'].strftime('%H:%M:%S') p['chan'] = p['close'] - prec if prec == 0: p['per'] = 0 else: p['per'] = round((p['close'] - prec) * 100 / prec, 3) prec = p['close'] prices.append(p) return prices
def runStrategy(in_prices): global prices, ps, phs, pls, rsis log.debug('beginning s5 strategy ...') prices = in_prices ps = [p['close'] for p in prices] phs = [p['high'] for p in prices] pls = [p['low'] for p in prices] rsis = rsi.calc_rsi(prices, 14) pool = StrategyPool(50) doTrade(pool, 1, 180, 12, 0.5, -0.6) pool.showStrategies() return direction = 1 starttime = time.time() for i in range(30, 150)[::10]: for j in range(2, 30)[::5]: if i < j: continue elapsed = long(time.time() - starttime) log.debug('== ' + str(elapsed) + ', ' + str(i) + ',' + str(j) + ' ==') for kp in [0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3]: for kl in [0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3]: doTrade(pool, direction, i, j, kp, -kl) pool.showStrategies() return
def runStrategy(prices, front): #prices = SqliteDB().getAllPrices(table) ps = [p['close'] for p in prices] pool = StrategyPool(100) doMaTrade(pool, prices, ps, front, 'MA', 6, 9, 35) pool.showStrategies() return for i in range(2, 9): for j in range(4, 20): if i >= j: continue doMaTrade(pool, prices, ps, front, 'MA', i, j) doMaTrade(pool, prices, ps, front, 'EMA', i, j) doMaTrade(pool, prices, ps, front, 'SMA', i, j) log.debug(' ========= ' + str(i) + ',' + str(j) + ' ===========') for k in range(6, 40): if j >= k: continue doMaTrade(pool, prices, ps, front, 'MA', i, j, k) doMaTrade(pool, prices, ps, front, 'EMA', i, j, k) doMaTrade(pool, prices, ps, front, 'SMA', i, j, k) continue for l in range(8, 60): if k >= l: continue doMaTrade(pool, prices, ps, front, 'MA', i, j, k, l) doMaTrade(pool, prices, ps, front, 'EMA', i, j, k, l) doMaTrade(pool, prices, ps, front, 'SMA', i, j, k, l) pool.showStrategies()
def addNotice(self, data): cur = self.conn.cursor() log.debug('inserting notice: ' + str(data[0]) + ',' + str(data[1]) + ',' + str(data[4]) + ',' + str(data[6])) cur.execute('INSERT INTO NOTICE(DTYPE,DSUBTYPE,DTLONG,DDATE,DTIME,DVALUE,DPERCENT,DTEXT,NOTES) VALUES(?,?,?,?,?,?,?,?,?)', data) self.conn.commit() cur.close() return
def runStrategy(in_prices): global prices, ps log.debug('beginning fma strategy ...') prices = in_prices ps = [p['close'] for p in prices] #12_0.15_SMA_31_EMA_56_SMA_160__0__0,93,93,1558,25166.84 #12_0.15_SMA_25_LWMA_48_SMA_160__0__0,105,97,1987,25156.73 #12_0.15_SMA_30_EMA_58_SMA_160__0__0,96,95,1558,24957.8 #36_0.15_SMA_31_EMA_56_SMA_160__0__0,92,87,1935,23762.4 #24_0.2_SMA_37_LWMA_64_SMA_140__0__0,92,86,1452,24911.19 #12_0.15__0__0_SMA_35_SMA_78_SMA_120,75,69,4941,24376.28 #12_0.15__0__0_MA_30_SMA_78_SMA_100,93,83,4376,24252.22 #12_0.15__0__0_SMA_35_SMA_72_SMA_120,77,71,4930,24391.03 #12_0.15__0__0_SMA_39_SMA_72_SMA_120,77,70,4946,24365.99 #36_0.15__0__0_EMA_17_LWMA_24_SMA_150,276,282,3205,24670.78 #24_0.2__0__0_SMA_9_MA_16_SMA_170,216,219,3667,24692.56 pool = Pool(10) doTrade(pool, 12, 0.15, 'SMA', 25, 'LWMA', 48, 'SMA', 160, 'SMA', 35, 'SMA', 78, 'SMA', 120) doTrade(pool, 12, 0.15, 'SMA', 25, 'LWMA', 48, 'SMA', 160, 'MA', 30, 'SMA', 78, 'SMA', 100) doTrade(pool, 12, 0.15, 'SMA', 31, 'EMA', 56, 'SMA', 160, 'SMA', 35, 'SMA', 72, 'SMA', 120) doTrade(pool, 12, 0.15, 'SMA', 31, 'EMA', 56, 'SMA', 160, 'MA', 30, 'SMA', 78, 'SMA', 100) doTrade(pool, 36, 0.15, 'SMA', 31, 'EMA', 56, 'SMA', 160, 'EMA', 17, 'LWMA', 24, 'SMA', 150) doTrade(pool, 24, 0.2, 'SMA', 37, 'LWMA', 64, 'SMA', 140, 'SMA', 9, 'MA', 16, 'SMA', 170) pool.showStrategies() return
def tally(ptype, price): db = SqliteDB() ret = '' dLong = time.mktime(price['dt'].timetuple()) dDate = price['dt'].strftime('%Y-%m-%d') dTime = price['dt'].strftime('%H:%M:%S') db.addPrice((ptype, dLong, dDate, dTime, price['p'], price['per'], price['p0'], '', dLong, dDate, dTime)) # calculate the percentage percent0 = price['per'] # get the price of 3 minutes ago price3 = db.getPrice(ptype, dLong - 180) percent3 = 0 if price3: log.debug(ptype + ',price3,' + str(price3[3]) + ',' + str(price3[0])) price3 = price3[0] percent3 = round((price['p'] - price3) * 100 / price3, 3) # get the price of 30 minutes ago price30 = db.getPrice(ptype, dLong - 1800) percent30 = 0 if price30: log.debug(ptype + ',price30,' + str(price30[3]) + ',' + str(price30[0])) price30 = price30[0] percent30 = round((price['p'] - price30) * 100 / price30, 3) # get last message information notper0 = db.getNotice(ptype, 0, dDate) log.info(ptype + ', percentage 0: ' + str(percent0) + ', last notice: ' + str(notper0)) #print notper0 if abs(percent0 - notper0) >= 1: ret = ptype + '0,' + str(price['p']) + ',' + str(percent0) + '%;\n' db.addNotice( (ptype, 0, dLong, dDate, dTime, price['p'], percent0, ret, '')) notcount30 = db.getNoticeCount(ptype, 30, dLong - 1800) log.info(ptype + ', percentage 30: ' + str(percent30) + ', notice in 30 minutes: ' + str(notcount30)) if notcount30 == 0 and abs(percent30) >= 1: ret = ret + ptype + '30,' + str( price['p']) + ',' + str(percent30) + '%;\n' db.addNotice( (ptype, 30, dLong, dDate, dTime, price['p'], percent30, ret, '')) notcount3 = db.getNoticeCount(ptype, 3, dLong - 180) log.info(ptype + ', percentage 3: ' + str(percent3) + ', notice in 3 minutes: ' + str(notcount3)) if notcount3 == 0 and abs(percent3) >= 0.5: ret = ret + ptype + '3,' + str( price['p']) + ',' + str(percent3) + '%;\n' db.addNotice( (ptype, 3, dLong, dDate, dTime, price['p'], percent3, ret, '')) return ret
def process(func): thread = threading.Thread(target=func) thread.start() thread.join(120) if thread.is_alive(): log.info('* hanging thread * ') else: log.debug('* thread ended normally * ')
def addPrice(self, data): cur = self.conn.cursor() cur.execute('SELECT DTLONG FROM FEDATA WHERE DTYPE=? AND DTLONG=?', (data[0], long(data[1]),)) if cur.fetchone() == None: log.debug('inserting price: ' + data[0] + ' ' + str(data[1]) + ' ' + data[3] + ' ' + str(data[4])) cur.execute('INSERT INTO FEDATA(DTYPE,DTLONG,DDATE,DTIME,DVALUE,DPER,DOPEN,NOTES,FETCHDT,FETCHDATE,FETCHTIME) VALUES(?,?,?,?,?,?,?,?,?,?,?)', data) self.conn.commit() cur.close() return
def testCo(co): xagPrices = dataloader.importToArray('XAGUSD5_201307') xags = [p['close'] for p in xagPrices] usdxPrices = dataloader.importToArray('_USDX5_201307') usdxs = [p['close'] for p in usdxPrices] us500Prices = dataloader.importToArray('_US5005_201307') us500s = [p['close'] for p in us500Prices] us30Prices = dataloader.importToArray('_US305_201307') us30s = [p['close'] for p in us30Prices] nq100Prices = dataloader.importToArray('_NQ1005_201307') nq100s = [p['close'] for p in nq100Prices] l = len(xagPrices) xs = [] ys = [] yps = [] typs = [] #for i in range(10, l - 1): for i in range(100, 200): xag = xagPrices[i] xagd = xags[i-10+1 : i+1] dtlong = xag['dtlong'] usdxd = findData(dtlong, usdxPrices, usdxs) us500d = findData(dtlong, us500Prices, us500s) us30d = findData(dtlong, us30Prices, us30s) nq100d = findData(dtlong, nq100Prices, nq100s) if not (usdxd and us500d and us30d and nq100d): log.debug('Insufficient Data. ' + xag['date'] + ' ' + xag['time']) continue xs.append([xags[i], slope(xagd), std(xagd), slope(usdxd), std(usdxd), slope(us500d), std(us500d), slope(us30d), std(us30d), slope(nq100d), std(nq100d)]) typs.append(xags[i]) ys.append(xags[i+1]) for i in range(len(xs)): yp = co[0] + xs[i][0] * co[1] yp += xs[i][1] * co[2] + xs[i][2] * co[3] + xs[i][3] * co[4] yp += xs[i][4] * co[5] + xs[i][5] * co[6] + xs[i][6] * co[7] + xs[i][7] * co[8] yp += xs[i][8] * co[9] + xs[i][9] * co[10] + xs[i][10] * co[11] yps.append(typs[i] + yp) print co ts = range(len(xs)) plt.plot(ts, ys, 'o', label='Original data', linestyle='-', markersize=2) plt.plot(ts, yps, 'ro', label='Fitted line', linestyle='-', markersize=2) plt.legend() plt.show()
def tally(ptype, price): db = SqliteDB() ret = '' dLong = time.mktime(price['dt'].timetuple()) dDate = price['dt'].strftime('%Y-%m-%d') dTime = price['dt'].strftime('%H:%M:%S') db.addPrice((ptype, dLong, dDate, dTime, price['p'], price['per'], price['p0'], '', dLong, dDate, dTime)) # calculate the percentage percent0 = price['per'] # get the price of 3 minutes ago price3 = db.getPrice(ptype, dLong - 180) percent3 = 0 if price3: log.debug(ptype + ',price3,' + str(price3[3]) + ',' + str(price3[0])) price3 = price3[0] percent3 = round((price['p'] - price3) * 100 / price3, 3) # get the price of 30 minutes ago price30 = db.getPrice(ptype, dLong - 1800) percent30 = 0 if price30: log.debug(ptype + ',price30,' + str(price30[3]) + ',' + str(price30[0])) price30 = price30[0] percent30 = round((price['p'] - price30) * 100 / price30, 3) # get last message information notper0 = db.getNotice(ptype, 0, dDate) log.info(ptype + ', percentage 0: ' + str(percent0) + ', last notice: ' + str(notper0)) #print notper0 if abs(percent0 - notper0) >= 1: ret = ptype + '0,' + str(price['p']) + ',' + str(percent0) + '%;\n' db.addNotice((ptype, 0, dLong, dDate, dTime, price['p'], percent0, ret, '')) notcount30 = db.getNoticeCount(ptype, 30, dLong - 1800) log.info(ptype + ', percentage 30: ' + str(percent30) + ', notice in 30 minutes: ' + str(notcount30)) if notcount30 == 0 and abs(percent30) >= 1: ret = ret + ptype + '30,' + str(price['p']) + ',' + str(percent30) + '%;\n' db.addNotice((ptype, 30, dLong, dDate, dTime, price['p'], percent30, ret, '')) notcount3 = db.getNoticeCount(ptype, 3, dLong - 180) log.info(ptype + ', percentage 3: ' + str(percent3) + ', notice in 3 minutes: ' + str(notcount3)) if notcount3 == 0 and abs(percent3) >= 0.5: ret = ret + ptype + '3,' + str(price['p']) + ',' + str(percent3) + '%;\n' db.addNotice((ptype, 3, dLong, dDate, dTime, price['p'], percent3, ret, '')) return ret
def runStrategy(prices): log.debug('beginning l4 strategy ...') ps = [p['close'] for p in prices] pool = StrategyPool(50) #doTrade(pool, prices, ps, 3, 9) #pool.showStrategies() #return for i in range(5, 40)[::2]: for j in range(3, 30)[::2]: doTrade(pool, prices, ps, i, j) pool.showStrategies()
def runStrategy(prices): log.debug('beginning l3 strategy ...') ps = [p['close'] for p in prices] pool = StrategyPool(50) #doTrade(pool, prices, ps, 3, 9) #pool.showStrategies() #return for i in range(5, 40)[::2]: for j in range(3, 30)[::2]: doTrade(pool, prices, ps, i, j) pool.showStrategies()
def runStrategy(in_prices): global prices, ps log.debug("beginning fma strategy ...") prices = in_prices ps = [p["close"] for p in prices] # 20_1.0_LWMA_10_EMA_24_EMA_25__0__0,20,23,533,36486.0 # 20_1.0__0__0_MA_6_MA_36_MA_37,18,18,354,30755.0 pool = Pool(10) doTrade(pool, 20, 1.0, "LWMA", 10, "EMA", 24, "EMA", 25, "MA", 6, "MA", 36, "MA", 37) # doTrade(pool, 25, 1.3, 'LWMA', 10, 'EMA', 24, 'EMA', 25, 'MA', 6, 'MA', 36, 'MA', 37) doTrade(pool, 25, 1.3, "MA", 7, "SMA", 13, "EMA", 31, "SMA", 7, "MA", 12, "MA", 13) pool.showStrategies() return
def runVoter(prices): log.debug('beginning rsi voter ...') starttime = time.time() pool = VoterPool(5, prices) #calcTickets(pool, 12, 26, 9) #calcTickets(pool, 'SMA', 3, 'EMA', 4) #calcTickets(pool, 'MA', 7, 'SMA', 13) #pool.showVoters() #return for i in range(5, 50): calcTickets(pool, prices, i) pool.showVoters()
def runStrategy(in_prices): global mas, emas, smas, lwmas, std, prices log.debug('beginning ma strategy ...') prices = in_prices ps = [p['close'] for p in prices] std = [0] * 51 l = len(prices) for period in range(2, 51): std[period] = [0] * l for i in range(period - 1, l): std[period][i] = np.std(ps[i-period+1 : i+1], dtype=np.float64, ddof=0) mas = [0] * 81 emas = [0] * 81 smas = [0] * 81 lwmas = [0] * 81 for period in range(2, 81): mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) lwmas[period] = ma.calc_lwma(ps, period) pool = Pool(100) #t = doTrade(pool, 25, 1.0, 'MA', 7, 'SMA', 12, 'EMA', 31, 'SMA', 7, 'MA', 12, 'MA', 13) #t = doTrade(pool, 25, 1.3, 'MA', 7, 'SMA', 13, 'EMA', 31, 'SMA', 7, 'MA', 12, 'MA', 13) #pool.showStrategies() #return log.debug('running ma strategy ...') starttime = datetime.datetime.now() matypes = ['MA', 'EMA', 'SMA', 'LWMA'] farr = range(5, 20) s1arr = range(8, 40) s2arr = range(0, 80) poola = Pool(10) poolb = Pool(10) for stdPeriod in [20, ]: for stdGuage in [1.0, ]: log.debug('*** ' + str(stdPeriod) + ',' + str(stdGuage) + ' ***') for ft, f in [(matype, period) for matype in matypes for period in farr]: for s1t, s1 in [(matype, period) for matype in matypes for period in s1arr]: if s1 != 0 and s1 <= f: continue elapsed = (datetime.datetime.now() - starttime).seconds log.debug('== ' + str(elapsed) + ',' + ft + '_' + str(f) + ',' + s1t + '_' + str(s1) + ' ==') for s2t, s2 in [(matype, period) for matype in matypes for period in s2arr]: if s2 != 0 and s2 <= s1: continue if s2 == 0 and (s2t == 'EMA' or s2t == 'SMA' or s2t == 'LWMA'): continue doTrade(poola, stdPeriod, stdGuage, ft, f, s1t, s1, s2t, s2, '', 0, '', 0, '', 0) doTrade(poolb, stdPeriod, stdGuage, '', 0, '', 0, '', 0, ft, f, s1t, s1, s2t, s2) poola.showStrategies() poolb.showStrategies()
def runStrategy(in_prices): global prices, ps log.debug('beginning fma strategy ...') prices = in_prices ps = [p['close'] for p in prices] #20_1.0_LWMA_10_EMA_24_EMA_25__0__0,20,23,533,36486.0 #20_1.0__0__0_MA_6_MA_36_MA_37,18,18,354,30755.0 pool = Pool(10) doTrade(pool, 20, 1.0, 'LWMA', 10, 'EMA', 24, 'EMA', 25, 'MA', 6, 'MA', 36, 'MA', 37) #doTrade(pool, 25, 1.3, 'LWMA', 10, 'EMA', 24, 'EMA', 25, 'MA', 6, 'MA', 36, 'MA', 37) doTrade(pool, 25, 1.3, 'MA', 7, 'SMA', 13, 'EMA', 31, 'SMA', 7, 'MA', 12, 'MA', 13) pool.showStrategies() return
def runStrategy(prices): log.debug('beginning l2 strategy ...') ps = [p['close'] for p in prices] pool = StrategyPool(50) #doTrade(pool, prices, ps, 14, 21, 14) #pool.showStrategies() #return for i in range(5, 20)[::2]: for j in range(12, 50)[::2]: if i >= j: continue for k in range(10, 40)[::3]: for l in [20, 30, 40, 50, 60, 70]: doTrade(pool, prices, ps, i, j, k, l) #doMacdTrade(pool, prices, ps, i, j, k) pool.showStrategies()
def runStrategy(prices): logs.info('STRATEGY,BUY TIMES, SELL TIMES, FINAL EQUITY') #prices = SqliteDB().getAllPrices(table) ps = [p['close'] for p in prices] pool = StrategyPool(100) #doBollingTrade(pool, prices, ps, 12, 2.4) #pool.showStrategies() #return for i in range(2, 40): j = 0 log.debug(i) while j <= 5: doBollingTrade(pool, prices, ps, i, j) j += 0.1 pool.showStrategies()
def runStrategy(in_prices): log.debug("beginning s3 strategy ...") prices = in_prices ps = [p["close"] for p in prices] pool = StrategyPool(50) doTrade(pool, prices, ps, 90, 17, 45) pool.showStrategies() return for i in range(10, 100)[::10]: for j in range(2, 30)[::5]: log.debug("== " + str(i) + " , " + str(j) + " ==") for k in range(5, 100)[::20]: doTrade(pool, prices, ps, i, j, k) pool.showStrategies() return
def runStrategy(in_prices): log.debug('beginning s3 strategy ...') prices = in_prices ps = [p['close'] for p in prices] pool = StrategyPool(50) doTrade(pool, prices, ps, 90, 17, 45) pool.showStrategies() return for i in range(10, 100)[::10]: for j in range(2, 30)[::5]: log.debug('== ' + str(i) + ' , ' + str(j) + ' ==') for k in range(5, 100)[::20]: doTrade(pool, prices, ps, i, j, k) pool.showStrategies() return
def runVoter(in_prices): global mas, emas, smas, lwmas, prices log.debug('beginning ma voter ...') prices = in_prices ps = [p['close'] for p in prices] mas = [0] * 61 emas = [0] * 61 smas = [0] * 61 lwmas = [0] * 61 for period in range(2, 61): mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) lwmas[period] = ma.calc_lwma(ps, period) log.debug('running ma voter ...') starttime = time.time() matypes = ['MA', 'EMA', 'SMA', 'LWMA'] pool = VoterPool(2, prices) #calcTickets(pool, 'MA', 7, 'EMA', 18) #calcTickets(pool, 'SMA', 3, 'EMA', 4) #calcTickets(pool, 'MA', 7, 'SMA', 13) #pool.showVoters() #return farr = range(2, 10) sarr = range(4, 60) for ft, f in [(matype, period) for matype in matypes for period in farr]: elapsed = long(time.time() - starttime) #log.debug('== ' + str(elapsed) + ',' + ft + '_' + str(f) + ' ==') for st, s in [(matype, period) for matype in matypes for period in sarr]: if s < f: continue calcTickets(pool, ft, f, st, s) pool.showVoters()
def runStrategy(prices): log.debug('beginning l5 strategy ...') ps = [p['close'] for p in prices] ys = ps[55:110] l = len(ys) high1 = high2 = low1 = low2 = 0 highsm = lowsm = float('inf') for x in range(1, l): ty, sm = genLine(high1, x, ys, 1) if sm < highsm: high2 = x highsm, highy = sm, ty if high2 != x and high1 != high2: ty, sm = genLine(high2, x, ys, 1) if sm < highsm: high1, high2 = high2, x highsm, highy = sm, ty ty, sm = genLine(low1, x, ys, -1) if sm < lowsm: low2 = x lowsm, lowy = sm, ty if low2 != x and low1 != low2: ty, sm = genLine(low2, x, ys, -1) if sm < lowsm: low1, low2 = low2, x lowsm, lowy = sm, ty #return highy, lowy xs = range(l) upys = map(highy, xs) lowys = map(lowy, xs) plt.plot(xs, ys, '-', xs, upys, '-', xs[:50], lowys[:50], '-') plt.show() return
def runStrategy(in_prices): log.debug('beginning one strategy ...') prices = in_prices ps = [p['close'] for p in prices] slopePeriod = 50 l = len(prices) slopes = [0] * l stds = [0] * l for i in range(slopePeriod, l): slopes[i] = calc_slope(ps[i - slopePeriod + 1:i + 1]) stds[i] = round( np.std(ps[i - slopePeriod + 1:i + 1], dtype=np.float64, ddof=0), 3) found = 0 for i in range(1055, l): curSlope = slopes[i] curStd = stds[i] minDiffSlope = minDiffStd = 999 jslope = jstd = 0 for j in range(slopePeriod, i - 20): diffSlope = abs(slopes[j] - curSlope) diffStd = abs(stds[j] - curStd) if diffSlope <= 0.001 and diffStd <= 0.005: minDiffSlope, jslope = diffSlope, j minDiffStd, jstd = diffStd, j found += 1 break #log.debug('i :' + str(i) + ',' + str(curSlope) + ',' + str(curStd) + ', min diff slope,' + str(jslope) + ':' + str(minDiffSlope) + ', min diff std,' + str(jstd) + ':' + str(minDiffStd)) log.debug('i :' + str(prices[i]['dt']) + ', j :' + str(prices[jslope]['dt'])) log.debug('total:' + str(l - slopePeriod) + ',found:' + str(found))
def runStrategy(in_prices): log.debug("beginning one strategy ...") prices = in_prices ps = [p["close"] for p in prices] slopePeriod = 50 l = len(prices) slopes = [0] * l stds = [0] * l for i in range(slopePeriod, l): slopes[i] = calc_slope(ps[i - slopePeriod + 1 : i + 1]) stds[i] = round(np.std(ps[i - slopePeriod + 1 : i + 1], dtype=np.float64, ddof=0), 3) found = 0 for i in range(1055, l): curSlope = slopes[i] curStd = stds[i] minDiffSlope = minDiffStd = 999 jslope = jstd = 0 for j in range(slopePeriod, i - 20): diffSlope = abs(slopes[j] - curSlope) diffStd = abs(stds[j] - curStd) if diffSlope <= 0.001 and diffStd <= 0.005: minDiffSlope, jslope = diffSlope, j minDiffStd, jstd = diffStd, j found += 1 break # log.debug('i :' + str(i) + ',' + str(curSlope) + ',' + str(curStd) + ', min diff slope,' + str(jslope) + ':' + str(minDiffSlope) + ', min diff std,' + str(jstd) + ':' + str(minDiffStd)) log.debug("i :" + str(prices[i]["dt"]) + ", j :" + str(prices[jslope]["dt"])) log.debug("total:" + str(l - slopePeriod) + ",found:" + str(found))
def runStrategy_2(in_prices): global mas, emas, smas, std, prices log.debug('beginning first strategy ...') prices = in_prices ps = [p['close'] for p in prices] std = [0] * 51 l = len(prices) for period in range(2, 51): std[period] = [0] * l for i in range(period - 1, l): std[period][i] = round( np.std(ps[i - period + 1:i + 1], dtype=np.float64, ddof=0), 3) mas = [0] * 61 emas = [0] * 61 smas = [0] * 61 for period in range(2, 61): mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) log.debug('running first strategy ...') starttime = datetime.datetime.now() strat_as = [ ['MA', 7, 'SMA', 10, 'SMA', 12], ['MA', 7, 'SMA', 14, 'EMA', 33], ['MA', 7, 'SMA', 16, 'EMA', 27], ] strat_bs = [ ['SMA', 7, 'MA', 12, 'MA', 12], ['SMA', 7, 'MA', 12, 'MA', 36], ['MA', 7, 'SMA', 14, 'EMA', 33], ] pool = StrategyPool(100) for stdPeriod in [25]: stdGuage = 1.3 while stdGuage <= 1.3: elapsed = (datetime.datetime.now() - starttime).seconds log.debug('== ' + str(elapsed) + ',' + str(stdPeriod) + ',' + str(stdGuage) + ' ==') for sa in strat_as: for sb in strat_bs: doTrade(pool, stdPeriod, stdGuage, sa[0], sa[1], sa[2], sa[3], sa[4], sa[5], sb[0], sb[1], sb[2], sb[3], sb[4], sb[5]) stdGuage += 0.02 pool.showStrategies() return
def runStrategy_2(in_prices): global mas, emas, smas, std, prices log.debug('beginning first strategy ...') prices = in_prices ps = [p['close'] for p in prices] std = [0] * 51 l = len(prices) for period in range(2, 51): std[period] = [0] * l for i in range(period - 1, l): std[period][i] = round(np.std(ps[i-period+1 : i+1], dtype=np.float64, ddof=0), 3) mas = [0] * 61 emas = [0] * 61 smas = [0] * 61 for period in range(2, 61): mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) log.debug('running first strategy ...') starttime = datetime.datetime.now() strat_as = [ ['MA',7,'SMA',10,'SMA',12], ['MA',7,'SMA',14,'EMA',33], ['MA',7,'SMA',16,'EMA',27], ] strat_bs = [ ['SMA',7,'MA',12,'MA',12 ], ['SMA',7,'MA',12,'MA',36 ], ['MA',7,'SMA',14,'EMA',33], ] pool = StrategyPool(100) for stdPeriod in [25]: stdGuage = 1.3 while stdGuage <= 1.3: elapsed = (datetime.datetime.now() - starttime).seconds log.debug('== ' + str(elapsed) + ',' + str(stdPeriod) + ',' + str(stdGuage) + ' ==') for sa in strat_as: for sb in strat_bs: doTrade(pool, stdPeriod, stdGuage, sa[0], sa[1], sa[2], sa[3], sa[4], sa[5], sb[0], sb[1], sb[2], sb[3], sb[4], sb[5]) stdGuage += 0.02 pool.showStrategies() return
def runStrategy(in_prices): global mas, emas, smas, lwmas, prices log.debug('beginning ma strategy ...') prices = in_prices ps = [p['close'] for p in prices] log.debug('generating mas ...') mas = [0] * 61 emas = [0] * 61 smas = [0] * 61 lwmas = [0] * 61 for period in range(2, 61): mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) lwmas[period] = ma.calc_lwma(ps, period) pool = StrategyPool(20) doMaTrade(pool, 'SMA', 19, 'MA', 40, 'LWMA', 60) pool.showStrategies() return log.debug('running ma strategy ...') starttime = datetime.datetime.now() matypes = ['MA', 'EMA', 'SMA', 'LWMA'] pool = StrategyPool(100) for ft, f in [(matype, period) for matype in matypes for period in range(2, 10)]: for s1t, s1 in [(matype, period) for matype in matypes for period in range(4, 21)]: elapsed = (datetime.datetime.now() - starttime).seconds log.debug('== ' + str(elapsed) + ',' + ft + '_' + str(f) + ',' + s1t + '_' + str(s1) + ' ==') for s2t, s2 in [(matype, period) for matype in matypes for period in range(0, 41)]: if s2 != 0 and s2 <= s1: continue if s2 == 0 and (s2t == 'EMA' or s2t == 'SMA' or s2t == 'LWMA'): continue doMaTrade(pool, ft, f, s1t, s1, s2t, s2) pool.showStrategies()
def runVoter(in_prices): global mas, emas, smas, lwmas, prices log.debug('beginning ma voter ...') prices = in_prices ps = [p['close'] for p in prices] malength = 101 mas = [0] * malength emas = [0] * malength smas = [0] * malength lwmas = [0] * malength for period in range(2, malength): if period % 30 == 0: print period mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) lwmas[period] = ma.calc_lwma(ps, period) log.debug('running ma voter ...') starttime = time.time() matypes = ['MA', 'EMA', 'SMA', 'LWMA'] pool = VoterPool(1, prices) #calcTickets(pool, 'SMA', 95, 'LWMA', 240) #calcTickets(pool, 'SMA', 3, 'EMA', 4) #calcTickets(pool, 'MA', 7, 'SMA', 13) #pool.showVoters() #return farr = range(5, 30)[::3] sarr = range(10, 100)[::5] for ft, f in [(matype, period) for matype in matypes for period in farr]: elapsed = long(time.time() - starttime) log.debug('== ' + str(elapsed) + ',' + ft + '_' + str(f) + ' ==') for st, s in [(matype, period) for matype in matypes for period in sarr]: if s < f: continue calcTickets(pool, ft, f, st, s) pool.showVoters()
def runVoter(prices): log.debug('beginning macd voter ...') log.debug('running ma voter ...') starttime = time.time() pool = VoterPool(5, prices) #calcTickets(pool, 12, 26, 9) #calcTickets(pool, 'SMA', 3, 'EMA', 4) #calcTickets(pool, 'MA', 7, 'SMA', 13) #pool.showVoters() #return for i in range(2, 30): for j in range(5, 60): if i > j: continue elapsed = long(time.time() - starttime) log.debug('== ' + str(elapsed) + ',' + str(i) + '_' + str(j) + ' ==') for k in range(2, 30): calcTickets(pool, prices, i, j, k) pool.showVoters()
def runStrategy_0(in_prices): global mas, emas, smas, std, prices log.debug('beginning first strategy ...') prices = in_prices ps = [p['close'] for p in prices] std = [0] * 51 l = len(prices) for period in range(2, 51): std[period] = [0] * l for i in range(period - 1, l): std[period][i] = round( np.std(ps[i - period + 1:i + 1], dtype=np.float64, ddof=0), 3) mas = [0] * 61 emas = [0] * 61 smas = [0] * 61 for period in range(2, 61): mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) log.debug('running first strategy ...') starttime = datetime.datetime.now() matypes = ['MA', 'EMA', 'SMA'] farr = [ 2, 3, 4, 5, 6, 7, ] s1arr = [ 4, 6, 8, 10, 12, 14, 16, 18, 20, ] s2arr = [ 0, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, ] pool = StrategyPool(100) for stdPeriod in [20, 30, 40]: stdGuage = 1.0 while stdGuage <= 1.3: maxAEquity = maxBEquity = 0 poola = StrategyPool(5) poolb = StrategyPool(5) for ft, f in [(matype, period) for matype in matypes for period in farr]: for s1t, s1 in [(matype, period) for matype in matypes for period in s1arr]: elapsed = (datetime.datetime.now() - starttime).seconds log.debug('== ' + str(elapsed) + ',' + ft + '_' + str(f) + ',' + s1t + '_' + str(s1) + ' ==') for s2t, s2 in [(matype, period) for matype in matypes for period in s2arr]: if s2 != 0 and s2 < s1: continue if s2 == 0 and (s2t == 'EMA' or s2t == 'SMA'): continue t = doTrade(poola, stdPeriod, stdGuage, ft, f, s1t, s1, s2t, s2, '', 0, '', 0, '', 0) if t.equity > maxAEquity: maxAEquity = t.equity maxEAs = [ft, f, s1t, s1, s2t, s2] elapsed = (datetime.datetime.now() - starttime).seconds log.info('find A time: ' + str(elapsed) + ' ') poola.showStrategies() for ft, f in [(matype, period) for matype in matypes for period in farr]: for s1t, s1 in [(matype, period) for matype in matypes for period in s1arr]: elapsed = (datetime.datetime.now() - starttime).seconds log.debug('== ' + str(elapsed) + ',' + ft + '_' + str(f) + ',' + s1t + '_' + str(s1) + ' ==') for s2t, s2 in [(matype, period) for matype in matypes for period in s2arr]: if s2 != 0 and s2 < s1: continue if s2 == 0 and (s2t == 'EMA' or s2t == 'SMA'): continue t = doTrade(poolb, stdPeriod, stdGuage, '', 0, '', 0, '', 0, ft, f, s1t, s1, s2t, s2) if t.equity > maxBEquity: maxBEquity = t.equity maxEBs = [ft, f, s1t, s1, s2t, s2] elapsed = (datetime.datetime.now() - starttime).seconds log.info('find B time: ' + str(elapsed) + ' ') poolb.showStrategies() logb.info( str(stdPeriod) + ',' + str(stdGuage) + ',' + str(maxAEquity) + ',' + str(maxBEquity)) logb.info(str(maxEAs)) logb.info(str(maxEBs)) for i in range(5): sa = poola.strategies[i] sb = poolb.strategies[i] t = doTrade(pool, stdPeriod, stdGuage, sa[0].args[2], sa[0].args[3], sa[0].args[4], sa[0].args[5], sa[0].args[6], sa[0].args[7], sb[0].args[8], sb[0].args[9], sb[0].args[10], sb[0].args[11], sb[0].args[12], sb[0].args[13]) t.generateGraph() pool.estimate(t) stdGuage += 0.1 pool.showStrategies()
def regression(): xagPrices = dataloader.importToArray('XAGUSD5_2013070809') xags = [p['close'] for p in xagPrices] usdxPrices = dataloader.importToArray('_USDX5_2013070809') usdxs = [p['close'] for p in usdxPrices] us500Prices = dataloader.importToArray('_US5005_2013070809') us500s = [p['close'] for p in us500Prices] us30Prices = dataloader.importToArray('_US305_2013070809') us30s = [p['close'] for p in us30Prices] nq100Prices = dataloader.importToArray('_NQ1005_2013070809') nq100s = [p['close'] for p in nq100Prices] l = len(xagPrices) xs = [] ys = [] for i in range(10, l - 1): xag = xagPrices[i] xagd = xags[i-10+1 : i+1] dtlong = xag['dtlong'] usdxd = findData(dtlong, usdxPrices, usdxs) us500d = findData(dtlong, us500Prices, us500s) us30d = findData(dtlong, us30Prices, us30s) nq100d = findData(dtlong, nq100Prices, nq100s) if not (usdxd and us500d and us30d and nq100d): log.debug('Insufficient Data. ' + xag['date'] + ' ' + xag['time']) continue xs.append([xags[i], slope(xagd), std(xagd), slope(usdxd), std(usdxd), slope(us500d), std(us500d), slope(us30d), std(us30d), slope(nq100d), std(nq100d)]) ys.append(xags[i+1] - xags[i]) #print xs #print ys xxs = np.array(xs) #print xsT yys = np.array(ys) mymodel = multipolyfit(xxs.T, yys, 20, model_out = False) #mymodel = ols.ols(yys, xxs, 'y',['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10', 'x11']) #print mymodel.b print mymodel #print mymodel.summary() return mymodel yps = [] co = mymodel.b for i in range(len(xs)): yp = co[0] + xs[i][0] * co[1] + xs[i][1] * co[2] + xs[i][2] * co[3] + xs[i][3] * co[4] yp += xs[i][4] * co[5] + xs[i][5] * co[6] + xs[i][6] * co[7] + xs[i][7] * co[8] yp += xs[i][8] * co[9] + xs[i][9] * co[10] + xs[i][10] * co[11] yps.append(yp) ts = range(len(xs)) plt.plot(ts, ys, 'o', label='Original data', linestyle='-', marker='') plt.plot(ts, yps, 'r', label='Fitted line') plt.legend() plt.show()
def runStrategy(in_prices): global mas, emas, smas, lwmas, std, prices log.debug('beginning one strategy ...') prices = in_prices ps = [p['close'] for p in prices] std = [0] * 51 l = len(prices) for period in range(5, 41): std[period] = [0] * l for i in range(period - 1, l): std[period][i] = round( np.std(ps[i - period + 1:i + 1], dtype=np.float64, ddof=0), 3) mas = [0] * 181 emas = [0] * 181 smas = [0] * 181 lwmas = [0] * 181 for period in range(2, 181): mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) lwmas[period] = ma.calc_lwma(ps, period) #pool = StrategyPool(100) #t = doTrade(pool, 20, 0.1, 0.2, 'SMA', 20, 'SMA', 34, 'LWMA', 40, 'SMA', 20, 'SMA', 34, 'LWMA', 120, 'MA', 20, 'SMA', 34, 'LWMA', 120) #pool.showStrategies() #return log.debug('running first strategy ...') starttime = time.time() matypes = ['MA', 'EMA', 'SMA', 'LWMA'] #farr = [2, 3, 4, 5, 6, 7, ] #s1arr = [4, 6, 8, 10, 12, 14, 16, 18, 20, ] #s2arr = [0, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, ] #farr = [20,] #s1arr = [40, ] #s2arr = [0, ] farr = range(40, 41)[::3] s1arr = range(4, 121)[::6] s2arr = range(0, 181)[::15] stdGuage1, stdGuage2 = 0.1, 0.2 pool = StrategyPool(50) poola = StrategyPool(10) poolb = StrategyPool(10) poolc = StrategyPool(10) for stdPeriod in [ 20, ]: for no in ['A', 'B', 'C']: for ft, f in [(matype, period) for matype in matypes for period in farr]: for s1t, s1 in [(matype, period) for matype in matypes for period in s1arr]: if s1 < f: continue elapsed = long(time.time() - starttime) log.debug('== ' + str(elapsed) + ',' + ft + '_' + str(f) + ',' + s1t + '_' + str(s1) + ' ==') for s2t, s2 in [(matype, period) for matype in matypes for period in s2arr]: if s2 != 0 and s2 <= s1: continue if s2 == 0 and (s2t == 'EMA' or s2t == 'SMA' or s2t == 'LWMA'): continue if no == 'A': doTrade(poola, stdPeriod, stdGuage1, stdGuage2, ft, f, s1t, s1, s2t, s2, '', 0, '', 0, '', 0, '', 0, '', 0, '', 0) elif no == 'B': doTrade(poolb, stdPeriod, stdGuage1, stdGuage2, '', 0, '', 0, '', 0, ft, f, s1t, s1, s2t, s2, '', 0, '', 0, '', 0) elif no == 'C': doTrade(poolc, stdPeriod, stdGuage1, stdGuage2, '', 0, '', 0, '', 0, '', 0, '', 0, '', 0, ft, f, s1t, s1, s2t, s2) elapsed = long(time.time() - starttime) log.info('find ' + no + ' time: ' + str(elapsed) + ' ') for i in range(10): sa = poola.strategies[i] sb = poolb.strategies[i] sc = poolc.strategies[i] t = doTrade(pool, stdPeriod, stdGuage1, stdGuage2, sa[0].args[0], sa[0].args[1], sa[0].args[2], sa[0].args[3], sa[0].args[4], sa[0].args[5], sb[0].args[6], sb[0].args[7], sb[0].args[8], sb[0].args[9], sb[0].args[10], sb[0].args[11], sc[0].args[12], sc[0].args[13], sc[0].args[14], sc[0].args[15], sc[0].args[16], sc[0].args[17]) #t.generateGraph() pool.showStrategies()
def runStrategy(in_prices): global mas, emas, smas, lwmas, std, prices log.debug('beginning ma strategy ...') prices = in_prices ps = [p['close'] for p in prices] std = [0] * 51 l = len(prices) for period in range(2, 51): std[period] = [0] * l for i in range(period - 1, l): std[period][i] = np.std(ps[i - period + 1:i + 1], dtype=np.float64, ddof=0) malength = 181 mas = [0] * malength emas = [0] * malength smas = [0] * malength lwmas = [0] * malength for period in range(2, malength): mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) lwmas[period] = ma.calc_lwma(ps, period) pool = Pool(10) t = doTrade(pool, 12, 0.15, 'SMA', 25, 'LWMA', 48, 'SMA', 160, 'SMA', 30, 'EMA', 58, 'SMA', 160) t = doTrade(pool, 12, 0.15, 'SMA', 25, 'LWMA', 48, 'SMA', 160, 'MA', 30, 'SMA', 68, 'SMA', 100) t = doTrade(pool, 12, 0.15, 'SMA', 25, 'EMA', 38, 'SMA', 160, 'MA', 30, 'SMA', 68, 'SMA', 100) t = doTrade(pool, 12, 0.1, 'SMA', 25, 'EMA', 38, 'SMA', 160, 'MA', 30, 'SMA', 68, 'SMA', 100) t = doTrade(pool, 12, 0.12, 'SMA', 25, 'EMA', 38, 'SMA', 160, 'MA', 30, 'SMA', 68, 'SMA', 100) t = doTrade(pool, 20, 0.15, 'SMA', 25, 'LWMA', 48, 'SMA', 160, 'MA', 30, 'SMA', 68, 'SMA', 100) t = doTrade(pool, 20, 0.1, 'SMA', 25, 'LWMA', 48, 'SMA', 160, 'MA', 30, 'SMA', 68, 'SMA', 100) t = doTrade(pool, 20, 0.12, 'SMA', 25, 'LWMA', 48, 'SMA', 160, 'MA', 30, 'SMA', 68, 'SMA', 100) t = doTrade(pool, 40, 0.15, 'SMA', 25, 'LWMA', 48, 'SMA', 160, 'MA', 30, 'SMA', 68, 'SMA', 100) t = doTrade(pool, 40, 0.1, 'SMA', 25, 'LWMA', 48, 'SMA', 160, 'MA', 30, 'SMA', 68, 'SMA', 100) t = doTrade(pool, 40, 0.12, 'SMA', 25, 'LWMA', 48, 'SMA', 160, 'MA', 30, 'SMA', 68, 'SMA', 100) #t = doTrade(pool, 25, 1.3, 'MA', 7, 'SMA', 13, 'EMA', 31, 'SMA', 7, 'MA', 12, 'MA', 13) pool.showStrategies() return log.debug('running ma strategy ...') starttime = datetime.datetime.now() matypes = ['MA', 'EMA', 'SMA', 'LWMA'] farr = range(5, 40) s1arr = range(8, 80) s2arr = range(0, 180) poola = Pool(10) poolb = Pool(10) for stdPeriod in [ 12, ]: for stdGuage in [ 0.15, ]: log.debug('*** ' + str(stdPeriod) + ',' + str(stdGuage) + ' ***') for ft, f in [(matype, period) for matype in matypes for period in farr]: for s1t, s1 in [(matype, period) for matype in matypes for period in s1arr]: if s1 != 0 and s1 <= f: continue elapsed = (datetime.datetime.now() - starttime).seconds log.debug('== ' + str(elapsed) + ',' + ft + '_' + str(f) + ',' + s1t + '_' + str(s1) + ' ==') for s2t, s2 in [(matype, period) for matype in matypes for period in s2arr]: if s2 != 0 and s2 <= s1: continue if s2 == 0 and (s2t == 'EMA' or s2t == 'SMA' or s2t == 'LWMA'): continue doTrade(poola, stdPeriod, stdGuage, ft, f, s1t, s1, s2t, s2, '', 0, '', 0, '', 0) doTrade(poolb, stdPeriod, stdGuage, '', 0, '', 0, '', 0, ft, f, s1t, s1, s2t, s2) poola.showStrategies() poolb.showStrategies()
def emptyTables(self): cur = self.conn.cursor() cur.execute('DELETE FROM XAGUSD1440') self.conn.commit() log.debug('Emptied')
def runStrategy(in_prices): global mas, emas, smas, lwmas, std, prices log.debug('beginning one strategy ...') prices = in_prices ps = [p['close'] for p in prices] std = [0] * 51 l = len(prices) for period in range(20, 21): std[period] = [0] * l for i in range(period - 1, l): std[period][i] = round(np.std(ps[i-period+1 : i+1], dtype=np.float64, ddof=0), 3) mas = [0] * 181 emas = [0] * 181 smas = [0] * 181 lwmas = [0] * 181 for period in range(2, 181): mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) lwmas[period] = ma.calc_lwma(ps, period) #pool = StrategyPool(100) #t = doTrade(pool, 20, 0.1, 0.2, 'SMA', 20, 'SMA', 34, 'LWMA', 40, 'SMA', 20, 'SMA', 34, 'LWMA', 120) #pool.showStrategies() #return log.debug('running first strategy ...') starttime = time.time() matypes = ['MA', 'EMA', 'SMA', 'LWMA'] #farr = [2, 3, 4, 5, 6, 7, ] #s1arr = [4, 6, 8, 10, 12, 14, 16, 18, 20, ] #s2arr = [0, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, ] #farr = [20,] #s1arr = [40, ] #s2arr = [0, ] farr = range(40, 41)[::3] s1arr = range(4, 121)[::6] s2arr = range(0, 181)[::15] stdGuage1, stdGuage2 = 0.1, 0.2 pool = StrategyPool(50) poola = StrategyPool(10) poolb = StrategyPool(10) for stdPeriod in [20, ]: for no in ['A', 'B', ]: for ft, f in [(matype, period) for matype in matypes for period in farr]: for s1t, s1 in [(matype, period) for matype in matypes for period in s1arr]: if s1 < f: continue elapsed = long(time.time() - starttime) log.debug('== ' + str(elapsed) + ',' + ft + '_' + str(f) + ',' + s1t + '_' + str(s1) + ' ==') for s2t, s2 in [(matype, period) for matype in matypes for period in s2arr]: if s2 != 0 and s2 <= s1: continue if s2 == 0 and (s2t == 'EMA' or s2t == 'SMA' or s2t == 'LWMA'): continue if no == 'A': doTrade(poola, stdPeriod, stdGuage1, stdGuage2, ft, f, s1t, s1, s2t, s2, '', 0, '', 0, '', 0) elif no == 'B': doTrade(poolb, stdPeriod, stdGuage1, stdGuage2, '', 0, '', 0, '', 0, ft, f, s1t, s1, s2t, s2) elapsed = long(time.time() - starttime) log.info('find ' + no + ' time: ' + str(elapsed) + ' ') for i in range(10): sa = poola.strategies[i] sb = poolb.strategies[i] t = doTrade(pool, stdPeriod, stdGuage1, stdGuage2, sa[0].args[0], sa[0].args[1], sa[0].args[2], sa[0].args[3], sa[0].args[4], sa[0].args[5], sb[0].args[6], sb[0].args[7], sb[0].args[8], sb[0].args[9], sb[0].args[10], sb[0].args[11]) #t.generateGraph() pool.showStrategies()
def runStrategy_1(in_prices): global mas, emas, smas, std, prices log.debug("beginning first strategy ...") prices = in_prices ps = [p["close"] for p in prices] std = [0] * 51 l = len(prices) for period in range(2, 51): std[period] = [0] * l for i in range(period - 1, l): std[period][i] = round(np.std(ps[i - period + 1 : i + 1], dtype=np.float64, ddof=0), 3) mas = [0] * 61 emas = [0] * 61 smas = [0] * 61 for period in range(2, 61): mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) log.debug("running first strategy ...") starttime = datetime.datetime.now() strat_as = [ ["MA", 6, "SMA", 14, "EMA", 39], ["MA", 7, "SMA", 10, "SMA", 12], ["MA", 7, "SMA", 12, "EMA", 18], ["MA", 7, "SMA", 12, "MA", 27], ["MA", 7, "SMA", 12, "SMA", 12], ["MA", 7, "SMA", 14, "EMA", 27], ["MA", 7, "SMA", 14, "EMA", 30], ["MA", 7, "SMA", 14, "EMA", 33], ["MA", 7, "SMA", 14, "EMA", 45], ["MA", 7, "SMA", 14, "MA", 27], ["MA", 7, "SMA", 14, "SMA", 15], ["MA", 7, "SMA", 14, "SMA", 30], ["MA", 7, "SMA", 16, "EMA", 24], ["MA", 7, "SMA", 16, "EMA", 27], ["MA", 7, "SMA", 16, "EMA", 30], ["MA", 7, "SMA", 16, "MA", 30], ] strat_bs = [ ["EMA", 3, "EMA", 16, "MA", 42], ["EMA", 3, "EMA", 16, "MA", 45], ["EMA", 6, "SMA", 6, "MA", 30], ["EMA", 7, "MA", 4, "EMA", 51], ["MA", 6, "SMA", 16, "EMA", 45], ["MA", 6, "SMA", 18, "MA", 36], ["MA", 6, "SMA", 20, "MA", 36], ["MA", 6, "SMA", 20, "MA", 39], ["MA", 7, "EMA", 18, "EMA", 45], ["MA", 7, "SMA", 12, "EMA", 42], ["MA", 7, "SMA", 12, "SMA", 21], ["MA", 7, "SMA", 14, "EMA", 42], ["MA", 7, "SMA", 14, "MA", 45], ["MA", 7, "SMA", 14, "SMA", 21], ["SMA", 2, "EMA", 16, "MA", 42], ["SMA", 4, "MA", 4, "EMA", 51], ["SMA", 5, "MA", 4, "MA", 15], ["SMA", 5, "MA", 6, "MA", 42], ["SMA", 6, "EMA", 10, "MA", 36], ["SMA", 6, "MA", 12, "MA", 12], ["SMA", 7, "MA", 12, "EMA", 18], ["SMA", 7, "MA", 12, "EMA", 27], ["SMA", 7, "MA", 12, "EMA", 36], ["SMA", 7, "MA", 12, "EMA", 45], ["SMA", 7, "MA", 12, "EMA", 48], ["SMA", 7, "MA", 12, "MA", 12], ["SMA", 7, "MA", 12, "MA", 18], ["SMA", 7, "MA", 12, "MA", 33], ["SMA", 7, "MA", 12, "MA", 36], ["SMA", 7, "MA", 12, "MA", 51], ["SMA", 7, "MA", 12, "SMA", 15], ] pool = StrategyPool(100) for stdPeriod in [5, 8, 10, 12, 15, 18, 19, 20, 21, 22, 25, 30, 32, 34, 38, 40]: stdGuage = 0.6 while stdGuage <= 2: elapsed = (datetime.datetime.now() - starttime).seconds log.debug("== " + str(elapsed) + "," + str(stdPeriod) + "," + str(stdGuage) + " ==") for sa in strat_as: for sb in strat_bs: doTrade( pool, stdPeriod, stdGuage, sa[0], sa[1], sa[2], sa[3], sa[4], sa[5], sb[0], sb[1], sb[2], sb[3], sb[4], sb[5], ) stdGuage += 0.1 pool.showStrategies() return
def runStrategy(prices): log.debug('beginning l5 strategy ...') ps = [p['close'] for p in prices] ys = ps[556:656] l = len(ys) slope, midy = calc_slope(ys) xs = range(l) midys = map(midy, xs) std = np.std(ys, dtype=np.float64, ddof=0) upys = map(lambda y: y + std * 1.2, midys) lowys = map(lambda y: y - std * 1.2, midys) plt.plot(xs, ys, 'b', xs, midys, 'y', xs, upys, 'r', xs, lowys, 'g')#, nxs, nys, 'm') #plt.plot(xs, ys, 'b-', xs, upys, 'r-', xs, lowys, 'g-') plt.show() return high1 = int(l/2) low1 = int(l/2) high2 = ys.index(max(ys)) low2 = ys.index(min(ys)) #high1 = high2 = low1 = low2 = 0 highsm = lowsm = float('inf') for x in range(0, l): if high1 != x: ty, sm, slope = genLine(high1, x, ys, 1) if sm < highsm: high2 = x highsm, highy, highSlope = sm, ty, slope if high2 != x: ty, sm, slope = genLine(high2, x, ys, 1) if sm < highsm: high1, high2 = high2, x highsm, highy, highSlope = sm, ty, slope if low1 != x: ty, sm, slope = genLine(low1, x, ys, -1) #print low1, x, sm, lowsm if sm < lowsm: low2 = x lowsm, lowy, lowSlope = sm, ty, slope #print low1, low2, sm if low2 != x: # and low1 != low2: ty, sm, slope = genLine(low2, x, ys, -1) #print low2, x, sm, lowsm if sm < lowsm: low1, low2 = low2, x lowsm, lowy, lowSlope = sm, ty, slope #return highy, lowy #print highSlope, lowSlope xs = range(l) upys = map(highy, xs) lowys = map(lowy, xs) plt.plot(xs, ys, 'b-', xs, upys, 'r-', xs, lowys, 'g-') plt.show() return
def runStrategy_0(in_prices): global mas, emas, smas, std, prices log.debug("beginning first strategy ...") prices = in_prices ps = [p["close"] for p in prices] std = [0] * 51 l = len(prices) for period in range(2, 51): std[period] = [0] * l for i in range(period - 1, l): std[period][i] = round(np.std(ps[i - period + 1 : i + 1], dtype=np.float64, ddof=0), 3) mas = [0] * 61 emas = [0] * 61 smas = [0] * 61 for period in range(2, 61): mas[period] = ma.calc_ma(ps, period) emas[period] = ma.calc_ema(ps, period) smas[period] = ma.calc_sma(ps, period) log.debug("running first strategy ...") starttime = datetime.datetime.now() matypes = ["MA", "EMA", "SMA"] farr = [2, 3, 4, 5, 6, 7] s1arr = [4, 6, 8, 10, 12, 14, 16, 18, 20] s2arr = [0, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51] pool = StrategyPool(100) for stdPeriod in [20, 30, 40]: stdGuage = 1.0 while stdGuage <= 1.3: maxAEquity = maxBEquity = 0 poola = StrategyPool(5) poolb = StrategyPool(5) for ft, f in [(matype, period) for matype in matypes for period in farr]: for s1t, s1 in [(matype, period) for matype in matypes for period in s1arr]: elapsed = (datetime.datetime.now() - starttime).seconds log.debug("== " + str(elapsed) + "," + ft + "_" + str(f) + "," + s1t + "_" + str(s1) + " ==") for s2t, s2 in [(matype, period) for matype in matypes for period in s2arr]: if s2 != 0 and s2 < s1: continue if s2 == 0 and (s2t == "EMA" or s2t == "SMA"): continue t = doTrade(poola, stdPeriod, stdGuage, ft, f, s1t, s1, s2t, s2, "", 0, "", 0, "", 0) if t.equity > maxAEquity: maxAEquity = t.equity maxEAs = [ft, f, s1t, s1, s2t, s2] elapsed = (datetime.datetime.now() - starttime).seconds log.info("find A time: " + str(elapsed) + " ") poola.showStrategies() for ft, f in [(matype, period) for matype in matypes for period in farr]: for s1t, s1 in [(matype, period) for matype in matypes for period in s1arr]: elapsed = (datetime.datetime.now() - starttime).seconds log.debug("== " + str(elapsed) + "," + ft + "_" + str(f) + "," + s1t + "_" + str(s1) + " ==") for s2t, s2 in [(matype, period) for matype in matypes for period in s2arr]: if s2 != 0 and s2 < s1: continue if s2 == 0 and (s2t == "EMA" or s2t == "SMA"): continue t = doTrade(poolb, stdPeriod, stdGuage, "", 0, "", 0, "", 0, ft, f, s1t, s1, s2t, s2) if t.equity > maxBEquity: maxBEquity = t.equity maxEBs = [ft, f, s1t, s1, s2t, s2] elapsed = (datetime.datetime.now() - starttime).seconds log.info("find B time: " + str(elapsed) + " ") poolb.showStrategies() logb.info(str(stdPeriod) + "," + str(stdGuage) + "," + str(maxAEquity) + "," + str(maxBEquity)) logb.info(str(maxEAs)) logb.info(str(maxEBs)) for i in range(5): sa = poola.strategies[i] sb = poolb.strategies[i] t = doTrade( pool, stdPeriod, stdGuage, sa[0].args[2], sa[0].args[3], sa[0].args[4], sa[0].args[5], sa[0].args[6], sa[0].args[7], sb[0].args[8], sb[0].args[9], sb[0].args[10], sb[0].args[11], sb[0].args[12], sb[0].args[13], ) t.generateGraph() pool.estimate(t) stdGuage += 0.1 pool.showStrategies()