1
0
Fork 0
mirror of https://github.com/maybe-finance/maybe.git synced 2025-08-02 20:15:22 +02:00

holding: Add multi-currency support for average costs calculations. (#2153)

Fixes: #2051.
This commit is contained in:
Joseph Ho 2025-05-06 12:12:44 -04:00 committed by GitHub
parent 60c3a04a48
commit 8c10e87387
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 30 additions and 11 deletions

View file

@ -27,10 +27,18 @@ class Holding < ApplicationRecord
# Basic approximation of cost-basis
def avg_cost
avg_cost = account.entries.trades
.joins("INNER JOIN trades ON trades.id = entries.entryable_id")
.where("trades.security_id = ? AND trades.qty > 0 AND entries.date <= ?", security.id, date)
.average(:price)
avg_cost = account.trades
.with_entry
.joins(ActiveRecord::Base.sanitize_sql_array([
"LEFT JOIN exchange_rates ON (
exchange_rates.date = entries.date AND
exchange_rates.from_currency = trades.currency AND
exchange_rates.to_currency = ?
)", account.currency
]))
.where(security_id: security.id)
.where("trades.qty > 0 AND entries.date <= ?", date)
.average("trades.price * COALESCE(exchange_rates.rate, 1)")
Money.new(avg_cost || price, currency)
end