예제 #1
0
def test_for_dataset_psar(acc_step, acc_max, file_name,
                          should_display_metric_visuals):
    # load data
    with open(file_name, 'r') as history_json_file:
        history = json.load(history_json_file)

    print('Loaded ' + str(len(history['Data'])) + ' minutes of currency data.')

    # Create the pandas DataFrames for price time-series fields
    price_df = pd.DataFrame(history['Data'])
    price_open = price_df['open'].tolist()
    price_close = price_df['close'].tolist()
    price_high = price_df['high'].tolist()
    price_low = price_df['low'].tolist()

    print('History data frame loaded')

    # Create numpy array
    price_list_np_array = np.array(price_open)

    # Expose info about tulip indicator for
    tulip_util.print_info(ti.rsi)
    tulip_util.print_info(ti.psar)

    # Try out tulip indicator on numpy array
    rsi = ti.rsi(price_list_np_array, 120)

    # high_low = np.array([price_high, price_low], np.int32)
    price_high_np = np.array(price_high)
    price_low_np = np.array(price_low)

    # Run PSAR
    psar = ti.psar(high=price_high_np,
                   low=price_low_np,
                   acceleration_factor_step=acc_step,
                   acceleration_factor_maximum=acc_max)

    # Calculate total potential gains of time-series
    print("Total potential gains: " +
          str(test_util.calculate_potential_gains(price_df)))

    # Run desired test
    # test_metrics_instance = run_test.run_test(60, price_open)
    test_metrics_instance = run_test_psar.run_test(
        price_open, price_high_np, price_low_np, acc_step, acc_max,
        detect_buy_sar.detect_buy_sar, detect_sell_sar.detect_sell_sar)
    # detect_buy_psar_updated.detect_buy_sar_updated,
    # detect_sell_psar_updated.detect_sell_sar_updated)

    # test_metrics_instance = run_test_sequential.run_test_sequential(price_df, acc_step, acc_max)

    if should_display_metric_visuals:
        display_metrics(test_metrics_instance, price_open, psar,
                        should_display_metric_visuals)

    return test_metrics_instance
예제 #2
0
파일: sar.py 프로젝트: muibast/crypto-bot
 def calculate(self, candles):        
     candles_len = len(candles)
     if candles_len < self.period:
         return 0
     
     high_array = np.array([float(x['ohlc'].high) for x in candles[-self.period:]])
     low_array = np.array([float(x['ohlc'].low) for x in candles[-self.period:]])
     
     #calculate 
     sar = ti.psar (high_array, low_array)
     
     return sar[-1]
예제 #3
0
    def inds(self):

        Indicators = {}

        for i in range(len(self.time)):
            #i/o?
            ''' 2 = High, 3 = Low, 4 = Close, 5 = Volume
            collects the needed market data into one list to push to the indicators'''
            close = self.time[i][4].values.copy(order='C')
            high = self.time[i][2].values.copy(order='C')
            low = self.time[i][3].values.copy(order='C')
            volume = self.time[i][5].values.copy(order='C')
            # !!!This needs to be changed. Each volume of the base time must be indexed up to the slice
            __time = self.time[i][6]

            # these are the indicators currently being used, and recored
            Indicators[i] = {
                'stochrsi': ti.stochrsi(close, 5),
                'rsi': ti.rsi(close, 5),
                # indicators that need to be doublechecked
                'mfi': ti.mfi(high, low, close, volume, 5),
                'sar': ti.psar(high, low, .2, 2),
                'cci': ti.cci(high, low, close, 5),
                'ema': ti.ema(close, 5)
            }
            # this one is good
            Indicators[i]['stoch_k'], Indicators[i]['stoch_d'] = ti.stoch(
                high, low, close, 5, 3, 3)

            # check on this, to see if it functions properly
            Indicators[i]['bbands_lower'], Indicators[i]['bbands_middle'],
            Indicators[i]['bbands_upper'] = ti.bbands(close, 5, 2)

            Indicators[i]['macd'], Indicators[i]['macd_signal'],
            Indicators[i]['macd_histogram'] = ti.macd(close, 12, 26, 9)

            Indicators[i]['time'] = __time
            Indicators[i]['close'] = close
            ''' below changes the length of each array to match the longest one, for a pandas df
             np.nan for the tail of the shorter ones'''
            Indicators[i] = to_pd(Indicator=Indicators[i]).dropna(how='all')
        return Indicators
