Search in sources :

Example 1 with LatestSecurityPrice

use of name.abuchen.portfolio.model.LatestSecurityPrice in project portfolio by buchen.

the class HTMLTableQuoteFeed method updateLatestQuotes.

@Override
public boolean updateLatestQuotes(Security security, List<Exception> errors) {
    boolean isUpdated = false;
    // if latestFeed is null, then the policy is 'use same configuration
    // as historic quotes'
    String feedURL = security.getLatestFeed() == null ? security.getFeedURL() : security.getLatestFeedURL();
    List<LatestSecurityPrice> quotes = internalGetQuotes(security, feedURL, errors);
    int size = quotes.size();
    if (size > 0) {
        Collections.sort(quotes);
        LatestSecurityPrice latest = quotes.get(size - 1);
        LatestSecurityPrice previous = size > 1 ? quotes.get(size - 2) : null;
        latest.setPreviousClose(previous != null ? previous.getValue() : latest.getValue());
        latest.setVolume(LatestSecurityPrice.NOT_AVAILABLE);
        isUpdated = security.setLatest(latest);
    }
    return isUpdated;
}
Also used : LatestSecurityPrice(name.abuchen.portfolio.model.LatestSecurityPrice)

Example 2 with LatestSecurityPrice

use of name.abuchen.portfolio.model.LatestSecurityPrice in project portfolio by buchen.

the class YahooFinanceQuoteFeed method fillValues.

protected <T extends SecurityPrice> void fillValues(String[] values, T price, DateTimeFormatter dateFormat) throws ParseException, DateTimeParseException {
    LocalDate date = LocalDate.parse(values[CSVColumn.Date], dateFormat);
    long v = asPrice(values[CSVColumn.Close]);
    price.setDate(date);
    price.setValue(v);
    if (price instanceof LatestSecurityPrice) {
        LatestSecurityPrice latest = (LatestSecurityPrice) price;
        latest.setVolume(asNumber(values[CSVColumn.Volume]));
        latest.setHigh(asPrice(values[CSVColumn.High]));
        latest.setLow(asPrice(values[CSVColumn.Low]));
    }
}
Also used : LatestSecurityPrice(name.abuchen.portfolio.model.LatestSecurityPrice) LocalDate(java.time.LocalDate)

Example 3 with LatestSecurityPrice

use of name.abuchen.portfolio.model.LatestSecurityPrice in project portfolio by buchen.

the class AlphavantageQuoteFeed method updateLatestQuotes.

@Override
public boolean updateLatestQuotes(Security security, List<Exception> errors) {
    if (security.getTickerSymbol() == null) {
        errors.add(new IOException(MessageFormat.format(Messages.MsgMissingTickerSymbol, security.getName())));
        return false;
    }
    if (apiKey == null)
        throw new IllegalArgumentException(Messages.MsgAlphaVantageAPIKeyMissing);
    if (rateLimiter != null && !rateLimiter.tryAcquire())
        throw new RateLimitExceededException(Messages.MsgAlphaVantageRateLimitExceeded);
    String wknUrl = MessageFormat.format(// $NON-NLS-1$
    "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY" + // $NON-NLS-1$
    "&symbol={0}&interval=1min&apikey={1}&datatype=csv&outputsize=compact", security.getTickerSymbol(), apiKey);
    try {
        URL obj = new URL(wknUrl);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setConnectTimeout(1000);
        con.setReadTimeout(20000);
        int responseCode = con.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK)
            // $NON-NLS-1$
            throw new IOException(wknUrl + " --> " + responseCode);
        try (Scanner scanner = new Scanner(con.getInputStream(), StandardCharsets.UTF_8.name())) {
            // $NON-NLS-1$
            String body = scanner.useDelimiter("\\A").next();
            // $NON-NLS-1$
            String[] lines = body.split("\\r?\\n");
            if (lines.length <= 2)
                return false;
            // poor man's check
            if (// $NON-NLS-1$
            !"timestamp,open,high,low,close,volume".equals(lines[0])) {
                errors.add(new IOException(MessageFormat.format(Messages.MsgUnexpectedHeader, body)));
                return false;
            }
            String line = lines[1];
            // $NON-NLS-1$
            String[] values = line.split(",");
            if (values.length != 6)
                throw new IOException(MessageFormat.format(Messages.MsgUnexpectedValue, line));
            // $NON-NLS-1$
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LatestSecurityPrice price = new LatestSecurityPrice();
            price.setDate(LocalDate.parse(values[0], formatter));
            price.setValue(asPrice(values[4]));
            price.setHigh(asPrice(values[2]));
            price.setLow(asPrice(values[3]));
            price.setVolume(Long.parseLong(values[5]));
            price.setPreviousClose(LatestSecurityPrice.NOT_AVAILABLE);
            if (price.getValue() != 0)
                security.setLatest(price);
            return true;
        }
    } catch (IOException | ParseException e) {
        errors.add(e);
        return false;
    }
}
Also used : LatestSecurityPrice(name.abuchen.portfolio.model.LatestSecurityPrice) Scanner(java.util.Scanner) RateLimitExceededException(name.abuchen.portfolio.util.RateLimitExceededException) IOException(java.io.IOException) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) ParseException(java.text.ParseException) DateTimeFormatter(java.time.format.DateTimeFormatter)

