Ejemplo n.º 1
0
def test_debug_fixerio():
    """ Debug fixerio download for currencies """

    # pricedb dl -a fixerio -f symbols-fixerio-eur.txt -c eur
    app = PriceDbApplication()
    result = app.download_price("AUD", "EUR", "fixerio")
    assert result is not None
Ejemplo n.º 2
0
def test_dl_bnd():
    """ download BND quote """
    app = PriceDbApplication()
    price = app.download_price("NYSEARCA:VTI", "USD", "morningstar")
    assert price
    price = app.download_price("NYSEARCA:BND", "USD", "morningstar")
    assert price
 def get_last_available_price(self) -> PriceModel:
     """ Finds the last available price for security. Uses PriceDb. """
     price_db = PriceDbApplication()
     symbol = SecuritySymbol(self.security.namespace,
                             self.security.mnemonic)
     result = price_db.get_latest_price(symbol)
     return result
Ejemplo n.º 4
0
def add_price_for_yesterday(session):
    """ Create a price entry for test(s) """
    value = Decimal("1.0548")

    app = PriceDbApplication(session=session)

    datum = Datum()
    datum.yesterday()

    symbol = SecuritySymbol("VANGUARD", "BOND")

    model = PriceModel()
    model.currency = "AUD"
    model.datum = datum
    model.symbol = symbol
    model.value = value

    app.add_price(model)

    # make sure that the price is there
    first = app.price_repo.query.first()
    assert first

    yesterday_str = datum.to_iso_date_string()
    assert first.date == yesterday_str

    assert first.currency == "AUD"
    assert first.value == 10548
    assert first.denom == 10000
Ejemplo n.º 5
0
    def get_latest_price(self, security: Commodity) -> PriceModel:
        """ Returns the latest available price for commodity """
        assert isinstance(security, Commodity)

        symbol = SecuritySymbol(security.namespace, security.mnemonic)
        prices = PriceDbApplication()
        result = prices.get_latest_price(symbol)
        return result
Ejemplo n.º 6
0
def test_dl_prices_for_currency(session):
    """ See if only prices for USD get downloaded.
    Testing the securities filter.
    """
    # TODO add at least one symbol with USD currency to the in-memory database first

    app = PriceDbApplication(session=session)
    app.download_prices(currency="USD")
Ejemplo n.º 7
0
def import_csv(filepath: str, currency: str):
    """ Import prices from CSV file """
    logger.debug(f"currency = {currency}")
    # auto-convert to uppercase.
    currency = currency.upper()

    app = PriceDbApplication()
    app.logger = logger
    app.import_prices(filepath, currency)
    def get_prices(self) -> List[PriceModel]:
        """ Returns all available prices for security """
        # return self.security.prices.order_by(Price.date)
        from pricedb.dal import Price

        pricedb = PriceDbApplication()
        repo = pricedb.get_price_repository()
        query = (repo.query(Price).filter(
            Price.namespace == self.security.namespace).filter(
                Price.symbol == self.security.mnemonic).orderby_desc(
                    Price.date))
        return query.all()
Ejemplo n.º 9
0
    def load_currency(self, mnemonic: str):
        """ load the latest rate for the given mnemonic; expressed in the base currency """
        # , base_currency: str <= ignored for now.
        if self.rate and self.rate.currency == mnemonic:
            # Already loaded.
            return

        app = PriceDbApplication()
        # TODO use the base_currency parameter for the query #33
        symbol = SecuritySymbol("CURRENCY", mnemonic)
        self.rate = app.get_latest_price(symbol)
        if not self.rate:
            raise ValueError(f"No rate found for {mnemonic}!")
