class TheHood: """ A wrapper for producing the kinds of transactions and calls on my Robinhood portfolio I'm looking for. """ def __init__(self, credentials: str) -> None: self._ext_equity = 0.0 # Set up connection to Robinhood's API. self._rh = Robinhood() self._rh.login(**read_credentials(credentials)) @property def extended_hours_equity(self) -> float: """ Keep track of the extended equity and prevent its setting to NoneType. Returns: The current extended equity. """ return self._ext_equity @extended_hours_equity.setter def extended_hours_equity(self, new_equity: Union[float, None]) -> None: """ Keep track of the extended equity and prevent its setting to NoneType. Returns: The current extended equity. """ if type(new_equity) is not float: pass else: self._ext_equity = new_equity @retry def total_dollar_equity(self) -> Tuple[float, float, float]: """ Get values that explain the current monetary value of my account. Returns: A tuple containing today's closing equity in my account, followed by the previous day's closing value and the current extended / after-hours value. """ self.extended_hours_equity = self._rh.extended_hours_equity() return self._rh.equity(), self._rh.equity_previous_close( ), self.extended_hours_equity @retry def account_potential(self) -> float: """ Get the total account potential for comparison against the total account value. I define account potential as the sum of all stocks' current worth plus the absolute value of any losses. Returns: A float representing the account potential. """ stocks = self._rh.securities_owned()['results'] potential_sum = float(self._rh.portfolios()['withdrawable_amount']) for stock in stocks: # Make quantity a float as the API may change when I buy fractional shares. quantity = float(stock['quantity']) buy_price = float(stock['average_buy_price']) potential_sum += quantity * buy_price return potential_sum @retry def dividend_payments(self, since: str = '') -> float: """ If there are dividend payments, I want to graph a sum in Grafana. Args: since: the date since we should allow the summation of dividends. For instance, you may wish to set this to the past year. Returns: A float representing the sum of dividend payments to my account. """ dividends: Dict = self._rh.dividends()['results'] dividend_sum = 0.0 for dividend in dividends: if dividend['state'] == 'paid': if since and not (datetime.fromisoformat( dividend['paid_at'][:-1]) > datetime.fromisoformat(since)): continue dividend_sum += float(dividend['amount']) return dividend_sum
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