Пример #1
0
def TransformToBinary(dataset , enable_indicator = True , pred_days = 7):
    # data: 1 ~ -31 days, every day will compare to previous 1 day (5) and 30 days (5) and next 7 day (1).
    # Hence, binary string will be (N-30-7)x(5+5+1) array
    size = dataset.shape[0]-30 - pred_days
    binary_string = np.zeros((size , 11) , dtype=np.int)

    for i in range(size):
        index = i + pred_days # get the index of dataset

        thisday = dataset[index]
        nextday = dataset[index-pred_days] #next day
        prvday = dataset[index+1] #previous day
        monthdata = dataset[index+1:index+31] #previous 30 days
        averagedata = np.sum(monthdata ,axis= 0)/30 #average of previous 30 days

        binary_string[i][:5] = thisday[1:] > prvday[1:] #represent the up and downs compared to previous day
        binary_string[i][5:10] = thisday[1:] > averagedata[1:] #represent the up and downs compared to prvious 30 days
        binary_string[i][-1] = nextday[1] > thisday[1]  # up and down

    if enable_indicator:
        arr1 = indicator.probability(dataset, 30 , pred_days).reshape(-1,1)

        arr2_1 = indicator.comAvg(dataset, 10, 5 , pred_days).reshape(-1,1)
        arr2_2 = indicator.comAvg(dataset, 30, 10 ,pred_days).reshape(-1,1)
        arr2_3 = indicator.comAvg(dataset, 30, 7 , pred_days).reshape(-1,1)
        arr2 = np.hstack((arr2_1, arr2_2, arr2_3))

        arr3 = indicator.RSI(dataset , pred_days)

        input_string = np.hstack((arr1, arr2, arr3, binary_string))
    else:
        input_string = binary_string

    return input_string
Пример #2
0
def indicatorPage():

	print('indicatorPage', file=sys.stderr)
	# POST
	if request.method == 'GET':
		try:
			stock_name = request.args['stock_name']
			indicatorSelect = request.args['indicatorSelect']
			#lists = None
			if indicatorSelect == "1":
				lists = indicator.MTM(stock_name)
				return render_template('indicatorPage.html', lists=json.dumps(lists), indicatorSelect="MTM")
			elif indicatorSelect == "2":
				lists = indicator.RSI(stock_name)
				return render_template('indicatorPage.html', lists=json.dumps(lists), indicatorSelect="RSI")
			else:
				lists = indicator.MACD(stock_name)
				return render_template('macdIndicator.html', lists=json.dumps(lists), indicatorSelect="MACD")

		#except Exception as e: print(e)
		except:
			return 'Fail'

	# if not POST, then it is GET
	return render_template('dashboardUser.html')
Пример #3
0
    def Xindicator(self, syms, dates):

        sma = ind.SMA(syms, 20, dates)
        bb = ind.BB(syms, 20, 2, dates)
        _, macd = ind.MACD(syms, 12, 26, 9, dates)
        rsi = ind.RSI(syms, 14, dates)

        X = pd.DataFrame({'SMA': sma, 'BB': bb, "MACD": macd, "RSI": rsi})
        return X
def calculate_thres():
    
    symbol = 'JPM'
    sd=dt.datetime(2008,1,1)
    ed=dt.datetime(2009,12,31)
    
    date = pd.date_range(sd  - dt.timedelta(days=50), ed)
    stockvals = get_data([symbol], date)
    stockvals = stockvals.loc[:, [symbol]]
    
    sma = ind.SMA(symbol, 20, date, gen_plot = False)
    sma = sma[sma.index >= sd]
    bb = ind.BB(symbol, 20, 2, date, gen_plot = False)
    bb = bb[bb.index >= sd]
    _, macd = ind.MACD(symbol, 12, 26, 9, date, gen_plot = False)
    macd = macd[macd.index >= sd]
    rsi = ind.RSI(symbol, 14, date, gen_plot = False)
    rsi = rsi[rsi.index >= sd]
    
    bounds = [(0, 1), (60, 85), (15,40)]
    optimal_thres = differential_evolution(optimalize, bounds, args=(sma, bb, macd, rsi, ))
    
    return(optimal_thres)