예제 #4
0
def run_test(price_list, price_high_np, price_low_np, acc_step, acc_max,
             detect_buy_sar, detect_sell_sar):

    # Begin detecting buy/sell, examining plots of 30 seconds
    # Initialize variables
    holding = False
    buys = []
    sells = []
    holding_indices = []
    last_buy_price = 0
    num_buys = 0
    num_sells = 0
    profit = 0
    fees = 0

    # Crunch PSAR
    psar = ti.psar(high=price_high_np,
                   low=price_low_np,
                   acceleration_factor_step=acc_step,
                   acceleration_factor_maximum=acc_max)

    # Begin iteration
    for ind, val in enumerate(price_list):
        # Ensure that we have passed the minimum for psar measurements
        if (ind <= acc_step):
            continue

        # Record the times during which we are holding
        if (holding == True):
            holding_indices.append(ind)

        # If we aren't holding, detect whether or not to buy
        if (holding == False):
            execute_buy = detect_buy_sar(psar[ind - 1], price_list[ind - 1])
            if (execute_buy):
                holding = True
                last_buy_price = price_list[ind]

                # # Account for trading fees ($2.99 ex on coinbase for traces > $100)
                # profit -= 3;

                # Account for Kraken trading fees (.26% for takers on Kraken)
                fees += price_list[ind] * .00075
                num_buys += 1

                buys.append(ind)
        # Else if we are holding, detect when to sell
        else:
            execute_sell = detect_sell_sar(psar[ind - 1], price_list[ind - 1])
            if (execute_sell):
                holding = False
                profit += price_list[ind] - last_buy_price

                # # Account for trading fees ($2.99 ex on coinbase for traces > $100)
                # profit -= 3;

                # Account for Kraken trading fees (.16% for makers on Kraken)
                fees += price_list[ind] * .00075
                num_sells += 1

                sells.append(ind)

    test_metrics_instance = TestMetrics()
    test_metrics_instance.buys = buys
    test_metrics_instance.sells = sells
    test_metrics_instance.holding_indices = holding_indices
    test_metrics_instance.num_buys = num_buys
    test_metrics_instance.num_sells = num_sells
    test_metrics_instance.profit = profit
    test_metrics_instance.fees = fees
    test_metrics_instance.holding_profit = price_list[len(price_list) -
                                                      1] - price_list[0]

    return test_metrics_instance
예제 #5
0
        # Add current values to value history
        ticker_low_history = test_util.add_to_ticker_history_np(
            ticker_low_history, current_low, history_length)
        ticker_bid_history = test_util.add_to_ticker_history_np(
            ticker_bid_history, current_bid, history_length)
        ticker_high_history = test_util.add_to_ticker_history_np(
            ticker_high_history, current_high, history_length)

        # Ensure that we have passed the minimum for psar measurements
        if (len(ticker_bid_history) <= 10):  #TODO 10 is arbitrary
            continue

        # Calculate PSAR for history
        psar = ti.psar(high=ticker_high_history,
                       low=ticker_low_history,
                       acceleration_factor_step=acc_step,
                       acceleration_factor_maximum=acc_max)

        if (holding == False):
            # Detect PSAR for most recent x values
            execute_buy = detect_buy_sar.detect_buy_sar(
                psar[len(psar) - 1], current_bid)
            if (execute_buy):
                holding = True
                print('Executing buy at: ' + str(current_bid))
                last_buy_price = current_bid

                # Account for trading fees
                fees += current_bid * .00075
                num_buys += 1
        else:
