OK, what you have to do is to get away from procedural programming paradigm and into database paradigm. You are working through each account completely before moving on to the next, that is the procedural way. What you have to do is to work through each step in the calculations for all records using sql, then you will just be running 5-10 queries.
Now, I'm not going to try and get my head around the details of these complex calculations so I'll have to explain this in a more genric way.
I have a calc-debt function in an access app that does a similar thing:
accounts have a starting balance, they acrue fees, payments, credits and debits to arrive at a current balance. So,
query 1 calculates total fees and stores that in a column in the debt
2 cals total credits
3 calcs total debits
4 calcs total payments
5 then calculates the balance from those stored totals
6 then runs an audit trail
100,000 accounts in 6 queries
The thing that is throwing you is the conditional processing if ($deposit['roi'] + $roi > TOTAL_ROI) {
You can use IF within a query to handle this Control Flow Functions , or just run 2 or 3 conditional queries as Installer suggests.
It is at times like this that you need to step back from your code and abstract the logic using pen and paper to identify each transformation step and then code the queries to perform each step.