Ejemplo n.º 1
0
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
Ejemplo n.º 2
0
except:
    print("[ERROR] login to webull failed.")

# Robinhood Current Portfolio Value
print("===Robinhood Portfolio Value===")
print(f"Cash  : ${rh.portfolios()['withdrawable_amount']}"
      )  #!!! DOUBLE-CHECK: Seems to update slow
print(f"Stocks: ${rh.portfolios()['market_value']}")
print(f"Total : ${rh.portfolios()['equity']}")
print("")

# Stocks Owned in Robinhood
# TODO: Print in table format instead
print("===My Robinhood Stocks===")
rh_stocks = []
for s in rh.securities_owned()['results']:
    sample_instrument = rh.get_url(s['instrument'])
    print(f"Name  : {sample_instrument['simple_name']}")
    print(f"Symbol: {sample_instrument['symbol']}")
    print(f"Shares: {s['quantity']}")
    #print(f"Average Cost: {s['average_buy_price']}")
    rh_stocks.append(sample_instrument['symbol'])
    print("")

# Webull Current Portfolio Value
print("===Webull Portfolio Value===")
print(f"Cash  : ${wb.get_account()['accountMembers'][1]['value']}")
print(f"Stocks: ${wb.get_account()['accountMembers'][0]['value']}")
print(f"Total : ${wb.get_account()['netLiquidation']}")
print("")