Ejemplo n.º 10
0
def display(model: SecurityDetailsViewModel):
    """ Format and display the results """
    # header
    #print("    security            quantity  ")
    #print("-------------------------------------------------------")
    print(f"{model.security.fullname}")

    #shares = agg.get_num_shares()

    print(f"{model.security.namespace}:{model.security.mnemonic}, shares: {model.quantity:,.2f}")

    # todo add all the info from the security details page in web ui,
    # prices, etc.
    # avg_price = agg.get_avg_price()
    #currency = agg.get_currency()
    currency = model.currency
    print(f"Average price: {model.average_price:.2f} {currency}")

    # last price
    prices_app = PriceDbApplication()
    sec_symbol = SecuritySymbol("", "")
    sec_symbol.parse(model.symbol)
    latest_price = prices_app.get_latest_price(sec_symbol)
    latest_price_date = latest_price.datum.to_iso_date_string()
    logging.debug(latest_price)
    print(f"Latest price: {latest_price.value:.2f} {latest_price.currency} on {latest_price_date}")

    print("")

    # Income
    print("Income")
    print(f"Total: {model.income:,.2f} {model.currency}, {model.income_perc:.2f}%")
    print(f"Last 12m: {model.income_last_12m:,.2f} {model.currency}, {model.income_perc_last_12m:.2f}%")

    # Return of Capital.
    if model.return_of_capital:
        print(f"Return of capital: {model.return_of_capital:,.2f}")

    print("")

    print("Holding Accounts:")
    print("-----------------")

    for account in model.accounts:
        balance = account.get_balance()
        if balance == 0:
            # Skip empty accounts
            continue
        value = balance * latest_price.value
        print(f"{account.fullname}, {balance:,.2f} units, {value:,.2f} {latest_price.currency}")
Ejemplo n.º 11
0
    def __load_latest_prices_from_pricedb(self, symbol: SecuritySymbol) -> PriceModel:
        """
        Load security prices from PriceDb.
        Uses a separate price database that can be updated on (or from) Android.
        """
        from pricedb import PriceDbApplication

        assert isinstance(symbol, SecuritySymbol)

        session = self.__get_pricedb_session()
        price_db = PriceDbApplication(session)
        latest_price = price_db.get_latest_price(symbol)

        return latest_price
Ejemplo n.º 12
0
def test_fetching_latest(session):
    """ Test fetching the latest out of two prices """
    app = PriceDbApplication(session)
    symbol = SecuritySymbol("SOME", "SYMB")

    add_prices_for_yesterday_and_today(session, symbol)

    # Fetch the latest
    latest_price = app.get_latest_price(symbol)

    # Assert that it is for today
    assert latest_price is not None
    assert latest_price.value == Decimal("150.13")
    assert latest_price.symbol.mnemonic == symbol.mnemonic
Ejemplo n.º 13
0
def list_prices(date, currency, last):
    """ Display all prices """
    app = PriceDbApplication()
    app.logger = logger

    if last:
        # fetch only the last prices
        prices = app.get_latest_prices()
    else:
        prices = app.get_prices(date, currency)
    for price in prices:
        print(price)

    print(f"{len(prices)} records found.")
Ejemplo n.º 14
0
def prune(symbol: str, all: str):
    """ Delete old prices, leaving just the last. """
    app = PriceDbApplication()
    app.logger = logger
    count = 0

    if symbol is not None:
        sec_symbol = SecuritySymbol("", "")
        sec_symbol.parse(symbol)

        deleted = app.prune(sec_symbol)
        if deleted:
            count = 1
    else:
        count = app.prune_all()

    print(f"Removed {count} old price entries.")
Ejemplo n.º 15
0
def last(symbol: str):
    """ displays last price, for symbol if provided """
    app = PriceDbApplication()

    # convert to uppercase
    if symbol:
        symbol = symbol.upper()
        # extract namespace
        sec_symbol = SecuritySymbol("", "")
        sec_symbol.parse(symbol)

        latest = app.get_latest_price(sec_symbol)
        assert isinstance(latest, PriceModel)
        print(f"{latest}")
    else:
        # Show the latest prices available for all securities.
        latest = app.get_latest_prices()
        for price in latest:
            print(f"{price}")
Ejemplo n.º 16
0
def download(ctx, help: bool, symbol: str, namespace: str, agent: str,
             currency: str):
    """ Download the latest prices """
    if help:
        click.echo(ctx.get_help())
        ctx.exit()

    app = PriceDbApplication()
    app.logger = logger

    if currency:
        currency = currency.strip()
        currency = currency.upper()

    # Otherwise download the prices for securities listed in the database.
    app.download_prices(currency=currency,
                        agent=agent,
                        symbol=symbol,
                        namespace=namespace)