Example 4 with LatestSecurityPrice

use of name.abuchen.portfolio.model.LatestSecurityPrice in project portfolio by buchen.

the class AlphavantageQuoteFeed method getHistoricalQuotes.

private <T extends SecurityPrice> List<T> getHistoricalQuotes(Class<T> klass, Security security, OutputSize outputSize, List<Exception> errors) {
    if (security.getTickerSymbol() == null) {
        errors.add(new IOException(MessageFormat.format(Messages.MsgMissingTickerSymbol, security.getName())));
        return Collections.emptyList();
    }
    if (apiKey == null)
        throw new IllegalArgumentException(Messages.MsgAlphaVantageAPIKeyMissing);
    if (rateLimiter != null && !rateLimiter.tryAcquire())
        throw new RateLimitExceededException(Messages.MsgAlphaVantageRateLimitExceeded);
    String wknUrl = MessageFormat.format(// $NON-NLS-1$
    "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY" + // $NON-NLS-1$
    "&symbol={0}&apikey={1}&datatype=csv&outputsize={2}", security.getTickerSymbol(), apiKey, outputSize.name().toLowerCase(Locale.US));
    try {
        URL obj = new URL(wknUrl);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setConnectTimeout(1000);
        con.setReadTimeout(20000);
        int responseCode = con.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK)
            // $NON-NLS-1$
            throw new IOException(wknUrl + " --> " + responseCode);
        try (Scanner scanner = new Scanner(con.getInputStream(), StandardCharsets.UTF_8.name())) {
            // $NON-NLS-1$
            String body = scanner.useDelimiter("\\A").next();
            // $NON-NLS-1$
            String[] lines = body.split("\\r?\\n");
            if (lines.length <= 2)
                return Collections.emptyList();
            // poor man's check
            if (// $NON-NLS-1$
            !"timestamp,open,high,low,close,volume".equals(lines[0])) {
                errors.add(new IOException(MessageFormat.format(Messages.MsgUnexpectedHeader, lines[0])));
                return Collections.emptyList();
            }
            // $NON-NLS-1$
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            List<T> prices = new ArrayList<>();
            for (int ii = 1; ii < lines.length; ii++) {
                String line = lines[ii];
                // $NON-NLS-1$
                String[] values = line.split(",");
                if (values.length != 6)
                    throw new IOException(MessageFormat.format(Messages.MsgUnexpectedValue, line));
                T price = klass.newInstance();
                if (values[0].length() > 10)
                    values[0] = values[0].substring(0, 10);
                price.setDate(LocalDate.parse(values[0], formatter));
                price.setValue(asPrice(values[4]));
                if (price instanceof LatestSecurityPrice) {
                    LatestSecurityPrice lsp = (LatestSecurityPrice) price;
                    lsp.setHigh(asPrice(values[2]));
                    lsp.setLow(asPrice(values[3]));
                    lsp.setVolume(Long.parseLong(values[5]));
                    lsp.setPreviousClose(LatestSecurityPrice.NOT_AVAILABLE);
                }
                if (price.getValue() != 0)
                    prices.add(price);
            }
            return prices;
        }
    } catch (IOException | ParseException | InstantiationException | IllegalAccessException e) {
        errors.add(e);
        return Collections.emptyList();
    }
}
Also used : LatestSecurityPrice(name.abuchen.portfolio.model.LatestSecurityPrice) Scanner(java.util.Scanner) ArrayList(java.util.ArrayList) RateLimitExceededException(name.abuchen.portfolio.util.RateLimitExceededException) IOException(java.io.IOException) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) ParseException(java.text.ParseException) DateTimeFormatter(java.time.format.DateTimeFormatter)

