Is there a way to use postgresql function to calculate weighted average in Rails?
04:58 24 Jun 2015

To calculate weighted average by a company's market capacity, I have a method like this:

class Company < ActiveRecord::Base
  def self.weighted_average(column)
    market_cap_sum = sum(:market_cap)
    array = []
    find_each do |company|
      next if company.send(column).nil?
      next if company.market_cap.nil?
      array << (company.market_cap.to_d/market_cap_sum) * company.send(column)
    end
    array.sum
  end
end

This code works fine but it's just slow to calculate. If there is a way to calculate by postgresql function, I wanna use it.

To calculate standard deviation there is a function like this, but I couldn't find how to calculate standard deviation with weighted average.

Company.select('stddev_pop(price) as stddev')

Is it possible to do what I want?

ruby-on-rails postgresql