Ejemplo n.º 17
0
def test_latest_date(session):
    """
    Test fetching the latest price.
    The date is always today, even if the latest price is not from today!
    """
    # Preparation
    add_price_for_yesterday(session)

    # Fetch the latest price for xy
    app = PriceDbApplication(session=session)
    symbol = SecuritySymbol("VANGUARD", "BOND")

    latest_price = app.get_latest_price(symbol)

    assert latest_price

    yesterday = Datum()
    yesterday.yesterday()
    yesterday.start_of_day()
    yesterday_str = yesterday.to_iso_date_string()
    assert latest_price.datum.to_iso_date_string() == yesterday_str
Ejemplo n.º 18
0
def add(symbol: str, date, value, currency: str):
    """ Add individual price """
    symbol = symbol.upper()
    currency = currency.upper()

    app = PriceDbApplication()
    price = PriceModel()

    # security = SecuritySymbol("", "")
    price.symbol.parse(symbol)
    # price.symbol.mnemonic = price.symbol.mnemonic.upper()

    # date_str = f"{date}"
    # date_format = "%Y-%m-%d"
    # if time:
    #     date_str = f"{date_str}T{time}"
    #     date_format += "T%H:%M:%S"
    # datum.from_iso_date_string(date)
    # price.datetime = datetime.strptime(date_str, date_format)
    price.datum.from_iso_date_string(date)

    price.value = Decimal(value)
    price.currency = currency
    app.add_price(price)
    app.save()

    click.echo("Price added.")
Ejemplo n.º 19
0
def add_prices_for_yesterday_and_today(session, symbol: SecuritySymbol):
    """ Add prices for the same symbol for yesterday and today """
    app = PriceDbApplication(session)

    assert isinstance(symbol, SecuritySymbol)

    price = PriceModel()
    # Create price for today
    price.datum = Datum()
    price.currency = "EUR"
    price.symbol = symbol
    price.value = Decimal("150.13")
    app.add_price(price)

    # Create price for yesterday
    price.datum.yesterday()
    price.value = Decimal("50.28")
    app.add_price(price)
Ejemplo n.º 20
0
def test_namespace_parameter(session):
    """
    Test that the namespace parameter filters out appropriate symbols.
    Debugging test.
    """
    from pricedb.dal import Security

    # Arrange
    app = PriceDbApplication(session)
    repo = app.get_security_repository()
    sec = Security()
    sec.symbol = "BOND"
    sec.namespace = "VANGUARD"
    sec.updater = "vanguard_au"
    sec.currency = "AUD"
    repo.session.add(sec)

    # Act
    app.download_prices(namespace="vanguard")

    # Assert
    prices = app.get_latest_prices()
    assert prices
    
Ejemplo n.º 21
0
""" Test Morningstar downloader """
from pricedb import PriceDbApplication
from pydatum import Datum
from decimal import Decimal

app = PriceDbApplication()


def test_date():
    """ Test the price date """
    price = app.download_price("ASX:VTS", "AUD", "morningstar")

    assert price is not None
    assert price.value > Decimal(0)
    #assert price.datum.time.hour == 0
    #assert price.datum.time.minute == 0
    #assert price.datum.time.second == 0
Ejemplo n.º 22
0
 def get_price_as_of(self, stock: Commodity, on_date: datetime):
     """ Gets the latest price on or before the given date. """
     # return self.get_price_as_of_query(stock, on_date).first()
     prices = PriceDbApplication()
     prices.get_prices_on(on_date.date().isoformat(), stock.namespace,
                          stock.mnemonic)
Ejemplo n.º 23
0
def test_download_using_symbols_in_db():
    """ Download the prices that are listed in db.
    Used for debugging
    """
    app = PriceDbApplication()
    app.download_prices()
Ejemplo n.º 24
0
def test_latest_prices():
    """ Get the latest prices """
    app = PriceDbApplication()
    latest = app.get_latest_prices()

    assert latest is not None
Ejemplo n.º 25
0
def test_debug_aud_morningstar():
    """ Debug download for aud quote """
    app = PriceDbApplication()
    result = app.download_price("ASX:AEF", "AUD", "morningstar")
    assert result is not None
Ejemplo n.º 26
0
def download_bnd():
    app = PriceDbApplication()
    #price = app.download_price("NYSEARCA:VTI", "USD", "morningstar")
    price = app.download_price("NYSEARCA:BND", "USD", "morningstar")
    assert price