def macd(Neff_pos, Neff_neg, Nwindow): "moving average convergence/divergence" h_pos = ema(Neff_pos, Nwindow) h_neg = ema(Neff_neg, Nwindow) h = h_pos - h_neg return h
def test_ema(closes): """EMA test function.""" ema5 = ema(closes, 5) ema10 = ema(closes, 10) data = pd.concat([closes, ema5, ema10], axis=1) # print(data) data.plot(title="EMA Chart") plt.show()
def dema(arg, window): """DEMA: Double Exponential Moving Average. Params: arg (Series): Time series data such as close prices. window (int): Moving average window size. Returns: Series: Double exponential moving average of arg. """ ema1 = ema(arg, window) ema2 = ema(ema1, window) dema = ema1 * 2 - ema2 return Series(data = dema, name = "dema" + str(window))
def tema(arg, window): """TEMA: Triple Exponential Moving Average. Params: arg (Series): Time series data such as close prices. window (int): Moving average window size. Returns: Series: Triple exponential moving average of arg. """ ema1 = ema(arg, window) ema2 = ema(ema1, window) ema3 = ema(ema2, window) tema = ema1 * 3 - ema2 * 3 + ema3 return Series(data = tema, name = "tema" + str(window))
def macd_poly(Neff, Nwindow): "Macd-Poly differencer" if Neff > 0: h_pos = ema(Neff/3.0, Nwindow) h_neg = ema_poly1(Neff, Nwindow) h = h_pos - h_neg else: h = np.zeros(Nwindow) h[0]=1 h[1]=-1 return h
def animate(i): try: ax1.clear() em = ema.ema(h.bidHistory['price']) ax1.plot(h.bidHistory['time'], h.bidHistory['price'], '-o', label='second') ax1.plot(h.bidHistory['time'], em, '-o', label='third') ax1.xaxis.set_major_formatter(majorFormatter) ax1.autoscale_view() except: pass
def pac(result, longueur): #pacC result = ema.ema(result, longueur, "close") #pacL result = ema.ema(result, longueur, "low") #pacU result = ema.ema(result, longueur, "high") for i in range(0, len(result[0])): try: if (result[0][i]["close"] >= result[0][i]["EMA" + str(longueur) + "high"]): result[0][i]["pac"] = 1 elif (result[0][i]["close"] <= result[0][i]["EMA" + str(longueur) + "low"]): result[0][i]["pac"] = -1 else: result[0][i]["pac"] = 0 except KeyError: pass return result
def macd_poly(Neff, Nwindow): "Macd-Poly differencer" if Neff > 0: h_pos = ema(Neff / 3.0, Nwindow) h_neg = ema_poly1(Neff, Nwindow) h = h_pos - h_neg else: h = np.zeros(Nwindow) h[0] = 1 h[1] = -1 return h
def calc_ema_imacd_spectra_mse(Neff_imacd, Neff_ema, Nwindow): "Mean-Squared Error\ 1) generates h_ema and h_imacd given the input parameters;\ 2) takes the amplitude of the FFT for each response\ 3) computes the cumulative sum of each gain spectrum\ 4) computes and retuns the MSE of the two cumulative gain spectra" h_ema = ema(Neff_ema, Nwindow) h_imacd = int_macd_poly(Neff_imacd, Nwindow) h_ema_fft = np.fft.fft(h_ema) h_imacd_fft = np.fft.fft(h_imacd) h_ema_fft_abs = np.absolute(h_ema_fft) h_imacd_fft_abs = np.absolute(h_imacd_fft) h_ema_fft_abs_sum = np.cumsum(h_ema_fft_abs) h_imacd_fft_abs_sum = np.cumsum(h_imacd_fft_abs) mse = np.sum(np.square(h_ema_fft_abs_sum - h_imacd_fft_abs_sum)) / Nwindow return mse
def calc_box_ema_spectra_mse(Neff, Nbox, Nwindow): "Mean-Squared Error\ 1) generates h_ema and h_box given the input parameters;\ 2) takes the amplitude of the FFT for each response\ 3) computes the cumulative sum of each gain spectrum\ 4) computes and retuns the MSE of the two cumulative gain spectra" h_box = box(Nbox, Nwindow) h_ema = ema(Neff, Nwindow) h_box_fft = np.fft.fft(h_box) h_ema_fft = np.fft.fft(h_ema) h_box_fft_abs = np.absolute(h_box_fft) h_ema_fft_abs = np.absolute(h_ema_fft) h_box_fft_abs_sum = np.cumsum(h_box_fft_abs) h_ema_fft_abs_sum = np.cumsum(h_ema_fft_abs) mse = np.sum(np.square(h_box_fft_abs_sum - h_ema_fft_abs_sum)) / Nwindow return mse
axarr[0, 1].set_title("Box") axarr[0, 1].plot(impulse_response_fde) axarr[0, 1].plot(impulse_response_direct, 'o', markerfacecolor='none') # c) Ema Neff = 32 lag = 1 impulse = np.zeros(Nwindow) impulse[lag] = 1 candidate = apply_ema_filter(impulse, Neff) impulse_response_fde = candidate[lag:] impulse_response_direct = ema(Neff, Nwindow) axarr[1, 0].set_title("Ema") axarr[1, 0].plot(impulse_response_fde) axarr[1, 0].plot(impulse_response_direct, 'o', markerfacecolor='none') # d) Ema poly1 Neff = 32 lag = 2 impulse = np.zeros(Nwindow) impulse[lag] = 1 candidate = apply_ema_poly1_filter(impulse, Neff) impulse_response_fde = candidate[lag:]
indicator = bbands.bbands(closes, 20, 2.0) print("Calculate BOLL: \t %gs" % ((time.time() - t1) / 1.0)) t1 = time.time() for i in range(10): indicator = dchannel.dchannel(ohlc, 10) print("Calculate DCHANNEL: \t %gs" % ((time.time() - t1) / 10.0)) t1 = time.time() for i in range(10): indicator = sma.sma(closes, 10) print("Calculate SMA: \t\t %gs" % ((time.time() - t1) / 10.0)) t1 = time.time() for i in range(10): indicator = ema.ema(closes, 10) print("Calculate EMA: \t\t %gs" % ((time.time() - t1) / 10.0)) t1 = time.time() for i in range(10): indicator = dema.dema(closes, 10) print("Calculate DEMA: \t %gs" % ((time.time() - t1) / 10.0)) t1 = time.time() for i in range(10): indicator = tema.tema(closes, 10) print("Calculate TEMA: \t %gs" % ((time.time() - t1) / 10.0)) t1 = time.time() for i in range(1): indicator = wma.wma(closes, 10)
from box import box from delta import delta from ema import ema from macd import macd from diff import diff Nwindow = 400 Neff_pos = 20 Neff_neg = 40 Neff = 20 Nbox = 20 h_step = step(Nwindow) h_box = box(Nbox, Nwindow) h_delta = delta(Neff_pos, Nwindow) h_ema = ema(Neff_pos, Nwindow) h_macd = macd(Neff_pos, Neff_neg, Nwindow) h_diff = diff(Neff_pos, Neff_neg, Nwindow) f, axarr = plt.subplots(3, 2) axarr[0, 0].plot(h_step) axarr[0, 0].set_title("step") axarr[0, 1].plot(h_box) axarr[0, 1].set_title("box") axarr[1, 0].plot(h_delta) axarr[1, 0].set_title("delta") axarr[1, 1].plot(h_diff)
# ГЛАВНАЯ ПРОГРАММА НАЧИНАЕТСЯ ЗДЕСЬ stopFlag = False # если этот флаг=Истина, ордера не выставляем print("BTC доступно: ", "%.8f" % wallet.checkAmountOnWallet()) print("CREX доступно: ", "%.8f" % wallet.checkAmountOnWalletCREX()) # startWallet=wallet.checkAmountOnWallet() print( "Запускаю основной цикл. Обновление раз в 30 секунд. Торгуем на 3 минутах." ) while (True): data = getdata.getData() sred = ema.ema(data[-20:-1:], 0.5) #alpha была 0.5 bol = (4 * std(data[-20:-1:]) / sred[-1]) / 2 interval = abs(sred[-1] - sred[-1] * (1 + bol)) # покупаем-продаем (восходящий тренд) if (getdata.currentPriceBid() < sred[-1] - interval * 0.7) and (stopFlag == False): buy.placeOrder(float(getdata.currentPriceBid())) stopFlag = True print("КУПИЛИ по цене ", getdata.currentPriceBid()) sell.placeOrder(sred[-1] + interval) print("ОРДЕР НА ПРОДАЖУ по цене ", float(sred[-1] * (1 + bol))) # продаем-покупаем (нисходящий тренд) if (getdata.currentPriceBid() > sred[-1] + interval * 0.7) and (stopFlag == False):
import csv import numpy as np import matplotlib.pyplot as plt from ema import ema f, axarr = plt.subplots(4, 2) print("Problem 6: Ema on price series") print("(a) Ema impulse response.") Nwindow = 500 h_ema_1 = ema(2, Nwindow) h_ema_2 = ema(5, Nwindow) h_ema_3 = ema(10, Nwindow) h_ema_4 = ema(20, Nwindow) h_ema_5 = ema(50, Nwindow) h_ema_6 = ema(100, Nwindow) axarr[0, 0].plot(h_ema_1) axarr[0, 0].plot(h_ema_2) axarr[0, 0].plot(h_ema_3) axarr[0, 0].plot(h_ema_4) axarr[0, 0].plot(h_ema_5) axarr[0, 0].plot(h_ema_6) axarr[0, 0].set_title('Ema impulse responses with Neff = 2,5,10,20,50,100') with open('jpm_trades.csv', 'r') as trades_csv:
from scipy import optimize from ema import ema from int_macd_poly import int_macd_poly from calc_ema_imacd_spectra_mse import calc_ema_imacd_spectra_mse Nwindow = 1024 Neff_ema = 16 Neff_imacd = 16 f, axarr = plt.subplots(2, 2) # a) Indicative responses h_ema = ema(Neff_ema, Nwindow) h_imacd = int_macd_poly(Neff_imacd, Nwindow) axarr[0, 0].plot(h_ema[:150]) axarr[0, 0].plot(h_imacd[:150]) axarr[0, 0].set_title('Ema and integrated macd poly.') # b) Spectra h_ema_fft = np.fft.fft(h_ema) h_imacd_fft = np.fft.fft(h_imacd) h_ema_fft_abs = np.absolute(h_ema_fft) h_imacd_fft_abs = np.absolute(h_imacd_fft) axarr[0, 1].plot(h_ema_fft_abs)
axarr[0, 1].set_title("Box") axarr[0, 1].plot(impulse_response_fde) axarr[0, 1].plot(impulse_response_direct, 'o',markerfacecolor='none') # c) Ema Neff = 32 lag = 1 impulse = np.zeros(Nwindow) impulse[lag] = 1 candidate = apply_ema_filter(impulse, Neff) impulse_response_fde = candidate[lag:] impulse_response_direct = ema(Neff, Nwindow) axarr[1, 0].set_title("Ema") axarr[1, 0].plot(impulse_response_fde) axarr[1, 0].plot(impulse_response_direct, 'o', markerfacecolor='none') # d) Ema poly1 Neff = 32 lag = 2 impulse = np.zeros(Nwindow) impulse[lag] = 1 candidate = apply_ema_poly1_filter(impulse, Neff) impulse_response_fde = candidate[lag:]
def test_ema_50(self): ema.ema(config.index, 50, refresh=config.refresh)
def loadCfg(self, pid : int, botId : str, binance_apikey : str, binance_sekkey : str, work_path : str, pid_file_path : str, cmd_pipe_file_path : str, binance_pair : str, fast_ema : int, fast_ema_offset : int, slow_ema : int, slow_ema_offset : int, time_sample : int, notification : str, max_timeout_to_exit : int, retry_timeout : int ) -> int: # global auxPid_file_path # global auxCmd_pipe_file_path # auxPid_file_path = pid_file_path # auxCmd_pipe_file_path = cmd_pipe_file_path setPidFileAndPipeFile(pid_file_path, cmd_pipe_file_path) self.cfg.set('binance_apikey' , binance_apikey) self.cfg.set('binance_sekkey' , binance_sekkey) self.cfg.set('work_path' , work_path) self.cfg.set('pid' , pid) self.cfg.set('pid_file_path' , pid_file_path) self.cfg.set('bot_id' , botId) self.cfg.set('cmd_pipe_file_path' , cmd_pipe_file_path) self.cfg.set('binance_pair' , binance_pair) self.cfg.set('fast_ema' , fast_ema) self.cfg.set('fast_ema_offset' , fast_ema_offset) self.cfg.set('slow_ema' , slow_ema) self.cfg.set('slow_ema_offset' , slow_ema_offset) self.cfg.set('max_timeout_to_exit', max_timeout_to_exit) self.cfg.set('retry_timeout' , retry_timeout) self.emaSlow = ema(self.cfg.get('slow_ema'), self.cfg.get('slow_ema_offset')) self.emaFast = ema(self.cfg.get('fast_ema'), self.cfg.get('fast_ema_offset')) if notification.lower() == 'twitter': self.twtt.accessData(self.cfg.get('bot_id')) try: self.cfg.set('time_sample', klineAPIIntervals[time_sample]) except KeyError as e: logging.info(f'Error: time sample {argvInit[6]} not defined. Use one of: ') logging.info(klineAPIIntervals.keys()) raise try: mkfifo(cmd_pipe_file_path) except (OSError, FileExistsError) as e: logging.info(f"Erro creating cmd pipe file: {e.errno} - {e.strerror}") raise logging.info(f"\n================================================================\nBOT {self.cfg.get('bot_id')} Configuration:") logging.info(f"\tPID = [{self.cfg.get('pid')}]") logging.info(f"\tPID file = [{self.cfg.get('pid_file_path')}]") logging.info(f"\tCMD pipe = [{self.cfg.get('cmd_pipe_file_path')}]") logging.info(f"\tWorking path = [{self.cfg.get('work_path')}]") logging.info(f"\tBinance pair = [{self.cfg.get('binance_pair')}]") logging.info(f"\tEMA Slow/Fast = [{self.cfg.get('slow_ema')} / {self.cfg.get('fast_ema')}]") logging.info(f"\tEMA Slow/Fast Offset = [{self.cfg.get('slow_ema_offset')} / {self.cfg.get('fast_ema_offset')}]") logging.info(f"\tTime sample = [{self.cfg.get('time_sample')[0]}]") logging.info(f"\tBinance API key = [{self.cfg.get('binance_apikey')}]") logging.info(f"\tMaximum timeout attempts before exit = [{self.cfg.get('max_timeout_to_exit')}]") logging.info(f"\tSeconds between timeouts = [{self.cfg.get('retry_timeout')}]\n") return 0
from box import box from ema import ema from calc_box_ema_spectra_mse import calc_box_ema_spectra_mse Nwindow = 1024 Nbox = 16 f, axarr = plt.subplots(2, 2) # a) Indicative responses Neff = Nbox / (1-np.exp(-1)) h_box = box(Nbox, Nwindow) h_ema = ema(Neff, Nwindow) axarr[0, 0].plot(h_box[:150]) axarr[0, 0].plot(h_ema[:150]) axarr[0, 0].set_title('Box and ema impulse response') # b) Spectra h_box_fft = np.fft.fft(h_box) h_ema_fft = np.fft.fft(h_ema) h_box_fft_abs = np.absolute(h_box_fft) h_ema_fft_abs = np.absolute(h_ema_fft) axarr[0, 1].plot(h_box_fft_abs) axarr[0, 1].plot(h_ema_fft_abs, 'r--')
#!/usr/bin/anaconda3/bin/python import csv import numpy as np import matplotlib.pyplot as plt from ema import ema from macd import macd f, axarr = plt.subplots(2, 3) print("Problem 5: Gain") Neff = 20 Nwindow = 100 h_ema = ema(Neff, Nwindow) Neff_pos = 20 Neff_neg = 40 h_macd = macd(Neff_pos, Neff_neg, Nwindow) with open('jpm_trades.csv', 'r') as trades_csv: trades = np.array(list(csv.reader(trades_csv))[1:]).astype('double') prices = trades[:,1] candidate = np.convolve(prices, h_ema) truncated = candidate[:len(prices)] print("(a) Ema gain") # The gain = 1 is the correct choice. # The factor g must be multiplied with the offset prices[0] # because
from box import box from ema import ema from calc_box_ema_spectra_mse import calc_box_ema_spectra_mse Nwindow = 1024 Nbox = 16 f, axarr = plt.subplots(2, 2) # a) Indicative responses Neff = Nbox / (1 - np.exp(-1)) h_box = box(Nbox, Nwindow) h_ema = ema(Neff, Nwindow) axarr[0, 0].plot(h_box[:150]) axarr[0, 0].plot(h_ema[:150]) axarr[0, 0].set_title('Box and ema impulse response') # b) Spectra h_box_fft = np.fft.fft(h_box) h_ema_fft = np.fft.fft(h_ema) h_box_fft_abs = np.absolute(h_box_fft) h_ema_fft_abs = np.absolute(h_ema_fft) axarr[0, 1].plot(h_box_fft_abs) axarr[0, 1].plot(h_ema_fft_abs, 'r--')