Example 5 with LatestSecurityPrice

use of name.abuchen.portfolio.model.LatestSecurityPrice in project portfolio by buchen.

the class QuoteFromTransactionExtractor method extractQuotes.

/**
 * Extracts the quotes for the given {@link Security}.
 *
 * @param security
 *            {@link Security}
 * @return true if quotes were found, else false
 */
public boolean extractQuotes(Security security) {
    boolean bChanges = false;
    SecurityPrice pLatest = null;
    // walk through all all transactions for securiy
    for (TransactionPair<?> p : security.getTransactions(client)) {
        Transaction t = p.getTransaction();
        // check the type of the transaction
        if (t instanceof PortfolioTransaction) {
            PortfolioTransaction pt = (PortfolioTransaction) t;
            // get date and quote and build a price from it
            Quote q = pt.getGrossPricePerShare();
            LocalDate d = pt.getDateTime().toLocalDate();
            SecurityPrice price = new SecurityPrice(d, q.getAmount());
            bChanges |= security.addPrice(price);
            // remember the lates price
            if ((pLatest == null) || d.isAfter(pLatest.getDate())) {
                pLatest = price;
            }
        }
    }
    // set the latest price (if at leas one price was found)
    if (pLatest != null) {
        LatestSecurityPrice lsp = new LatestSecurityPrice(pLatest.getDate(), pLatest.getValue());
        bChanges |= security.setLatest(lsp);
    }
    return bChanges;
}
Also used : Quote(name.abuchen.portfolio.money.Quote) LatestSecurityPrice(name.abuchen.portfolio.model.LatestSecurityPrice) PortfolioTransaction(name.abuchen.portfolio.model.PortfolioTransaction) PortfolioTransaction(name.abuchen.portfolio.model.PortfolioTransaction) Transaction(name.abuchen.portfolio.model.Transaction) LatestSecurityPrice(name.abuchen.portfolio.model.LatestSecurityPrice) SecurityPrice(name.abuchen.portfolio.model.SecurityPrice) LocalDate(java.time.LocalDate)

Aggregations

LatestSecurityPrice (name.abuchen.portfolio.model.LatestSecurityPrice)16 IOException (java.io.IOException)8 SecurityPrice (name.abuchen.portfolio.model.SecurityPrice)6 ParseException (java.text.ParseException)5 Scanner (java.util.Scanner)5 ArrayList (java.util.ArrayList)4 LocalDate (java.time.LocalDate)3 DateTimeParseException (java.time.format.DateTimeParseException)3 Security (name.abuchen.portfolio.model.Security)3 HttpURLConnection (java.net.HttpURLConnection)2 URISyntaxException (java.net.URISyntaxException)2 URL (java.net.URL)2 DateTimeFormatter (java.time.format.DateTimeFormatter)2 PortfolioTransaction (name.abuchen.portfolio.model.PortfolioTransaction)2 RateLimitExceededException (name.abuchen.portfolio.util.RateLimitExceededException)2 Elements (org.jsoup.select.Elements)2 File (java.io.File)1 MessageFormat (java.text.MessageFormat)1 List (java.util.List)1 BiFunction (java.util.function.BiFunction)1