Calculate interest on postgresql with trigger/function - postgresql

I'm currently working on a simple banking application.
I have built a postgresql database, with the right tables and functions.
My problem is, that I am not sure how to calculate the interest rate on the accounts. I have a function that will tell me the balance, on a time.
If we say that we have a 1 month period, where I want to calculate the interest on the account. The balance looks like this:
February Balance
1. $1000
3. $300
10. $700
27. $500
Balance on end of month: $500
My initial thoughts are to make a for loop, looping from the 1st in the month, to the last day in month, and adding the interest earned for that particular day in a row.
The function I want to use at end of month should be something like addInterest(startDate,endDate,accountNumber), which should insert one row into the table, adding the earned rate.
Could someone bring me on the right track, or show me some good learning resources on PL/PGSQL?
Edit
I have been reading a bit on cursors. Should I use a cursor to walk through the table?
I find it a bit confusing to use cursors, anyone here with some well explained examples?

There are various ways of interest calculation in banking system.
Interest = Balance x Rate x Days / Year
Types of Balances
Periodical Aggregate Balance
Daily Aggregate Balance
Types of Rates
Fixed Rate Dynamic Rate (according to balance)
Dynamic Rate (according to term)
Dynamic Rate (according to schedule)
Types of Days/Schedules
End of Day Processing (One day)
End of Month Processing (One month)
End of Quarter Processing (Three months)
End of Half Processing (Six months)
End of Year Processing (One year)
Year Formula
A year could consist of 365 or 366 days.
Your user might want to override number of days in a year, maintain a separate year variable property in your application.
Conclusion
Interest should be calculated as a routine task. Best approach would be that would run on a schedule depending upon the frequency setup of individual accounts.

The manual has a section about loops and looping through query results. There are also examples of trigger functions written in pl/pgsql. The manual is very complete, it's the best source I know of.

Related

Why are my values multiplying when I apply Month/Year to my values?

