def technical_analyze(): print("*******************************************************") print("Enter your client\'s id (number only):") cus_id = input() cus_ticker_list = taup.get_client_tickers(cus_id) if cus_ticker_list == None or cus_ticker_list == []: print("Customer data not found!") cus_ticker_list = [] print("*******************************************************") print("Select indicators:(choices separated by ',' e.g. 1,2,3)") keys = list(INDICATORS.keys()) keys.sort() for k in keys: print("{}) {}".format(k, INDICATORS.get(k))) choices = [c.strip() for c in input().split(',')] if len(choices) > len(INDICATORS) or len( list(set(choices) - set(INDICATORS.keys()))) > 0: print("Invalid input!") else: for c in choices: if INDICATORS[c] == 'B-Bands': bbands(cus_ticker_list) elif INDICATORS[c] == 'CCI': cci(cus_ticker_list) elif INDICATORS[c] == 'KDJ': kdj(cus_ticker_list) elif INDICATORS[c] == 'MACD': macd(cus_ticker_list) elif INDICATORS[c] == 'OBV': obv(cus_ticker_list) elif INDICATORS[c] == 'Parabolic SAR': psar(cus_ticker_list) elif INDICATORS[c] == 'RSI': rsi(cus_ticker_list)
def macdFourier(stockData): """Takes in stockData in pandas.dataFrame type and returns index "cycle" of maximum frequency bin after performed Discrete Fourier Transform""" macd.macd(stockData) macdsignal = [] for signalDifference in stockData['MACD Signal Difference']: macdsignal.append(signalDifference) fourierd = fft(np.array(macdsignal)) norm = np.absolute(fourierd) return norm.argmax()
def compound_smooth_impulse_response(Neff_pos, Neff_neg, Nwindow): "a compound smoothing impulse response" h_step = step(Nwindow) h_macd = macd(Neff_pos, Neff_neg, Nwindow) gauge = 1.0 / (Neff_neg - Neff_pos) candidate = np.convolve(gauge * h_macd, h_step) return candidate[:Nwindow]
def macd_sma_combination(price, macd_small, macd_long, signal, sma_period): value_macd = macd.macd(price, macd_small, macd_long) value_signal = pd.rolling_mean(value_macd, signal) value_sma = pd.rolling_mean(price, sma_period) buy = cover = (value_macd > value_signal) & ( value_macd.shift() < value_signal.shift()) & (price > value_sma) sell = short = (value_macd < value_signal) & ( value_macd.shift() > value_signal.shift()) & (price < value_sma) del cover del short return value_macd, value_signal, value_sma, buy, sell
def macd_ema_anding(price, macd_small, macd_long, signal, ema_period): value_ema = ema.expon_moving_avg(price, ema_period) value_macd = macd.macd(price, macd_small, macd_long) value_signal = pd.rolling_mean(value_macd, signal) buy = cover = (value_macd > value_signal) & ( value_macd.shift() < value_signal.shift()) & (price > value_ema) & ( price.shift() < value_ema.shift()) sell = short = (value_macd < value_signal) & ( value_macd.shift() > value_signal.shift()) & (price < value_ema) & ( price.shift() > value_ema.shift()) del cover del short return value_ema, value_macd, value_signal, buy, sell
def calc_box_diff_macd_spectra_mse(Neff, Nbox, Nwindow): "Mean-Squared Error\ 1) generates h_box_diff and h_macd 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_diff = box_diff(Nbox, Nwindow) h_macd = switch_to_composite_unit_gauge(macd(Neff/3.0, Neff, Nwindow)) #h_macd = macd(Neff, Nwindow) h_box_diff_fft = np.fft.fft(h_box_diff) h_macd_fft = np.fft.fft(h_macd) h_box_diff_fft_abs = np.absolute(h_box_diff_fft) h_macd_fft_abs = np.absolute(h_macd_fft) h_box_diff_fft_abs_sum = np.cumsum(h_box_diff_fft_abs) h_macd_fft_abs_sum = np.cumsum(h_macd_fft_abs) mse = np.sum(np.square(h_box_diff_fft_abs_sum - h_macd_fft_abs_sum)) / Nwindow return mse
def calc_box_diff_macd_spectra_mse(Neff, Nbox, Nwindow): "Mean-Squared Error\ 1) generates h_box_diff and h_macd 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_diff = box_diff(Nbox, Nwindow) h_macd = switch_to_composite_unit_gauge(macd(Neff / 3.0, Neff, Nwindow)) #h_macd = macd(Neff, Nwindow) h_box_diff_fft = np.fft.fft(h_box_diff) h_macd_fft = np.fft.fft(h_macd) h_box_diff_fft_abs = np.absolute(h_box_diff_fft) h_macd_fft_abs = np.absolute(h_macd_fft) h_box_diff_fft_abs_sum = np.cumsum(h_box_diff_fft_abs) h_macd_fft_abs_sum = np.cumsum(h_macd_fft_abs) mse = np.sum( np.square(h_box_diff_fft_abs_sum - h_macd_fft_abs_sum)) / Nwindow return mse
#!/usr/bin/anaconda3/bin/python import csv import numpy as np import matplotlib.pyplot as plt from macd import macd from diff import diff f, axarr = plt.subplots(5, 1) Nwindow = 500 h_diff_1 = macd(2, 4, Nwindow) h_diff_2 = macd(5, 10, Nwindow) h_diff_3 = macd(10, 20, Nwindow) h_diff_4 = macd(20, 40, Nwindow) h_diff_5 = macd(50, 100, Nwindow) h_diff_11 = diff(2, 4, Nwindow) h_diff_22 = diff(5, 10, Nwindow) h_diff_33 = diff(10, 20, Nwindow) h_diff_44 = diff(20, 40, Nwindow) h_diff_55 = diff(50, 100, Nwindow) with open('jpm_trades.csv', 'r') as trades_csv: trades = np.array(list(csv.reader(trades_csv))[1:]).astype('double') prices = trades[:, 1] log_prices = np.log(prices) candidate1 = np.convolve(log_prices - log_prices[0], h_diff_1)
formatter = MyFormatter(data.vDate[daysToPlot:]) [per_k, per_d] = stochastic_oscillator.stoc_osc(data.vHigh, data.vLow, data.vClose, 15, 5, 5, "ema") plt.figure(1) ax1 = plt.subplot('411') candlestick2(ax1, data.vOpen[daysToPlot:], data.vClose[daysToPlot:], data.vHigh[daysToPlot:], data.vLow[daysToPlot:], width=0.6) [macdOut, ema, divergence] = macd.macd(data.vClose, 12, 26, 9) ax2 = plt.subplot('412') ax2.plot(macdOut[daysToPlot:]) ax2.plot(ema[daysToPlot:]) ax2.stem(arange(-1 * daysToPlot), divergence[daysToPlot:]) # MACD [macdOut, ema, divergence] = macd.macd(data.vClose, 5, 10, 4) ax2 = plt.subplot('413') ax2.plot(macdOut[daysToPlot:]) ax2.plot(ema[daysToPlot:]) ax2.stem(arange(-1 * daysToPlot), divergence[daysToPlot:]) # Stochastic Oscillator. ax3 = plt.subplot('414') ax3.plot(per_k[daysToPlot:], color="red") ax3.plot(per_d[daysToPlot:], color='darkviolet') ax3.axhline(70, color="grey")
from box_diff import box_diff from macd import macd from switch_to_composite_unit_gauge import switch_to_composite_unit_gauge from calc_box_diff_macd_spectra_mse import calc_box_diff_macd_spectra_mse Nwindow = 1024 Nbox = 16 Neff_neg = 16 Neff_pos = Neff_neg / 3.0 f, axarr = plt.subplots(2, 2) # a) Indicative responses h_box_diff = box_diff(Nbox, Nwindow) h_macd = switch_to_composite_unit_gauge(macd(Neff_pos, Neff_neg, Nwindow)) axarr[0, 0].plot(h_box_diff[:150]) axarr[0, 0].plot(h_macd[:150]) axarr[0, 0].set_title('Box and macd differencer impulse response') # b) Spectra h_box_diff_fft = np.fft.fft(h_box_diff) h_macd_fft = np.fft.fft(h_macd) h_box_diff_fft_abs = np.absolute(h_box_diff_fft) h_macd_fft_abs = np.absolute(h_macd_fft) axarr[0, 1].plot(h_box_diff_fft_abs) axarr[0, 1].plot(h_macd_fft_abs, 'r--')
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) print("Calculate WMA: \t\t %gs" % ((time.time() - t1) / 1.0)) t1 = time.time() for i in range(10): indicator = kama.kama(closes) print("Calculate KAMA: \t %gs" % ((time.time() - t1) / 10.0)) t1 = time.time() for i in range(10): indicator = kd.kd(ohlc) print("Calculate KD: \t\t %gs" % ((time.time() - t1) / 10.0)) t1 = time.time() for i in range(10): indicator = macd.macd(closes) print("Calculate MACD: \t %gs" % ((time.time() - t1) / 10.0))
ind = int(round(x)) if ind>=len(self.dates) or ind<0: return '' return self.dates[ind].strftime(self.fmt) formatter= MyFormatter(data.vDate[daysToPlot:]) [per_k, per_d] = stochastic_oscillator.stoc_osc(data.vHigh, data.vLow, data.vClose,15,5,5,"ema") plt.figure(1) ax1 = plt.subplot('411') candlestick2(ax1, data.vOpen[daysToPlot:],data.vClose[daysToPlot:],data.vHigh[daysToPlot:],data.vLow[daysToPlot:], width=0.6) [macdOut, ema, divergence] = macd.macd(data.vClose, 12,26, 9) ax2 = plt.subplot('412') ax2.plot(macdOut[daysToPlot:]) ax2.plot( ema[daysToPlot:]) ax2.stem(arange(-1*daysToPlot), divergence[daysToPlot:]) # MACD [macdOut, ema, divergence] = macd.macd(data.vClose, 5,10, 4) ax2 = plt.subplot('413') ax2.plot(macdOut[daysToPlot:]) ax2.plot( ema[daysToPlot:]) ax2.stem(arange(-1*daysToPlot), divergence[daysToPlot:]) # Stochastic Oscillator. ax3 = plt.subplot('414') ax3.plot(per_k[daysToPlot:], color="red") ax3.plot(per_d[daysToPlot:], color='darkviolet') ax3.axhline(70, color="grey")
impulse[lag] = 1 candidate = apply_integrated_macd_poly_filter(impulse, Neff) impulse_response_fde = candidate[lag:] impulse_response_direct = int_macd_poly(Neff_modified, Nwindow) axarr[2, 0].set_title("Integrated Macd-Poly") axarr[2, 0].plot(impulse_response_fde) axarr[2, 0].plot(impulse_response_direct, 'o', markerfacecolor='none') # f) Macd Neff_pos = 16 Neff_neg = 32 lag = 2 impulse = np.zeros(Nwindow) impulse[lag] = 1 candidate = apply_macd_filter(impulse, Neff_pos, Neff_neg) impulse_response_fde = candidate[lag:] impulse_response_direct = macd(Neff_pos, Neff_neg, Nwindow) axarr[2, 1].set_title("Macd") axarr[2, 1].plot(impulse_response_fde) axarr[2, 1].plot(impulse_response_direct, 'o', markerfacecolor='none') plt.tight_layout() plt.show()
def macdSlope3DirectInput(stockString, date): """Input stock as a string and date of crossover and returns angle made with midpoints three days past and three days ahead of MACD line and Signal Line""" stock = pd.io.parsers.read_csv('presentstockdata/' + stockString + '.csv') macd.macd(stock) volume.volumeAve(stock) index = len(stock['date']) - 1 while index != -1: if stock['date'][index] == date: break index -= 1 m3Before = stock['MACD Line'][index - 5] m1Before = stock['MACD Line'][index - 3] m1After = stock['MACD Line'][index - 2] m3After = stock['MACD Line'][index] s3Before = stock['Signal Line'][index - 5] s1Before = stock['Signal Line'][index - 3] s1After = stock['Signal Line'][index - 2] s3After = stock['Signal Line'][index] mid3Before = (m3Before + s3Before) / 2 mid3After = (m3After + s3After) / 2 print("mids") print(mid3Before, mid3After) slopeMACD = -(m1After - m1Before) slopeSignal = -(s1After - s1Before) eqs = np.array([[slopeMACD, 1], [slopeSignal, 1]]) points = np.array([m1Before, s1Before]) sol = np.linalg.solve(eqs, points) print("sols") print(sol) xcoor = sol[0] ycoor = sol[1] xDBefore = 2 + xcoor yDBefore = mid3Before - ycoor xDAfter = 3 - xcoor yDAfter = mid3After - ycoor print("coordinates") print(xDBefore, yDBefore, xDAfter, yDAfter) dBefore = math.sqrt(xDBefore**2 + yDBefore**2) dAfter = math.sqrt(xDAfter**2 + yDAfter**2) longest = math.sqrt(5**2 + (mid3Before - mid3After)**2) print("legs of triangles") print(dBefore, dAfter, longest) print(dBefore**2, dAfter**2, longest**2) valueOne = (dBefore**2 + dAfter**2 - longest**2) / (2 * dBefore * dAfter) print(valueOne) return np.arccos(valueOne)
cloture_veille = float(span[12].contents[0].split()[0]) date = datetime.datetime.now() # Récupération dans la base les valeurs de la dernière cotation d = "{2}-{1}-{0}".format(date.day,date.month,date.year) conn = sqlite3.connect(r'e:\doc\technip.db') c = conn.cursor() t = (d,) c.execute('select mme20,mme12,mme26 from cotation where date < ? order by date DESC LIMIT 1', t) mme_veille_20, mme_veille_mme12, mme_veille_mme26 = c.fetchone() conn.close() mme20 = mme(20,mme_veille_20,cotation) mme12 = mme(12,mme_veille_mme12,cotation) mme26 = mme(26,mme_veille_mme26,cotation) macd = macd(mme12,mme26) # On affiche print("{}\n".format(action)) print("Cotation : {}\n".format(cotation)) print("Date : {0}/{1}/{2} \n".format(date.day,date.month,date.year)) print("Volume : {}\n".format(volume)) print("Ouverture : {}\n".format(ouverture)) print("Haut : {}\n".format(haut)) print("Bas : {}\n".format(bas)) print("Cloture de la veille : {}\n".format(cloture_veille)) print("Variation : {}".format((( cotation - cloture_veille ) / cotation ) * 100)) # INSERTION dans base SQLITE conn = sqlite3.connect(r'e:\doc\technip.db') c = conn.cursor()
from macd import macd from switch_to_composite_unit_gauge import switch_to_composite_unit_gauge from calc_box_diff_macd_spectra_mse import calc_box_diff_macd_spectra_mse Nwindow = 1024 Nbox = 16 Neff_neg = 16 Neff_pos = Neff_neg/3.0 f, axarr = plt.subplots(2, 2) # a) Indicative responses h_box_diff = box_diff(Nbox, Nwindow) h_macd = switch_to_composite_unit_gauge(macd(Neff_pos, Neff_neg, Nwindow)) axarr[0, 0].plot(h_box_diff[:150]) axarr[0, 0].plot(h_macd[:150]) axarr[0, 0].set_title('Box and macd differencer impulse response') # b) Spectra h_box_diff_fft = np.fft.fft(h_box_diff) h_macd_fft = np.fft.fft(h_macd) h_box_diff_fft_abs = np.absolute(h_box_diff_fft) h_macd_fft_abs = np.absolute(h_macd_fft) axarr[0, 1].plot(h_box_diff_fft_abs) axarr[0, 1].plot(h_macd_fft_abs, 'r--')
#!/usr/bin/anaconda3/bin/python import csv import numpy as np import matplotlib.pyplot as plt from macd import macd from diff import diff f, axarr = plt.subplots(5, 1) Nwindow=500 h_diff_1 = macd(2, 4, Nwindow) h_diff_2 = macd(5, 10, Nwindow) h_diff_3 = macd(10, 20, Nwindow) h_diff_4 = macd(20, 40, Nwindow) h_diff_5 = macd(50, 100, Nwindow) h_diff_11 = diff(2, 4, Nwindow) h_diff_22 = diff(5, 10, Nwindow) h_diff_33 = diff(10, 20, Nwindow) h_diff_44 = diff(20, 40, Nwindow) h_diff_55 = diff(50, 100, Nwindow) with open('jpm_trades.csv', 'r') as trades_csv: trades = np.array(list(csv.reader(trades_csv))[1:]).astype('double') prices = trades[:,1] log_prices = np.log(prices) candidate1 = np.convolve(log_prices-log_prices[0], h_diff_1)
date1 = date.today() - timedelta(days=daysBack) # end date2 = date.today() # Format of quotes (d, open, close, high, low, volume) quotes = quotes_historical_yahoo( symbol, date1, date2) N = quotes.__len__(); vOpen = zeros(N) vClose = zeros(N) index = 0; for lines in quotes:#arange(0,N): vOpen[index] = lines [1]; vClose[index] = lines [2]; index = index + 1; macdOut, ema, divergence = macd.macd(vOpen, 26, 12, 9) plt.subplot(2, 1, 1) plt.plot(vClose); plt.hold(True) plt.grid() plt.subplot(2, 1, 2) plt.grid() plt.plot(macdOut, 'k') plt.plot(ema, 'g') plt.stem(arange(0, N), divergence) plt.show()
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 # conv(g h_ema, px[n]-px[0]) = conv(g h_ema, px[n]) - g px[0] # produces a term g px[0] because the gain of the ema impulse # response itself is one.
impulse = np.zeros(Nwindow) impulse[lag] = 1 candidate = apply_integrated_macd_poly_filter(impulse, Neff) impulse_response_fde = candidate[lag:] impulse_response_direct = int_macd_poly(Neff_modified, Nwindow) axarr[2, 0].set_title("Integrated Macd-Poly") axarr[2, 0].plot(impulse_response_fde) axarr[2, 0].plot(impulse_response_direct, 'o', markerfacecolor='none') # f) Macd Neff_pos = 16 Neff_neg = 32 lag = 2 impulse = np.zeros(Nwindow) impulse[lag] = 1 candidate = apply_macd_filter(impulse, Neff_pos, Neff_neg) impulse_response_fde = candidate[lag:] impulse_response_direct = macd(Neff_pos, Neff_neg, Nwindow) axarr[2, 1].set_title("Macd") axarr[2, 1].plot(impulse_response_fde) axarr[2, 1].plot(impulse_response_direct, 'o', markerfacecolor='none') plt.tight_layout() plt.show()