Search in sources :

Example 6 with Interval

use of name.abuchen.portfolio.util.Interval in project portfolio by buchen.

the class ClientIRRYield method create.

public static ClientIRRYield create(Client client, ClientSnapshot snapshotStart, ClientSnapshot snapshotEnd) {
    Interval interval = Interval.of(snapshotStart.getTime(), snapshotEnd.getTime());
    List<Transaction> transactions = new ArrayList<>();
    collectAccountTransactions(client, interval, transactions);
    collectPortfolioTransactions(client, interval, transactions);
    Collections.sort(transactions, new Transaction.ByDate());
    List<LocalDate> dates = new ArrayList<>();
    List<Double> values = new ArrayList<>();
    collectDatesAndValues(interval, snapshotStart, snapshotEnd, transactions, dates, values);
    double irr = IRR.calculate(dates, values);
    return new ClientIRRYield(irr);
}
Also used : PortfolioTransaction(name.abuchen.portfolio.model.PortfolioTransaction) Transaction(name.abuchen.portfolio.model.Transaction) AccountTransaction(name.abuchen.portfolio.model.AccountTransaction) ArrayList(java.util.ArrayList) LocalDate(java.time.LocalDate) Interval(name.abuchen.portfolio.util.Interval)

Example 7 with Interval

use of name.abuchen.portfolio.util.Interval in project portfolio by buchen.

the class PerformanceIndex method calculateAbsoluteInvestedCapital.

/**
 * Calculates the absolute invested capital, i.e. starting with the first
 * transaction recorded for the client.
 */
public long[] calculateAbsoluteInvestedCapital() {
    ToLongBiFunction<Money, LocalDateTime> convertIfNecessary = (amount, date) -> {
        if (amount.getCurrencyCode().equals(getCurrencyConverter().getTermCurrency()))
            return amount.getAmount();
        else
            return getCurrencyConverter().convert(date, amount).getAmount();
    };
    long startValue = 0;
    Interval interval = getActualInterval();
    LocalDateTime intervalStart = interval.getStart().atStartOfDay();
    for (Account account : getClient().getAccounts()) startValue += // 
    account.getTransactions().stream().filter(t -> t.getType() == AccountTransaction.Type.DEPOSIT || t.getType() == AccountTransaction.Type.REMOVAL).filter(// 
    t -> t.getDateTime().isBefore(intervalStart)).mapToLong(t -> {
        if (t.getType() == AccountTransaction.Type.DEPOSIT)
            return convertIfNecessary.applyAsLong(t.getMonetaryAmount(), t.getDateTime());
        else if (t.getType() == AccountTransaction.Type.REMOVAL)
            return -convertIfNecessary.applyAsLong(t.getMonetaryAmount(), t.getDateTime());
        else
            return 0;
    }).sum();
    for (Portfolio portfolio : getClient().getPortfolios()) startValue += // 
    portfolio.getTransactions().stream().filter(t -> t.getType() == PortfolioTransaction.Type.DELIVERY_INBOUND || t.getType() == PortfolioTransaction.Type.DELIVERY_OUTBOUND).filter(// 
    t -> t.getDateTime().isBefore(intervalStart)).mapToLong(t -> {
        if (t.getType() == PortfolioTransaction.Type.DELIVERY_INBOUND)
            return convertIfNecessary.applyAsLong(t.getMonetaryAmount(), t.getDateTime());
        else if (t.getType() == PortfolioTransaction.Type.DELIVERY_OUTBOUND)
            return -convertIfNecessary.applyAsLong(t.getMonetaryAmount(), t.getDateTime());
        else
            return 0;
    }).sum();
    return calculateInvestedCapital(startValue);
}
Also used : LocalDateTime(java.time.LocalDateTime) PortfolioTransaction(name.abuchen.portfolio.model.PortfolioTransaction) Arrays(java.util.Arrays) Money(name.abuchen.portfolio.money.Money) Values(name.abuchen.portfolio.money.Values) Client(name.abuchen.portfolio.model.Client) LocalDateTime(java.time.LocalDateTime) Messages(name.abuchen.portfolio.Messages) Classification(name.abuchen.portfolio.model.Classification) ToLongBiFunction(java.util.function.ToLongBiFunction) ClientClassificationFilter(name.abuchen.portfolio.snapshot.filter.ClientClassificationFilter) OutputStreamWriter(java.io.OutputStreamWriter) Interval(name.abuchen.portfolio.util.Interval) TradeCalendar(name.abuchen.portfolio.util.TradeCalendar) Portfolio(name.abuchen.portfolio.model.Portfolio) Account(name.abuchen.portfolio.model.Account) Predicate(java.util.function.Predicate) AccountTransaction(name.abuchen.portfolio.model.AccountTransaction) Volatility(name.abuchen.portfolio.math.Risk.Volatility) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) Drawdown(name.abuchen.portfolio.math.Risk.Drawdown) Security(name.abuchen.portfolio.model.Security) PortfolioClientFilter(name.abuchen.portfolio.snapshot.filter.PortfolioClientFilter) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) CurrencyConverter(name.abuchen.portfolio.money.CurrencyConverter) LocalDate(java.time.LocalDate) ClientSecurityFilter(name.abuchen.portfolio.snapshot.filter.ClientSecurityFilter) Writer(java.io.Writer) Optional(java.util.Optional) Collections(java.util.Collections) CSVStrategy(org.apache.commons.csv.CSVStrategy) CSVPrinter(org.apache.commons.csv.CSVPrinter) Money(name.abuchen.portfolio.money.Money) Account(name.abuchen.portfolio.model.Account) Portfolio(name.abuchen.portfolio.model.Portfolio) Interval(name.abuchen.portfolio.util.Interval)