def testPolicy(symbol = 'JPM', sd=dt.datetime(2008,1,1), ed=dt.datetime(2009,12,31), sv = 100000):
    
    date = pd.date_range(sd  - dt.timedelta(days=50), ed)
    stockvals = get_data([symbol], date)
    stockvals = stockvals.loc[:, [symbol]]
    
    sma = ind.SMA(symbol, 20, date, gen_plot = False)
    sma = sma[sma.index >= sd]
    bb = ind.BB(symbol, 20, 2, date, gen_plot = False)
    bb = bb[bb.index >= sd]
    _, macd = ind.MACD(symbol, 12, 26, 9, date, gen_plot = False)
    macd = macd[macd.index >= sd]
    rsi = ind.RSI(symbol, 14, date, gen_plot = False)
    rsi = rsi[rsi.index >= sd]
    
    thres = [0.99243522, 84.70103144, 25.01519814] 
    """
    from calculate_thres
    """
    order_signal = signal(sma, bb, macd, rsi, thres)
    order = Order(order_signal)
             
    return order
Пример #6
0
def createFactorsTable(instrument=None, dbpath=None, con=None, **factors):
    '''
    Only have to input on of these 3:
        :param instrument:
        :param dbpath:
        :param con:
    :param factors: No use temporarily
    :return:

    How to use:
        createFactorsTable(instrument='EUR_USD')
        -------------------------------------------------------------
        createFactorsTable(dbpath='E:/FinanceData/Oanda/EUR_USD.db')
        -------------------------------------------------------------
        con=sqlite3.connect('E:/FinanceData/Oanda/EUR_USD.db')
        createFactorsTable(con=con)
        con.close()

    '''

    close = False

    if len(factors) == 0:
        factors = {
            'D': ['time', 'closeBid', 'highBid', 'lowBid'],
            'COT': ['publish', 's-l', 's-l_diff'],
            'HPR': ['time', 'position', 'position_diff']
        }

    if dbpath is None:
        dbpath = '%s/%s.db' % (savePath, instrument)

    print(dbpath)

    if con is None:
        con = sqlite3.connect(dbpath)
        close = True

    data = {}
    start = 0
    for k in factors.keys():
        f = factors[k]

        data[k] = read_sql(k, con=con).get(f)
        startTime = data[k].get_value(0, f[0])
        if start < startTime:
            start = startTime

    data['COT'].columns = ['time', 's-l', 's-l_diff']

    if close:
        con.close()

    price = data['D']

    momentum = indicator.momentum(price['time'], price['closeBid'], period=60)
    data['momentumfast'] = momentum
    momentum = indicator.momentum(price['time'], price['closeBid'], period=130)
    data['momentumslow'] = momentum
    data['atr'] = indicator.ATR(price['time'],
                                price['highBid'],
                                price['lowBid'],
                                price['closeBid'],
                                period=10)
    data['mafast'] = indicator.MA(price['time'],
                                  price['closeBid'],
                                  period=60,
                                  compare=True)
    data['maslow'] = indicator.MA(price['time'],
                                  price['closeBid'],
                                  period=130,
                                  compare=True)
    adx = indicator.ADX(price['time'],
                        price['highBid'],
                        price['lowBid'],
                        price['closeBid'],
                        period=10)
    data['ADX'] = adx
    data['RSI'] = indicator.RSI(price['time'], price['closeBid'], period=10)
    data['MACD'] = indicator.MACD(price['time'],
                                  price['closeBid'],
                                  out=['hist'])
    histdiff = [0]
    for h in data['MACD'].index.tolist()[1:]:
        histdiff.append(data['MACD'].get_value(h, 'hist') -
                        data['MACD'].get_value(h - 1, 'hist'))
    data['MACD'].insert(2, 'hist_diff', histdiff)

    data['ADX-mom'] = indicator.momentum(adx['time'],
                                         adx['ADX%s' % 10],
                                         period=5)
    data['ADX-mom'].columns = ['time', 'ADX-mom']

    data.pop('D')

    out = None
    for k in sorted(data.keys()):
        # if k == 'D':
        #     continue

        v = data[k]
        select = v[v.time >= start]
        for i in select.index:
            t = select.get_value(i, 'time')

            select.set_value(i, 'time', datetime.date.fromtimestamp(t))
        # print(select)
        if out is None:
            out = select.drop_duplicates('time').set_index('time')

        else:
            out = out.join(select.drop_duplicates('time').set_index('time'),
                           how='outer')

    for c in out.columns:
        former = out.get_value(out.index.tolist()[0], c)
        for t in out.index.tolist()[1:]:
            v = out.get_value(t, c)
            # print(t,c,v,type(v))
            if math.isnan(v):
                out.set_value(t, c, former)
            former = out.get_value(t, c)

    return out.dropna()
Пример #7
0
 def rsi(self, data, column='Velocity', period=5):
     RSI = ind.RSI(data['time'], data[column], period)
     return data.merge(RSI, 'outer', 'time')