Ejemplo n.º 1
0
 def add_security(self, security: Security) -> None:
     """
     Adds the given security to this asset class.
     """
     sec_id: str = security.get_id()
     if not self.contains_security(sec_id):
         self.__securities[sec_id] = security
     else:
         raise Exception("add_security(): {} was already added to the '{}'"
                         "asset class.".format(sec_id, self.get_name()))
Ejemplo n.º 2
0
    def buy(self, security: Security, num_shares: int, online: bool) -> str:
        """
        Adds num_shares of the given security to the holdings of this asset
        class. Returns the state of the buy transaction.
        """
        price: Optional[float] = security.get_price()
        if price is None:
            raise Exception("Can't buy security with undefined price")
        security_id: str = security.get_id()
        if self.contains_holding(security_id):
            hol: Holding = self.get_holding(security_id)
            old_num_shares: int = hol.get_num_shares()
            old_abp: float = hol.get_average_buy_price()
            old_div: float = hol.get_dividends()
            new_num_shares: int = old_num_shares + num_shares
            new_abp: float = (old_abp * old_num_shares + price *
                              num_shares) / (old_num_shares + num_shares)
            self.update_holding(security_id, new_num_shares, new_abp, old_div)
        else:
            self.update_holding(security_id, num_shares, price, 0.0)

        log.info("Buy {n} {s} of {c} at {p} for a total of {t}? (Y/n) ".format(
            n=num_shares,
            s="shares" if num_shares > 1 else "share",
            c=security.get_symbol(),
            p=dollar_str(price),
            t=dollar_str(price * num_shares),
        ))
        order_state: str = "confirmed"
        if online:
            # Actually buy the ETFs
            user_choice: str = input("").lower()
            if user_choice in ["", "y"]:
                resp: Dict[str,
                           Any] = r.order_buy_limit(security.get_symbol(),
                                                    num_shares,
                                                    security.get_price())
                if resp is None:
                    order_state = "failed"
                else:
                    order_state = resp["state"]
        return order_state