예제 #1
0
    def _compute_indicators(prices, highs, lows, volumes, lookback):
        mtm = momentum(prices, lookback)
        sma, sma_ratio = simple_moving_average(prices, lookback)
        bbands = bollinger_bands(prices, sma, lookback)
        mfi = money_flow_index(prices, highs, lows, volumes, lookback)

        return mtm, sma_ratio, bbands, mfi
예제 #2
0
    def addEvidence(self, symbol = "IBM", \
        sd=dt.datetime(2008,1,1), \
        ed=dt.datetime(2009,1,1), \
        sv = 10000):

        window_size = self.window_size
        num_feature = self.idt_size
        num_n_day_return = 10
        threshold = max(0.03, 2 * self.impact)

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

        sma = indi.simple_moving_average(prices, window_size=window_size)

        X = []
        Y = []
        for i in range(window_size + num_feature + 1,
                       len(prices) - num_n_day_return):
            X.append(np.array(sma[i - num_feature:i]))

            gain = (prices.values[i + num_n_day_return] -
                    prices.values[i]) / prices.values[i]
            if gain > threshold:
                Y.append(1)
            elif gain < -threshold:
                Y.append(-1)
            else:
                Y.append(0)
        X = np.array(X)
        Y = np.array(Y)

        self.learner.addEvidence(X, Y)
예제 #3
0
def testPolicy(symbol='JPM',
               sd=dt.datetime(2008, 1, 1),
               ed=dt.datetime(2009, 12, 31),
               sv=100000):
    prices = get_data([symbol], pd.date_range(sd, ed))
    prices = prices[symbol]

    dates = pd.date_range(sd, ed)
    prices_all = get_data([symbol], dates)  # automatically adds SPY
    df_trades = prices_all[[
        symbol,
    ]].copy(deep=True)  # only portfolio symbols
    # df_trades = pd.DataFrame(data=np.zeros(len(prices.index)), index=prices.index, columns = ['val'])
    df_trades.values[:, :] = 0
    current = 0
    my_window = 20
    BB = bollinger_band(prices, window=my_window, show_pic=False)
    SMA = simple_moving_average(prices, window=my_window, show_pic=False)
    EMA = exponential_moving_average(prices, window=my_window, show_pic=False)
    # print [x for x in BB if x > 1 or x < -1]
    for i in range(my_window, len(prices.index)):
        if SMA[i] < -0.1:
            df_trades.values[i, :] = 1000 - current
            current = 1000
        elif SMA[i] > 0.1:
            df_trades.values[i, :] = -1000 - current
            current = -1000

    return df_trades
예제 #4
0
파일: main.py 프로젝트: walg/Projects
def main():
    '''main function'''
    #reads in list of stock dates, their corresponding prices and stock symbol
    dates, prices, symbol = _make_valid_request()

    #reads in signal strategy and the number of days back to assess
    signal_strategy = _get_signal_strategy()
    days = _get_number_of_days_back()

    #finds list of averages and list of strategies for simple moving average
    if signal_strategy == 'Simple Moving Average':
        data = indicators.simple_moving_average(days, prices).execute()
        strategies = signal_strategies.moving_average_signal(prices,
                                                             data).execute()

        #prints header and report data for simple moving average
        report = _create_report_header(symbol, signal_strategy, days)
        report += format_report(signal_strategy, dates, prices, data,
                                strategies)

    #finds list of directional indicators and strategies for directional indicators
    elif signal_strategy == 'Directional':
        positive_threshold = _get_valid_threshold('positive')
        negative_threshold = _get_valid_threshold('negative')
        data = indicators.directional_indicator(days, prices).execute()
        strategies = signal_strategies.directional_signal(
            prices, data, positive_threshold, negative_threshold).execute()

        #prints header and report data for directional indicators
        report = _create_report_header(symbol, signal_strategy, days,
                                       positive_threshold, negative_threshold)
        report += format_report(signal_strategy, dates, prices, data,
                                strategies)

    print(report)
