VoidZero VoidZero - 8 months ago 15
Ruby Question

How to convert all daily data of a year to monthly data

First let me tell you what I want, I want to make a chart of a growth of a users mutual funds portfolio.

Now I have a user who invests in a portfolio last year.

Now I have a task which stores all the daily growth values of a users
portfolio in user portfolio growth table.

Now as of current date I have all daily values of a portfolio growth in my user portfolio growth table.

What I want is to show monthly growth of a users portfolio on a graph.

So, my question here is how do I convert all the daily values to monthly values from date of his investment? So, that I can show it on a graph.

UserPortfolio Schema

# == Schema Information
# Table name: user_portfolios
# id :integer not null, primary key
# user_id :integer not null
# portfolio_name :string
# amount :integer not null
# investment_plan :string not null
# duration :integer default(1), not null
# risk_level :string not null
# created_at :datetime not null
# updated_at :datetime not null


# == Schema Information
# Table name: user_portfolio_growths
# id :integer not null, primary key
# user_portfolio_id :integer
# appreciated_value :float
# created_at :datetime not null
# updated_at :datetime not null

Thank You!


What you have to do is, you have to take all the values of amount or investment or whatever you want to take of a single month.

Now add them up.

and take the average.

for eg. we take for current month

total_amount = UserPortfolio.where(created_at: (Date.today.beginning_of_month..Date.today.end_of_month)).pluck(:amount)
average_amount = total_amount.inject(0, :+)/total_amount.count

This will give you average for current month similarly you are able to get for each and every month for whole year.

Then put it in a hash or an array and Show them in graph.