Exemplo n.º 1
0
def watcher():
    global graph_msg, graph_min, graph_max
    rh = Robinhood()
    rh.login(username=rh_user, password=rh_pass, qr_code=rh_qr)
    raw_result = rh.positions()
    result = raw_result['results']
    shares_total = []
    port_msg = f"Your portfolio ({rh.get_account()['account_number']}):\n"
    loss_output = 'Loss:'
    profit_output = 'Profit:'
    loss_total = []
    profit_total = []
    graph_msg = None  # initiates a variable graph_msg as None for looped condition below
    n = 0
    n_ = 0
    for data in result:
        share_id = str(data['instrument'].split('/')[-2])
        buy = round(float(data['average_buy_price']), 2)
        shares_count = int(data['quantity'].split('.')[0])
        if shares_count != 0:
            n = n + 1
            n_ = n_ + shares_count
        else:
            continue
        raw_details = rh.get_quote(share_id)
        share_name = raw_details['symbol']
        call = raw_details['instrument']
        share_full_name = loads(get(call).text)['simple_name']
        total = round(shares_count * float(buy), 2)
        shares_total.append(total)
        current = round(float(raw_details['last_trade_price']), 2)
        current_total = round(shares_count * current, 2)
        difference = round(float(current_total - total), 2)
        if difference < 0:
            loss_output += (
                f'\n{share_full_name}:\n{shares_count} shares of {share_name} at ${buy} Currently: ${current}\n'
                f'Total bought: ${total} Current Total: ${current_total}'
                f'\nLOST ${-difference}\n')
            loss_total.append(-difference)
        else:
            profit_output += (
                f'\n{share_full_name}:\n{shares_count} shares of {share_name} at ${buy} Currently: ${current}\n'
                f'Total bought: ${total} Current Total: ${current_total}'
                f'\nGained ${difference}\n')
            profit_total.append(difference)
        if graph_min and graph_max:
            graph_min = float(graph_min)
            graph_max = float(graph_max)
            if difference > graph_max or difference < -graph_min:
                time_now = datetime.now()
                metrics = time_now - timedelta(days=7)
                numbers = []
                historic_data = (rh.get_historical_quotes(
                    share_name, '10minute', 'week'))
                historical_values = historic_data['results'][0]['historicals']
                for close_price in historical_values:
                    numbers.append(round(float(close_price['close_price']), 2))
                fig, ax = plt.subplots()
                if difference > graph_max:
                    plt.title(
                        f"Stock Price Trend for {share_full_name}\nShares: {shares_count}  Profit: ${difference}"
                    )
                elif difference < graph_min:
                    plt.title(
                        f"Stock Price Trend for {share_full_name}\nShares: {shares_count}  LOSS: ${-difference}"
                    )
                plt.xlabel(
                    f"1 Week trend with 10 minutes interval from {metrics.strftime('%m-%d %H:%M')} to "
                    f"{time_now.strftime('%m-%d %H:%M')}")
                plt.ylabel('Price in USD')
                ax.plot(numbers, linewidth=1.5)
                if not path.isdir('img'):
                    mkdir('img')
                fig.savefig(f"img/{share_full_name}.png", format="png")
                plt.close(
                )  # close plt to avoid memory exception when more than 20 graphs are generated
                # stores graph_msg only if a graph is generated else graph_msg remains None
                if not graph_msg:  # used if not to avoid storing the message repeatedly
                    graph_msg = f"Attached are the graphs for stocks which exceeded a profit of " \
                                f"${graph_max} or deceeded a loss of ${graph_min}"
        elif not graph_msg:  # used elif not to avoid storing the message repeatedly
            graph_msg = "Add the env variables for <graph_min> and <graph_max> to include a graph of previous " \
                        "week's trend."

    lost = round(fsum(loss_total), 2)
    gained = round(fsum(profit_total), 2)
    port_msg += f'The below values will differ from overall profit/loss if shares were purchased ' \
                f'with different price values.\nTotal Profit: ${gained}\nTotal Loss: ${lost}\n'
    net_worth = round(float(rh.equity()), 2)
    output = f'Total number of stocks purchased: {n}\n'
    output += f'Total number of shares owned: {n_}\n\n'
    output += f'Current value of your total investment is: ${net_worth}\n'
    total_buy = round(fsum(shares_total), 2)
    output += f'Value of your total investment while purchase is: ${total_buy}\n'
    total_diff = round(float(net_worth - total_buy), 2)
    if total_diff < 0:
        output += f'Overall Loss: ${total_diff}'
    else:
        output += f'Overall Profit: ${total_diff}'
    yesterday_close = round(float(rh.equity_previous_close()), 2)
    two_day_diff = round(float(net_worth - yesterday_close), 2)
    output += f"\n\nYesterday's closing value: ${yesterday_close}"
    if two_day_diff < 0:
        output += f"\nCurrent Dip: ${two_day_diff}"
    else:
        output += f"\nCurrent Spike: ${two_day_diff}"
    if not graph_msg:  # if graph_msg was not set above
        graph_msg = f"You have not lost more than ${graph_min} or gained more than " \
                    f"${graph_max} to generate a graph."

    return port_msg, profit_output, loss_output, output, graph_msg