When I apply Month/Year to Cases or Deaths from my data, the values explode. For Cases it goes from approximately 48 million to over 1 billion, and for Deaths it goes from about 700 thousand to over 22 million. However, when I try the same thing with Initial Claims or the Stringency Index, my values remain correct. I'm trying to find the month over month percentage change by the way. And I'm using the Date column. I only select 2020 and 2021 in the filter for Year.
What I'm asking about is Sheet 21.
Link to workbook: https://public.tableau.com/app/profile/nilajah.rivers/viz/CoronaVirusProject_16323687296770/Sheet21
Your problem is that the data points are daily cumulative deaths. If you change the date aggregation to anything other than days, Tableau will default to summing the numbers for all the days in the month. This will give the wrong result, obviously.
If you want to show the correct total deaths or cases regardless of the time aggregation (months, days, weeks etc.) then you could use the New Case or New Death numbers plus a running sum table calculation. This will always give the correct total for the time period.
Table calculations will also allow automatic calculation of the period to period % change from the same data fields.
This is a common problem when working with datasets that offer pre-calculated aggregations. Tableau doesn't need that as it can dynamically calculate the aggregation of a field over any given time period but it is easy to forget which field has pre-aggregated data and which has raw data. Pre-aggregated fields assume a particular time period and can't be used for different time periods without disentangling that assumption (which is unnecessary if you also have the raw data (in this case daily new deaths/cases).

Tableau Summing up aggregated data with FIXED

Data granularity is per customer, per invoice date, per product type.
Generally the idea is simple:
We have a moving average calculation of the volume per week. MA based on last 12 weeks (MA Volume):
window_sum(sum([Volume]),-11,0)/window_count(count([Volume]), -11,0)
We need to see the deviation of the current week vs the MA for that week (Vol DIFF):
SUM([Volume])-[MA Calc]
We need to sum up the deviations for a fixed period of time (Year/Month)
Basically this should show us whether on average, for a given period of time, we deviate positively or negatively vs the base.
enter image description here
Unfortunately I get errors like:
"Argument to SUM (an aggregate function) is already an aggregation, and cannot be further aggregated."
Or
"Level of detail expressions cannot contain table calculations or the ATTR function"
Any ideas how I can go around this one?
Managed to solve this one. Needed to add months to the view and then just WINDOW_SUM(Vol_DIFF).
Simple as that!

Anylogic: adjust number of visitors over time (with trend?)

I am trying to create a trend in which visitors to an event slowly decline every year.
This is the setup: https://imgur.com/6mx3xy2
I want to ensure that for instance in year 1 there are 100,000 visitors but the next year this declines with 1%, so that next year only 99,000 visitors are present and the year after that 99.000*0.99 so in the total of those years 297.010 people have visited. (So, the Stock value of visitors being 297.010 after a simulation of 3 years)
What values/formulas should I give my NewInfoRealVisitors variable and flow equation for example? Or all the other variables for that matter
Ok, a lot of things to do here, first your structure is wrong and should be like this:
visitorsPerYear = annualVisitors it's the same variable, but defined as a flow and as a stock at the same time
annualVisitorsDecline = annualVisitors*declineRate
Now, to obtain the exact values you want (total visitors = 297010)
you need to use years as the model time units and you need to use 1 as the fixed time step:
And finally, you need to run the model in virtual time (as fast as possible) because otherwise anylogic changes your fixed time step without your control
If you don't do all this, you will just get an approximation of 297.010 based on Euler equations... close enough, but not exactly it.

Power BI - Calculating a price/cost until a variable end date

Let's say I have a table of projects/programs/subscriptions/etc, it doesn't really matter as long as there is a price or cost per some amount of time. My table includes at least the following columns:
[ProjectName]
[StartDate]
[EndDate]
[CostPerDay]
I'm trying to allow the user to choose another date (slicer I assume?) and display the cost of each and all projects up to that date. Is this possible?
Edit: After the first responses I realize the original question was very poorly worded. Sorry about that. I've reworded it and I'll explain more here:
I am not trying to filter the programs by end date. I'm trying to sum a cost up until the end date OR slicer date, whichever is earlier.
Here's a short example table:
So we can also think of it as a Gantt chart like this:
Now imagine sliding a vertical line along that chart. I want to see the total cost up to that date.
I'm sure it will have to do with counting days between start date and the slicer date, then multiplying by cost. But how do we not include days after the end date of each project? Or it may be easier to do a range slicer with a min and max date, but again not counting days before or after each project.
To word it differently: can I input a date range, count the days that each project has in common with that range, and (the simple part) multiply days by cost?
It looks like what you need is a table visualization with a slicer for End date. Once the table and slicer are created, you can click on the small down facing arrow in the slicer and choose "Before". If you want both start date and end date in the equation, then you would have to add one more slicer for "Start date". If this is not what you are looking for kindly provide additional details so that we can help you out.

Can I calculate a moving sum on a field in InfluxDB?

I'm trying to understand if it's possible to calculate a 1 month sum of revenue data in one of my measurements. For each day, I would like the sum of the previous 30 days.
Is this possible in InfluxDB or through Grafana's query interface?
A moving average is a moving sum, divided by the number of samples. So if you want a moving sum of the past 30 values:
select 30*moving_average(field_name, 30) from measurement
Edited to add:
As Peter Halicky points out in the comments, this is is not the past 30 days. It's the past 30 data points.
If you will always have data for every single day, it's not an issue.
If you're missing a day's data, you'll still get a 30-sample average, but it'll stretch over 31 days instead of 30.
If you don't actually care about the calendar, but want to know the past 30 days of activity, this is not a problem.
If it is a problem, there are a few work-arounds. One that's probably trickier than it sounds: ensure that there is always an entry for each day.
A more robust way is to have the reporting app do this in two steps. Something like this (haven't worked out all the details, but you get the idea):
find the number of data points in the past 30 days, using a query like select count(field_name) from measurement where time > now() - 30d.
Use this number (call it n) to form the query: select n*moving_average(field_name, n) from measurement where time > now - 30d.
Yes, definitely it's possible.
Just set this part of your query like this:
SELECT sum("value") FROM "YOUR_TAG_NAME"
WHERE $timeFilter GROUP BY time(30d) fill(null)
Just make sure that your dashboard time included Last 30 days (at least).