Example 8 with Interval

use of name.abuchen.portfolio.util.Interval in project portfolio by buchen.

the class SecurityIndex method calculate.

/* package */
void calculate(PerformanceIndex clientIndex, Security security) {
    List<SecurityPrice> prices = security.getPrices();
    if (prices.isEmpty()) {
        initEmpty(clientIndex);
        return;
    }
    // prices only include historical quotes, not the latest quote. Merge
    // the latest quote into the list if necessary
    prices = security.getPricesIncludingLatest();
    Interval actualInterval = clientIndex.getActualInterval();
    LocalDate firstPricePoint = prices.get(0).getDate();
    if (firstPricePoint.isAfter(actualInterval.getEnd())) {
        initEmpty(clientIndex);
        return;
    }
    LocalDate startDate = clientIndex.getFirstDataPoint().orElse(actualInterval.getEnd());
    if (firstPricePoint.isAfter(startDate))
        startDate = firstPricePoint;
    LocalDate endDate = actualInterval.getEnd();
    LocalDate lastPricePoint = prices.get(prices.size() - 1).getDate();
    if (lastPricePoint.isBefore(endDate))
        endDate = lastPricePoint;
    int size = (int) ChronoUnit.DAYS.between(startDate, endDate) + 1;
    if (size <= 0) {
        initEmpty(clientIndex);
        return;
    }
    // needs currency conversion if
    // a) the currency of the security is not null
    // (otherwise it is an index)
    // b) the term currency differs from the currency of the security
    CurrencyConverter converter = security.getCurrencyCode() != null && !security.getCurrencyCode().equals(clientIndex.getCurrencyConverter().getTermCurrency()) ? clientIndex.getCurrencyConverter() : null;
    dates = new LocalDate[size];
    delta = new double[size];
    accumulated = new double[size];
    inboundTransferals = new long[size];
    outboundTransferals = new long[size];
    totals = new long[size];
    final double adjustment = clientIndex.getAccumulatedPercentage()[Dates.daysBetween(actualInterval.getStart(), startDate)];
    // first value = reference value
    dates[0] = startDate;
    delta[0] = 0;
    accumulated[0] = adjustment;
    long valuation = totals[0] = convert(converter, security, startDate);
    // calculate series
    int index = 1;
    LocalDate date = startDate.plusDays(1);
    while (date.compareTo(endDate) <= 0) {
        dates[index] = date;
        long thisValuation = totals[index] = convert(converter, security, date);
        long thisDelta = thisValuation - valuation;
        delta[index] = (double) thisDelta / (double) valuation;
        accumulated[index] = ((accumulated[index - 1] + 1 - adjustment) * (delta[index] + 1)) - 1 + adjustment;
        date = date.plusDays(1);
        valuation = thisValuation;
        index++;
    }
}
Also used : SecurityPrice(name.abuchen.portfolio.model.SecurityPrice) LocalDate(java.time.LocalDate) Interval(name.abuchen.portfolio.util.Interval) CurrencyConverter(name.abuchen.portfolio.money.CurrencyConverter)

