Пример #1
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')
Пример #2
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
Пример #5
0
    def addEvidence(self, symbol, \
        sd=dt.datetime(2008,1,1), \
        ed=dt.datetime(2009,12,31), \
        sv = 100000):

        data = ut.get_data([symbol], pd.date_range(sd, ed))[symbol]
        price_indicator = indicator.bollinger(data)
        price_sma = price_indicator['Price/SMA']
        MACD = indicator.MACD(data)['MACD']
        # MACD = indicator.MACD(symbol, sd, ed)['Qstick']

        # calculate the feature & response for train, will do the same thing for test
        train_data = pd.DataFrame()

        train_data['Price/SMA'] = price_sma

        train_data['MACD'] = MACD

        train_data[
            'upper_ratio'] = price_indicator['upper'] / price_indicator['SMA']
        train_data[
            'lower_ratio'] = price_indicator['SMA'] / price_indicator['lower']
        train_data['return'] = price_indicator['price'].pct_change(5)

        # get X and Y
        data_arr = np.array(train_data.tail(-26))
        trainX = data_arr[:, 0:-1]
        trainY = data_arr[:, -1]

        # scaler = StandardScaler()
        # scaler.fit(trainY)
        # trainY_transform = scaler.transform(trainY)

        self.learner = rt.RTLearner(leaf_size=10, verbose=False)
        # self.learner.addEvidence(trainX,trainY_transform)
        trainY = (trainY - trainY.mean()) / trainY.std()
        self.learner.addEvidence(trainX, trainY)
Пример #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 testPolicy(self, symbol, \
        sd=dt.datetime(2010,1,1), \
        ed=dt.datetime(2011,12,31), \
        sv = 100000):

        data = ut.get_data([symbol], pd.date_range(sd, ed))[symbol]

        price_indicator = indicator.bollinger(data)
        price_sma = price_indicator['Price/SMA']

        # MACD = indicator.MACD(symbol, sd, ed)['Qstick']

        MACD = indicator.MACD(data)['MACD']

        # calculate the feature & response for train, will do the same thing for test
        data_policy = pd.DataFrame()
        data_policy['Price/SMA'] = price_sma
        data_policy['MACD'] = MACD

        data_policy[
            'upper_ratio'] = price_indicator['upper'] / price_indicator['SMA']
        data_policy[
            'lower_ratio'] = price_indicator['lower'] / price_indicator['SMA']
        # data_policy['return'] = price_indicator['price'].pct_change(periods=1)
        # print data_policy.shape
        # print data_policy
        data_test = np.array(data_policy.tail(-26))

        predict = self.learner.query(data_test)
        date = data_policy.tail(-26).index

        # build the trade dataframe based on the

        df_trades = pd.DataFrame({'Date': '', 'trade': ''}, index=[])
        options = [1000, -1000, 0]
        symbols = []
        symbols.append(symbol)

        YBUY = 0.01
        YSELL = -0.001
        for i in range(1, len(predict)):
            change = predict[i]
            pre_date = date[i]
            holding = df_trades.trade.sum()
            if holding == 0:
                if change - self.impact > YBUY:
                    trade = options[0]
                    df_trades = df_trades.append(
                        {
                            'Date': pre_date,
                            'trade': trade
                        }, ignore_index=True)
                else:
                    trade = options[1]
                    df_trades = df_trades.append(
                        {
                            'Date': pre_date,
                            'trade': trade
                        }, ignore_index=True)
            else:
                if change - self.impact > YBUY and holding < 0:
                    # buy 1000 shares, long 1000 shares
                    trade = options[0] + 1000
                    df_trades = df_trades.append(
                        {
                            'Date': pre_date,
                            'trade': trade
                        }, ignore_index=True)
                elif change < YSELL and holding > 0:
                    # sell 1000 shares, short 1000 shares
                    trade = options[1] - 1000
                    df_trades = df_trades.append(
                        {
                            'Date': pre_date,
                            'trade': trade
                        }, ignore_index=True)
                else:
                    continue
        if self.verbose: print type(trades)  # it better be a DataFrame!
        if self.verbose: print trades
        if self.verbose: print prices_all

        df_trades.set_index('Date', inplace=True)

        return df_trades