def testPolicy(symbol='JPM',
               sd=dt.datetime(2008, 1, 1),
               ed=dt.datetime(2009, 12, 31),
               sv=100000):
    prices = get_data([symbol], pd.date_range(sd, ed))
    prices = prices[symbol]
    df_trades = pd.DataFrame(data=np.zeros(len(prices.index)),
                             index=prices.index,
                             columns=['val'])

    current = 0
    my_window = 20
    BB = bollinger_band(prices, window=my_window, show_pic=False)
    SMA = simple_moving_average(prices, window=my_window, show_pic=False)
    EMA = exponential_moving_average(prices, window=my_window, show_pic=False)

    # Manual Strategy using Simple Moving Average
    for i in range(my_window, len(prices.index)):
        # Smaller than threshold -> buy
        # Bigger than threshold -> sell
        if SMA[i] < -0.1:
            df_trades['val'].iloc[i] = 1000 - current
            current = 1000
        elif SMA[i] > 0.1:
            df_trades['val'].iloc[i] = -current - 1000
            current = -1000

    return df_trades
예제 #6
0
파일: main.py 프로젝트: walg/Projects
def main():
    '''main function'''
    #reads in list of stock dates, their corresponding prices and stock symbol
    dates,prices,symbol = _make_valid_request()

    #reads in signal strategy and the number of days back to assess
    signal_strategy = _get_signal_strategy()
    days = _get_number_of_days_back()

    #finds list of averages and list of strategies for simple moving average
    if signal_strategy == 'Simple Moving Average':
        data = indicators.simple_moving_average(days,prices).execute()
        strategies = signal_strategies.moving_average_signal(prices, data).execute()

        #prints header and report data for simple moving average
        report = _create_report_header(symbol, signal_strategy, days)
        report += format_report(signal_strategy,dates,prices,data,strategies)

                                       
    #finds list of directional indicators and strategies for directional indicators
    elif signal_strategy == 'Directional':
        positive_threshold = _get_valid_threshold('positive')
        negative_threshold = _get_valid_threshold('negative')
        data = indicators.directional_indicator(days,prices).execute()
        strategies = signal_strategies.directional_signal(prices, data,positive_threshold,negative_threshold).execute()      

        #prints header and report data for directional indicators
        report = _create_report_header(symbol,signal_strategy, days, positive_threshold,negative_threshold)
        report += format_report(signal_strategy,dates,prices,data,strategies)

    print(report)
def main():
    '''main function'''
    while True:
        symbol = input('Please enter the ticker symbol of the stock you want to search: ')
        print()
        while True:
            start_date = input('Please enter the start date of the analysis in the following format:\nYYYY-MM-DD\n')
            if _D_.check_date(start_date) == True:
                if _D_.date_to_days(start_date) <= _D_.date_of_today():
                    break
                print("Error. The start date should be on or before today's date. Please try again.")
            print()
        print()
        while True:
            end_date = input('Please enter the end date:\nYYYY-MM-DD\n')
            if _D_.check_date(end_date) == True:
                if _D_.date_to_days(start_date) <= _D_.date_to_days(end_date):
                    if _D_.date_to_days(end_date) <= _D_.date_of_today():
                        break
                    else:
                        print("Error. The end date should be on or before today's date. Please try again.")
                else:
                    print('Error. The end date should be later than the start date. Please try again.')
        print()
        if webwork.data(symbol, start_date, end_date) != False:
            data_list = webwork.data(symbol, start_date, end_date)
            command = input(Menu)
            if command.upper() == 'A':
                N = int(input('Please enter the range of moving average: '))
                indicator = indicators.simple_moving_average(data_list, N)
                signal = signals.sm_signal(data_list, N, indicator.cal())
                print()
                print('SYMBOL: {}\nSTRATEGY: Simple moving average ({}-day)\n'.format(symbol, N))
                print_information_s(data_list, N, indicator.cal(), signal.cal())
                break
            elif command.upper() == 'B':
                N = int(input('Please enter the range of directional indicator: '))
                while True:
                    buy_threshold = int(input('Please enter the buy threshold: '))
                    sell_threshold = int(input('Please enter the sell threshold: '))
                    if buy_threshold > sell_threshold:
                        break
                    else:
                        print('Error. The buy threshold should be larger than the sell threshold. Please try again.\n')
                indicator = indicators.directional(data_list, N)
                signal = signals.dir_signal(indicator.cal(), buy_threshold, sell_threshold)
                print()
                print('SYMBOL: {}\nSTRATEGY: Directional ({}-day), buy above {}, sell below {}\n'.format(symbol, N, '%+d'%buy_threshold, sell_threshold))
                print_information_d(data_list, N, indicator.cal(), signal.cal())
                break
            else:
                invalid_command(command)
        print('Please try again.\n')
