2024-07-16 09:26:49 -04:00
|
|
|
class Account::Holding < ApplicationRecord
|
2024-07-25 16:46:04 -04:00
|
|
|
include Monetizable
|
|
|
|
|
|
|
|
monetize :amount
|
|
|
|
|
2024-07-16 09:26:49 -04:00
|
|
|
belongs_to :account
|
|
|
|
belongs_to :security
|
|
|
|
|
2024-07-25 16:46:04 -04:00
|
|
|
validates :qty, :currency, presence: true
|
|
|
|
|
2024-07-16 09:26:49 -04:00
|
|
|
scope :chronological, -> { order(:date) }
|
2024-07-25 16:46:04 -04:00
|
|
|
scope :current, -> { where(date: Date.current).order(amount: :desc) }
|
2024-08-02 17:09:25 -04:00
|
|
|
scope :in_period, ->(period) { period.date_range.nil? ? all : where(date: period.date_range) }
|
|
|
|
scope :known_value, -> { where.not(amount: nil) }
|
2024-07-25 16:46:04 -04:00
|
|
|
scope :for, ->(security) { where(security_id: security).order(:date) }
|
|
|
|
|
2024-08-01 19:43:23 -04:00
|
|
|
delegate :ticker, to: :security
|
2024-07-25 16:46:04 -04:00
|
|
|
|
2024-08-20 17:35:23 -04:00
|
|
|
def name
|
|
|
|
security.name || ticker
|
|
|
|
end
|
|
|
|
|
2024-07-25 16:46:04 -04:00
|
|
|
def weight
|
|
|
|
return nil unless amount
|
|
|
|
|
2024-08-02 17:09:25 -04:00
|
|
|
portfolio_value = account.holdings.current.known_value.sum(&:amount)
|
2024-07-25 16:46:04 -04:00
|
|
|
portfolio_value.zero? ? 1 : amount / portfolio_value * 100
|
|
|
|
end
|
|
|
|
|
|
|
|
# Basic approximation of cost-basis
|
|
|
|
def avg_cost
|
|
|
|
avg_cost = account.holdings.for(security).where("date <= ?", date).average(:price)
|
|
|
|
Money.new(avg_cost, currency)
|
|
|
|
end
|
|
|
|
|
|
|
|
def trend
|
|
|
|
@trend ||= calculate_trend
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def calculate_trend
|
|
|
|
return nil unless amount_money
|
|
|
|
|
|
|
|
start_amount = qty * avg_cost
|
|
|
|
|
|
|
|
TimeSeries::Trend.new \
|
|
|
|
current: amount_money,
|
|
|
|
previous: start_amount
|
|
|
|
end
|
2024-07-16 09:26:49 -04:00
|
|
|
end
|