예제 #6
0
def run_test_sequential(price_df, acc_step, acc_max):

    # Begin detecting buy/sell, examining plots of 30 seconds
    # Initialize variables
    holding = False
    buys = []
    sells = []
    holding_indices = []
    last_buy_price = 0
    profit = 0

    # Create the running lists for all needed metrics
    price_open = price_df['open'].tolist()
    price_close = price_df['close'].tolist()
    price_high = price_df['high'].tolist()
    price_low = price_df['low'].tolist()

    # Create running price list
    running_open_list = [];
    running_close_list = [];
    running_high_list = [];
    running_low_list = [];

    # Begin iteration
    for ind, val in enumerate(price_open):
        # Capture current price
        current_price = price_open[ind]
        running_open_list.append(current_price)
        running_close_list.append(price_close[ind])
        running_high_list.append(price_high[ind])
        running_low_list.append(price_low[ind])

        # Ensure that we have passed the minimum for psar measurements
        if(ind <= acc_step):
            continue

        # Prepare np arrays for current PSAR inputs
        price_high_np = np.array(price_high);
        price_low_np = np.array(price_low);

        # Crunch PSAR for the info we currently know
        psar = ti.psar(high=price_high_np, low=price_low_np, acceleration_factor_step=acc_step,
                       acceleration_factor_maximum=acc_max)

        # Record the times during which we are holding
        if(holding == True):
            holding_indices.append(ind)

        # If we aren't holding, detect whether or not to buy
        if(holding == False):
            execute_buy = detect_buy_sar.detect_buy_sar(psar[ind - 1], running_open_list[ind - 1])
            if(execute_buy):
                holding = True
                last_buy_price = running_open_list[ind]
                buys.append(ind)
        # Else if we are holding, detect when to sell
        else:
            execute_sell = detect_sell_sar.detect_sell_sar(psar[ind - 1], running_open_list[ind - 1])
            if (execute_sell):
                holding = False
                profit += running_open_list[ind] - last_buy_price
                sells.append(ind)

    test_metrics_instance = test_metrics.TestMetrics()
    test_metrics_instance.buys = buys
    test_metrics_instance.sells = sells
    test_metrics_instance.holding_indices = holding_indices
    test_metrics_instance.profit = profit

    return test_metrics_instance
예제 #7
0
    def evaluate_and_execute_trade(self):
        # Initialize Alpaca API
        os.environ["APCA_API_BASE_URL"] = "https://paper-api.alpaca.markets"
        # Insert API Credentials
        api = tradeapi.REST(constants.ALPACA_KEY,
                            constants.ALPACA_SECRET_KEY,
                            api_version='v2')
        account = api.get_account()

        # The mail addresses and password
        sender_address = constants.SENDER_EMAIL_ADDRESS
        sender_pass = constants.SENDER_EMAIL_PASSWORD
        receiver_address = constants.RECEIVING_EMAIL_ADDRESS
        # Setup the MIME
        message = MIMEMultipart()
        message['From'] = 'Ensenada'
        message['To'] = receiver_address
        message['Subject'] = 'Order activity'  # The subject line

        # Selection of stocks
        minutes = 1000
        stock = 'TSLA'
        barset = api.get_barset(stock, 'minute', limit=minutes)
        stock_bars = barset[stock]

        # Calculate PSAR
        acc_step = .02
        acc_max = .2
        price_open = stock_bars.df['open'].to_numpy()
        price_close = stock_bars.df['close'].to_numpy()
        price_high = stock_bars.df['high'].to_numpy()
        price_low = stock_bars.df['low'].to_numpy()
        psar = ti.psar(high=price_high,
                       low=price_low,
                       acceleration_factor_step=acc_step,
                       acceleration_factor_maximum=acc_max)

        # Trading_algo
        portfolio = api.list_positions()
        holding = any(x.symbol == stock for x in portfolio)
        clock = api.get_clock()

        # If markets are open
        mail_content = ""
        if clock.is_open == True:
            #If not holding
            if holding == False:
                # Detect should buy
                if detect_buy_sar.detect_buy_sar(
                        psar[len(psar) - 1],
                        price_close[price_close.size - 1]):
                    # buy 1 share
                    api.submit_order(symbol=stock,
                                     qty=1,
                                     side='buy',
                                     type='market',
                                     time_in_force='day')
                    buy_action_message = "Ordered buy of " + stock + " at " + str(
                        price_close[price_close.size - 1])
                    print(buy_action_message)
                    mail_content = buy_action_message
            # Else holding
            else:
                # Detect should sell
                if detect_sell_sar.detect_sell_sar(
                        psar[len(psar) - 1],
                        price_close[price_close.size - 1]):
                    # sell 1 share
                    api.submit_order(symbol=stock,
                                     qty=1,
                                     side='sell',
                                     type='market',
                                     time_in_force='day')
                    sell_action_message = "Sell has been ordered for" + stock + " with most recent close price " + str(
                        price_close[price_close.size - 1])
                    print(sell_action_message)
                    mail_content = sell_action_message
        else:
            print("The Market is Closed")
            mail_content = "The Market is Closed"

        # Only send mail if an action was taken
        if mail_content:
            # The body and the attachments for the mail
            message.attach(MIMEText(mail_content))
            # Create SMTP session for sending the mail
            session = smtplib.SMTP('smtp.gmail.com',
                                   587)  # use gmail with port
            session.starttls()  # enable security
            session.login(sender_address,
                          sender_pass)  # login with mail_id and password
            text = message.as_string()
            session.sendmail(sender_address, receiver_address, text)
            session.quit()