Example 9 with Interval

use of name.abuchen.portfolio.util.Interval in project portfolio by buchen.

the class PerformanceHeatmapWidget method fillTable.

private void fillTable() {
    // fill the table lines according to the supplied period
    // calculate the performance with a temporary reporting period
    // calculate the color interpolated between red and green with yellow as
    // the median
    Interval interval = get(ReportingPeriodConfig.class).getReportingPeriod().toInterval();
    DoubleFunction<Color> coloring = buildColorFunction();
    addHeaderRow();
    DataSeries dataSeries = get(DataSeriesConfig.class).getDataSeries();
    // adapt interval to include the first and last month fully
    Interval calcInterval = Interval.of(interval.getStart().getDayOfMonth() == interval.getStart().lengthOfMonth() ? interval.getStart() : interval.getStart().withDayOfMonth(1).minusDays(1), interval.getEnd().withDayOfMonth(interval.getEnd().lengthOfMonth()));
    PerformanceIndex performanceIndex = getDashboardData().calculate(dataSeries, new ReportingPeriod.FromXtoY(calcInterval));
    Interval actualInterval = performanceIndex.getActualInterval();
    for (Integer year : actualInterval.iterYears()) {
        // year
        Cell cell = new Cell(table, () -> {
            int numColumns = getDashboardData().getDashboard().getColumns().size();
            return numColumns > 2 ? String.valueOf(year % 100) : String.valueOf(year);
        });
        GridDataFactory.fillDefaults().grab(true, false).applyTo(cell);
        // monthly data
        for (LocalDate month = LocalDate.of(year, 1, 1); month.getYear() == year; month = month.plusMonths(1)) {
            if (actualInterval.contains(month)) {
                cell = createCell(performanceIndex, month, coloring);
                InfoToolTip.attach(cell, Messages.PerformanceHeatmapToolTip);
            } else {
                // $NON-NLS-1$
                cell = new Cell(table, () -> "");
            }
            GridDataFactory.fillDefaults().grab(true, false).align(SWT.FILL, SWT.FILL).applyTo(cell);
        }
    }
    table.layout(true);
}
Also used : ReportingPeriod(name.abuchen.portfolio.snapshot.ReportingPeriod) Color(org.eclipse.swt.graphics.Color) DataSeries(name.abuchen.portfolio.ui.views.dataseries.DataSeries) LocalDate(java.time.LocalDate) PerformanceIndex(name.abuchen.portfolio.snapshot.PerformanceIndex) Point(org.eclipse.swt.graphics.Point) Interval(name.abuchen.portfolio.util.Interval)

Aggregations

Interval (name.abuchen.portfolio.util.Interval)9 LocalDate (java.time.LocalDate)8 CurrencyConverter (name.abuchen.portfolio.money.CurrencyConverter)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 AccountTransaction (name.abuchen.portfolio.model.AccountTransaction)3 Client (name.abuchen.portfolio.model.Client)3 PortfolioTransaction (name.abuchen.portfolio.model.PortfolioTransaction)3 Money (name.abuchen.portfolio.money.Money)3 Values (name.abuchen.portfolio.money.Values)3 DateTimeFormatter (java.time.format.DateTimeFormatter)2 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2 Optional (java.util.Optional)2 Messages (name.abuchen.portfolio.Messages)2 Drawdown (name.abuchen.portfolio.math.Risk.Drawdown)2 Account (name.abuchen.portfolio.model.Account)2 Portfolio (name.abuchen.portfolio.model.Portfolio)2 Security (name.abuchen.portfolio.model.Security)2 SecurityPrice (name.abuchen.portfolio.model.SecurityPrice)2