예제 #8
0
    def _compute_indicators(self):
        price = self._stock_data.price
        high = self._stock_data.high
        low = self._stock_data.low
        volume = self._stock_data.volume

        mtm = momentum(price, self._lookback)
        sma, sma_ratio = simple_moving_average(price, self._lookback)
        bbands = bollinger_bands(price, sma, self._lookback)
        mfi = money_flow_index(price, high, low, volume, self._lookback)

        self._indicators = self._discretize((mtm, sma_ratio, bbands, mfi))
예제 #9
0
    def testPolicy(self, symbol = "IBM", \
        sd=datetime.datetime(2009,1,1), \
        ed=datetime.datetime(2010,1,1), \
        sv = 10000):

        current_holding = 0

        dates = pd.date_range(sd, ed)
        prices_all = ut.get_data([symbol], dates)  # automatically adds SPY
        trades = prices_all[[
            symbol,
        ]].copy(deep=True)  # only portfolio symbols
        trades_SPY = prices_all['SPY']  # only SPY, for comparison later

        window_size = self.window_size
        feature_size = self.feature_size

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

        SMA = simple_moving_average(prices, window=window_size, show_pic=False)
        BB = bollinger_band(prices, window=window_size, show_pic=False)
        EMA = exponential_moving_average(prices,
                                         window=window_size,
                                         show_pic=False)

        trades.values[:, :] = 0
        Xtest = []
        for i in range(window_size + feature_size + 1, len(prices) - 1):
            data = np.concatenate(
                (SMA[i - feature_size:i], BB[i - feature_size:i],
                 EMA[i - feature_size:i]))
            Xtest.append(data)

        res = self.learner.query(Xtest)
        for i, r in enumerate(res):
            if r > 0:
                # Buy signal
                trades.values[i + window_size + feature_size +
                              1, :] = 1000 - current_holding
                current_holding = 1000
            elif r < 0:
                # Sell signal
                trades.values[i + window_size + feature_size +
                              1, :] = -1000 - current_holding
                current_holding = -1000

        if self.verbose: print type(trades)  # it better be a DataFrame!
        if self.verbose: print trades
        if self.verbose: print prices_all

        return trades
예제 #10
0
    def testPolicy(self,
                   symbol="IBM",
                   sd=dt.datetime(2009, 1, 1),
                   ed=dt.datetime(2010, 1, 1),
                   sv=10000):

        current_holding = 0
        dates = pd.date_range(sd, ed)
        prices_all = ut.get_data([symbol], dates)
        trades = prices_all[[
            symbol,
        ]].copy(deep=True)

        window_size = self.window_size
        num_feature = self.idt_size

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

        # Indicator 1: simple moving average
        indi_val = indi.simple_moving_average(prices, window_size=window_size)

        # Indicator 2: bollinger_band
        #indi_val = indi.bollinger_band(prices, window_size=window_size)

        # Indicator 3: momentum
        #indi_val = indi.momentum(prices, window_size=window_size)

        trades.values[:, :] = 0
        Xtest = []

        for i in range(window_size + num_feature + 1, len(prices) - 1):
            data = np.array(indi_val[i - num_feature:i])
            Xtest.append(data)

        result = self.learner.query(Xtest)
        for i, r in enumerate(result):
            if r > 0:
                trades.values[i + window_size + num_feature +
                              1, :] = 1000 - current_holding
                current_holding = 1000
            elif r < 0:
                trades.values[i + window_size + num_feature +
                              1, :] = -1000 - current_holding
                current_holding = -1000

        return trades
예제 #11
0
 def execute(self, stocks:list) -> dict:
     ''' Generates a BUY or SELL signal and returns the result in
         a dictionary.
     '''
     sma_indicator = indicators.simple_moving_average(self._days)
     stock_indicators = sma_indicator.execute(stocks)
     signals = {}
     for index in range(len(stocks)):
         if index < self._days:
             signals[stocks[index].Date] = ''
         elif stock_indicators[stocks[index - 1].Date] != '':
             if (float(stocks[index].Close) > float(stock_indicators[stocks[index].Date])) and (float(stocks[index - 1].Close) < float(stock_indicators[stocks[index - 1].Date])):
                 signals[stocks[index].Date] = 'BUY'
             elif (float(stocks[index].Close) < float(stock_indicators[stocks[index].Date])) and (float(stocks[index - 1].Close) > float(stock_indicators[stocks[index - 1].Date])):
                 signals[stocks[index].Date] = 'SELL'
             else:
                 signals[stocks[index].Date] = ''
         else:
             signals[stocks[index].Date] = ''
     return signals