class PyrhAdapter(QSM):
    def __init__(self, name: str = 'pyrh_adapter'):
        super().__init__(name, ['pyrh_request', 'trade'])
        self.rbn = Robinhood()
        self.logged_in = False
        self.client_req = Queue()
        self.requests = Queue()
        self.request_lock = Lock()

    def setup_states(self):
        super().setup_states()
        self.mappings['login'] = self.login
        self.mappings['quote'] = self.quote
        self.mappings['buy'] = self.buy
        self.mappings['sell'] = self.sell

    def idle_state(self):
        try:
            req = self.client_req.get_nowait()
            self.append_state('pyrh_request', req)
        except Empty as _:
            pass

        super().idle_state()

    def trade_msg(self, msg: Message):
        transaction = msg.payload
        self.handler.send(
            Message('pyrh_request', 'buy' if transaction.buy else 'sell',
                    transaction))

    def pyrh_request_msg(self, msg: Message):
        if msg.msg == 'logout':
            if self.logged_in:
                self.rbn.logout()
                print("Logged out")
                self.logged_in = False
        if msg.msg == 'quote':
            if not self.logged_in:
                self.append_state('login')
            self.append_state('quote', msg.payload)
        elif msg.msg == 'buy':
            if not self.logged_in:
                self.append_state('login')
            self.append_state('buy', msg.payload)
        elif msg.msg == 'sell':
            if not self.logged_in:
                self.append_state('login')
            self.append_state('sell', msg.payload)

    def login(self):
        while True:
            user = input('Username(email): ')
            pwd = input('Password: '******'Logged in successfully')
                self.logged_in = True
                break
            print('Something went wrong, try again?')
            continue

    def quote(self, acronym: str):
        while True:
            try:
                self.requests.put(self.rbn.get_quote(acronym))
                break
            except Full as _:
                print('requests queue is full, skipping...')
                break
            except Exception as _:
                print('Something went wrong, trying again')
                time.sleep(5)

    def buy(self, descriptor: ManagedStock):
        # self.rbn.place_buy_order(self.rbn.get_quote(descriptor.acronym)['instrument'], descriptor.shares)
        print("Buying {}".format(descriptor))

    def sell(self, descriptor: ManagedStock):
        # self.rbn.place_sell_order(self.rbn.get_quote(descriptor.acronym)['instrument'], descriptor.shares)
        print("Selling {}".format(descriptor))

    def get_quote(self, acronym: str) -> dict:
        self.request_lock.acquire()
        self.client_req.put(Message('pyrh_request', 'quote', acronym))
        d = self.requests.get()
        self.request_lock.release()
        return d

    def place_buy(self, s: ManagedStock):
        self.client_req.put(Message('pyrh_request', 'buy', s))

    def place_sell(self, s: ManagedStock):
        self.client_req.put(Message('pyrh_request', 'sell', s))