def testPolicy(symbol = 'JPM', sd = dt.datetime(2008, 1, 1), ed = dt.datetime(2009, 12, 31), sv = 100000):
    prices = get_data([symbol], pd.date_range(sd, ed))
    prices = prices[symbol]
    df_trades = pd.DataFrame(data=np.zeros(len(prices.index)), index=prices.index, columns = ['val'])

    current = 0
    window_size = 20

    sma = indi.simple_moving_average(prices, window_size=window_size)
    for i in range(window_size, len(prices.index)):
        # the threshold here is 0.1
        # Smaller than threshold -> buy
        # Bigger than threshold -> sell
        if sma[i] < -0.1:
            df_trades['val'].iloc[i] = 1000 - current
            current = 1000
        elif sma[i] > 0.1:
            df_trades['val'].iloc[i] = - current - 1000
            current = -1000

    return df_trades
예제 #13
0
    def addEvidence(self, symbol = "IBM", \
        sd=datetime.datetime(2008,1,1), \
        ed=datetime.datetime(2009,1,1), \
        sv = 10000):

        window_size = self.window_size
        feature_size = self.feature_size
        # N day return (predict the N-day return)
        N = self.N
        # threshold to determine whether it's a buy signal or a sell signal or nothing
        threshold = max(0.03, 2 * self.impact)

        prices = ut.get_data([symbol], pd.date_range(sd, ed))
        prices = prices[symbol]
        SMA = simple_moving_average(prices, window=window_size, show_pic=False)
        BB = bollinger_band(prices, window=window_size, show_pic=False)
        EMA = exponential_moving_average(prices,
                                         window=window_size,
                                         show_pic=False)

        X = []
        Y = []
        for i in range(window_size + feature_size + 1, len(prices) - N):
            # X will be a feature_size * 3 dimension data (concatenate three indicators as feature)
            X.append(
                np.concatenate(
                    (SMA[i - feature_size:i], BB[i - feature_size:i],
                     EMA[i - feature_size:i])))
            ret = (prices.values[i + N] - prices.values[i]) / prices.values[i]
            if ret > threshold:
                Y.append(1)
            elif ret < -threshold:
                Y.append(-1)
            else:
                Y.append(0)

        X = np.array(X)
        Y = np.array(Y)
        self.learner.addEvidence(X, Y)
예제 #14
0
def menu() -> None:
    '''Menu for program
    '''
    while True:
        symbol = _get_symbol()
        start_date = _get_start_date()
        end_date = _get_end_date(start_date)
        strategy = _strategy_choice()
        days = _get_days()
        buy = 0
        sell = 0
        try:
            stocks = download_quotes.get_quotes(symbol, start_date, end_date)
            break
        except:
            print('Could not download stock quotes!')
    indicator = ''
    signal = ''
    indicator_result = ''
    signal_result = ''
    if strategy == 'Directional':
        print('Buy threshold')
        buy = _get_threshold()
        print('Sell threshold')
        sell = _get_threshold()
        indicator = indicators.directional(days)
        signal = signals.directional(days, buy, sell)
        indicator_result = indicator.execute(stocks)
        signal_result = signal.execute(stocks)
    else:
        indicator = indicators.simple_moving_average(days)
        signal = signals.simple_moving_average(days)
        indicator_result = indicator.execute(stocks)
        signal_result = signal.execute(stocks)
    _print_report(symbol, strategy, days, buy, sell, stocks, indicator_result,
                  signal_result)
    return None
def menu() -> None:
    '''Menu for program
    '''
    while True:
        symbol = _get_symbol()
        start_date = _get_start_date()
        end_date = _get_end_date(start_date)
        strategy = _strategy_choice()
        days =_get_days()
        buy = 0
        sell = 0
        try:
            stocks = download_quotes.get_quotes(symbol, start_date, end_date)
            break
        except:
            print('Could not download stock quotes!')
    indicator = ''
    signal = ''
    indicator_result = ''
    signal_result = ''
    if strategy == 'Directional':
        print('Buy threshold')
        buy = _get_threshold()
        print('Sell threshold')
        sell = _get_threshold()
        indicator = indicators.directional(days)
        signal = signals.directional(days, buy, sell)
        indicator_result = indicator.execute(stocks)
        signal_result = signal.execute(stocks)
    else:
        indicator = indicators.simple_moving_average(days)
        signal = signals.simple_moving_average(days)
        indicator_result = indicator.execute(stocks)
        signal_result = signal.execute(stocks)
    _print_report(symbol, strategy, days, buy, sell, stocks, indicator_result, signal_result)
    return None