How can I use Excel to calculate the avarage price of some BUY\SELL operation including the sell operations weighs? - excel

I am not so into Excel and I have the following problem.
I have a table like this:
Basiscally it is an example of sheet to keep track of buyed and selled cryptocoin. It does some calculation. The column title are in italian so following some details:
B column: it is the operation: BUY or SELL.
D column: the amount of money in EUR (€) related this buy or sell operation.
E column: the price of a single coin in EUR.
F column: the number of coin buyed\selled in this operation.
Then Into the I4 cell I have put the average purchase price calculated by this formula:
=SUM(FILTER(D1:D150;B1:B150="BUY"))/SUM(FILTER(F1:F150;B1:B150="BUY"))
Basically it calculate the avarange purchase price in a simplified way (and not totally correct): it calculate the sum of the total purchase price in EUR (only the BUY operation) dividing it for the sum of the purchased coins (also here only the buyed operation).
I think that this formula is not totally correct because for example the line 4 represents an operation where all my coins was tottally sold, so after the next buy operation (line 5) the new average purchase price (in EUR) should be the eur price of this operation (that after a complete sale can be considered the only operation) for the number of coin related this operation. Basically in this specific case (but this is not a general case) the D5 / F5 that infact have the value of the E5 cell.
Basically I think that the previous formula (defined into I4) should take in consideration also how much does the average purchase price weigh after each sale operation (this because after that a specific number of coins were sold --> the purchase price untill now is the same but when I have another buy operation it must be considered that are less coins).
So basically I was thinking to use this G column containing a value representing the amount of coins updated after each sale, so basically I can have 2 possibility:
There are no previous sell operation (not previous row related a SELL operation in the B column) --> the value will be the sum of the current F value and of the F value of all the previous rows.
There are at least one row before the current one representing a SELL operation --> the value will be the summ of all the F values relatd to all the BUY operation - the sum of all the F values related to all the SELL operation.
I am not sure that this is the best way to procede. Basically what I need in the G cells is the quantity of coin untill this operation (including this operation).
How can I implement this behavior? Or what could be a nice and elegang operation to solve my original problem related my original formula?

This is actually quite a complicated problem…
If you would like to show the running balance of coins, you could do it this way:
=SUMIFS(F:F,B:B,"BUY",C:C,"SHIBA",A:A,"<="&A2:A5)
-SUMIFS(F:F,B:B,"SELL",C:C,"SHIBA",A:A,"<="&A2:A5)
This will calculate your total coin position based on the sum of all purchases prior to today's date, minus the sum of all sales prior to today's date.
However, it's not so straight forward to calculate the average purchase price. When a sale is made, are you looking to deduct it from the oldest purchase first?
Sorry that it's such a messy formula, but here's the formula I came up with:
=LET(
Dates, A2:A5,
DatesRanked, RANK.EQ(Dates,Dates,1),
CumulativePurchases, SUMIFS(F:F,B:B,"BUY",C:C,"SHIBA",A:A,"<="&Dates),
CumulativeSales, TRANSPOSE(SUMIFS(F:F,B:B,"SELL",C:C,"SHIBA",A:A,"<="&Dates)),
RowCount, ROWS(Dates),
Matrix_NetOfSales, CumulativePurchases-CumulativeSales,
Matrix_PositiveOnly, IF(Matrix_NetOfSales<0,0,Matrix_NetOfSales),
Matrix_AmountsStillHeldFromEachPurchase, Matrix_PositiveOnly-IF(DatesRanked=1,0,INDEX(Matrix_PositiveOnly,XMATCH(DatesRanked-1,DatesRanked,0),SEQUENCE(,RowCount))),
Matrix_EliminateByDate, Matrix_AmountsStillHeldFromEachPurchase*(Dates<=TRANSPOSE(Dates)),
TRANSPOSE(MMULT(TRANSPOSE(E2:E5),Matrix_EliminateByDate))
)
Here, I'm using the LET function to break down the above into manageable parts. Here is what each of the above does:
Variable
How it works
Dates
Input date range from the spreadsheet
DatesRanked
In case your data isn't sorted, it ranks the dates
CumulativePurchases
This is a dynamic range that adds up all purchases that occurred before this purchase
CumulativeSales
Same thing, but for sales
RowCount
As the name suggests, the number of rows
Matrix_NetOfSales
This subtracts the sales from the purchases, as a matrix. This is important, because different dates draw upon different transactions
Matrix_PositiveOnly
Since cumulative sales may result in an entire transaction being eliminated from the calculation, we exclude any transaction that has a negative value still applied
Matrix_AmountStillHeldFromEachPurchase
This 'undoes' the cumulative operation, leaving just the portion of each transaction that still applies
Matrix_EliminateByDate
This ensures that we only apply transactions that occur on or before the date of the current transaction
Result
Finally, we use a matrix product between the cost per share per transaction, with the matrix of units from each transaction, to get the total value spent
Phew… That was a lot of work. To get the average price per coin, simply divide the total amount spent by the total number of coins (i.e. the first equation in this answer), and it should be done!
In finance (in common law countries), this solution is similar to Clayton's Rule: Which is that the newest credit(debit) is offset against the oldest debit(credit) when calculating interest… not a coincidence.

I don't have enough reputation to comment, but I don't think it's quite clear what you're trying to accomplish... if each line item has a quantity and a cost, why would you want the sum of all previous quantities? The cost per item should only be related to those items that were transacted in this line item?
I think, based on your formula in Column I, you are attempting to do an AVERAGEIF function. This would look like this:
I2=AVERAGEIF(B:B,B2,E:E)
This would make every row where B = "Buy" match each other, and every row where B = "Sell" match each other, which I think I understood you don't want. If you're wanting to weight the results based on the quantity sold, you can do that with a SUMPRODUCT:
I2=SUMPRODUCT(--(B:B=B2),E:E,F:F)/F2
Lastly, if I misunderstood this altogether, it sounds like you'd like column G to be the cumulative sum of quantity owned to date where BUYs are added and SELLs are subtracted. You could do that like this:
G2=SUMPRODUCT(--($B$2:$B2="Buy"),$F$2:$F2)-SUMPRODUCT(--($B$2:$B2="Sell"),$F$2:$F2)

Related

Facing difficulty in Excel when creating a logic for moving average of different variables

So, the point is, in my dataset I have to create a variable "Moving Avg. Amt paid per sq. ft." and the formula or the logic I need is to calculate the last five values as per most recent transactions. i.e. most recent sales by date. but this average should only return value in case it matches the same building and same area variable.
This is what my data looks like
Area ID has three categories. Building number has 5 categories. Date is sorted in ascending order. Now my variable moving average should calculate last 5 averages w.r.t date but for the same building in the same area. e.g. there are buildings 1 and 2 in area 102. I need my Mov Avg. variable to calculate using conditions when it matches criteria of building 1 in 102 for past five sales and when it finds building 2 in the building number variable, it should calculate average of last 5 sales of that building in area 102.
So my approach to this issue was (which is flawed at the moment):
I calculate average of amount paid per sq. foot w.r.t area & building based on dates using the formula
=AVERAGEIFS($N$2:$N$6547,$D$2:$D$6547,D14,$C$2:$C$6547,C14,$B$2:$B$6547,B14)
but I cannot make this formula work, to calculate moving average whenever it meets the criteria. I tried the offset the point as well by 5 but the logic is not right and hence its not working and returning #value in the cells. The formula I used to offset the above condition is
=AVERAGEIFS((OFFSET(N13,5,,5)),$D$2:$D$6547,D13,$C$2:$C$6547,C13,$B$2:$B$6547,B13)
(These formulae are used in column Q of my data)
Need a support from the community as I am badly stuck in making this data useful and I am out of any ideas to make this work.
Edit 1: I am not sure how I can attach my excel file here so you may review the dataset. I have uploaded it on a third party site, for which the link is shared below, so you can view the file in detail.
https://file.io/hlciAHJOHzWA
Expected result is as I have mentioned the instruction said
"Create a variable called "mov. avg amt. paid per sq ft". For each row, this variable should calculate average amt paid per sq ft for the most recent past five sales (by date) for the same building in the same area."
And my approach to build a logic or formula to make this variable calculate moving average w.r.t date for same building in the same area doesn't seem to work because there might be some flaws.
In Office 365 you could use:
=LET(f,FILTER($N$1:N13,($B$1:B13=B14)*($C$1:C13=C14),""),
c,COUNTA(f),
s,SEQUENCE(5,,c-5),
IFERROR(IF(c<5,SUM(f)/c,SUM(INDEX(f,s))/5),""))
If there's less than 5 matches prior to the current sales it'll calculate the average of the count. If 5 or more matches it'll calculate the average of the last 5 prior to the current sale.

Substract a cell (if it has a # value) with rows below it in a different column if the conditions are the same

I'm using this equation =IF(K2=0,0, K2-I2) to show the difference in a cell with what a client has to pay vs what he has paid (negative if he paid less than what he had to and positive if he paid more). How would I modify this equation to substract from the next amount paid (k3 in this case) or the following (k4) if they didn't pay in k3 so the difference becomes 0 if its used with the added condition that the name at Column C matches.
The first column is the amount someone needs to pay, the second is what they paid, the fourth shows the difference and the fifth states what it is. I would like the difference from the first row to use the paid amount from the second row to substract from it before applying itself to the difference in the second row. Is this possible? I've tried looking for hours in google with no luck.
Edit:
This is how I would like it to look (this is manually inputting the data). The amount the client has to pay each month is 425.65 so the second month he pays 400 it would first cancel the first 'debt' to then count towards his second month payment which results in more debt than the first pay cycle.
Prelim
Worksheet here / screenshot below refer.
If you don't mind using a 'helper' column (I don't see any other way around this, unless you go down the 'VBA/Pivot' route, given the nature of the sum function re arrays) - then this should (I think!:) address the issue...
Eqns
Helper
=IF(OR(B3<>B4,SUM(D$3:D3*(B$3:B3=B3))>=INDEX($C$3:$C$11,MATCH(B3,$B$3:$B$11,0))),1,0)
This turns 1 when the sum of "Paid" is at least >= "Owing" for the same individual. Assumes: rows ordered chronologically, grouped by 'Person' attribute.
Net ultimate
=IF(B3=B2,"",SUM(D3:INDEX($D$3:$D$11,MATCH(B3&1,$B$3:$B$11&$E$3:$E$11,0))))
Screenshots
This sums from the first instance of 'Paid' for a given Person, to the Paid value corresponding to the first instance of a '1' in the Helper column.
Examples
In this case, A owes £1k at outset, pays £450 initially, then pays a further £700 (i.e. has overpaid by £150). As such, the 'Net ultimate' figure reports back £1,150 (=£450 + £700); it doesn't consider the £50 (did you want it to? If so the function becomes a lot easier, and reduces to a regular sumifs...).
For B: net ultimate = £1,025 (the total amounts paid never exceed what is owing, so tally all amounts paid by B)
Same goes for £1k and C....

Choose correct PRODUCT COST from ROW based on amount sold

I am making a sheet to CALCULATE REAL REVENUE from each sale I make on my online store.
The problem is that the COST of my products is not always constant. It varies depending on many factors so each time I make a purchase I add the NEW PRODUCTS COST (LATEST COST).
Each time I make a new purchase I will add the QUANTITY and the new COST. (PURCHASE 1, PURCHASE 2, PURCHASE 3,etc).
Screenshoot of my sheet with example on ROW 41
In Column B I want to know which is the CURRENT COST based on the amount of TOTAL SALES of each product.
For example:
If I have sold less than 100 ( Pruchase 1 QUANTITY) then I need the formula to choose value of E41 (PURCHASE 1 COST).
If I have sold MORE than 100 and LESS than 300 (which is the SUM of PURCHASE 1 & PURCHASE 2) I need the formula to choose value of G41 (PURCHASE 2 COST) AND SO ON...
The formula I have come up with so far is this:
=INDEX(41:41,,IF(C41<=D41,COLUMN(E41),IF(C41<=D41+F41,COLUMN(E41)+2,IF(C41<=D41+F41+H41,COLUMN(E41)+4,COLUMN(E41)+6))))
This formula WORKS but only for the first 3 PURCHASES.
I need a formula that has no limit but I don't know how to make a VARIABLE formula.
Please take my words literally when I say that I wouldn't waste one minute on trying to solve your problem with your current sheet design. You would need VBA, and then extract quantities and prices from each purchase without the ability to filter on columns. (Minute is up.)
What you need is a Purchase database: ItemID, Date, Quantity, Price, maybe Ref#. From that you can pull out the transactions for any item by filtering on the item and the cost by using functions like SUMIF. However, this just brings the real problem within reach without solving it.
The problem is that when you buy 100 pcs #42 your price is 42. Then you buy another 100 pieces #46 your average price is 44. But if you sold 50 pieces with a cost of 42 then the average cost of the remaining 150 is 45. Therefore you can't determine the average cost of any remainder without knowing the quantity sold and the average cost applied to that sale. To solve that problem you will still need VBA but the suggested db format of purchase record would at least support such a solution.
Not so long ago I programmed a solution where there were additional columns in the db and each sale was recorded in 3 columns (much like your present purchase record): date, Qty, Ref. In this way I could trace the sale of each individual purchase (this was for shares trading). The sale of the newer quantity wouldn't start until the earlier quantity was sold out.
Perhaps you don't need to trace where the purchased quantity went to and just need one column to count down the balance to zero. That would be much simpler but has the drawback that you can't roll back errors. In the end the rollback was the reason why I abandoned the design. The key to the ability to abandon it is a similar db for sales: date, qty, price, Ref#.
With such a setup you might design a system to either extract the average or FiFo price from the purchase side and associate it with a sale. If the condition is that it should be done with worksheet functions you could add a column for "current cost" in the purchase db, changing with each purchase, which you look up by date from the sales side using VLOOKUP or SUMPRODUCT, having set a cost price applicable from the day of purchase until the next. If that appeals to you, a method must be found to deal with days on which there are both purchases and sales.

Excel Formula - Total subscriptions after Nth years based on monthly churn rates

A business works on a subscription model basis with a expected churn rate (Cancellations) each month during year 1 at 5% & during the following year a churn rate of 2.5% due to the fact these are now established customers (long term).
A new feature or service is launched with a expect increase of subscriptions each month. I need to calculate how many subscriptions would that be in N years based on a 5% churn rate for the first 12 month & a 2.5% churn rate during year 2.
Below is currently how were are calculating this in excel however this is really in inelegant solution when trying to calculate this for say 5 - 10 year impacts.
https://i.stack.imgur.com/yF5Rx.png
Are there any accounting formulas or something mathamitcally I can produce to calculate this in a single cell? Given I would need to set the given churn rates for each year & length of time.
For ease lets say 95% of the time I would be working on a 3 year model of subscriptions & each year will need its own churn rate.
I thought perhaps something with exp & halving the value might work but have not found anything yet.
Here's one way to build the model. I'll make reference to this image:
First we set up the churn model.
Row 1: Since Churn Rates depend on subscription age, Row 1 has the subscription age (in months). This is for reference only and is not used in the calculations.
Row 2: Churn Rates.
Row 3: Since Churn Rates always enter the calculation as (1-ChurnRate), call that term (Single-month) Retention Rate. As an example, in B3 the formula is =1-B2.
Row 4: Since the effects of churn are cumulative over multiple months, we define another term Multi-month Retention Rate (abbreviated MMRR). In the first month this is set to 1; in subsequent months this is the product of previous single-month retention rates. So in C4 the formula is =B4*B3; in C5, =C4*C3, etc.
Row 5: The model as described in the Question indicated a fixed rate of new subscriptions = 100/month. When the subscription rate is fixed, it is convenient to sum up the MMRRs. So in B5 we have =B4; in C5, =B5+C4; in D5, C5+D4; etc.
At this point we're essentially done. If you multiply the values in Row 5 by any fixed rate of new subscriptions (e.g. 100/month in the original Question) we get the number of subscribers in that month. But what if you want to model where the number of new subscriptions varies month to month? Here's how ...
The basic idea is to multiply the monthly subscription rate by its age-appropriate MMRR. Note that Row 8 has varying numbers of new subscriptions (100, 110, 97) in the first 3 months. To get the total subscriptions in Mar-19 for example, we need to
multiply the 100 (Jan-19) subscriptions (that have a 2 month age) by the MMRR for a 2-month old subscription (0.9025),
multiply the 110 (Feb-19) subscriptions (that have a 1 month age) by the MMRR for a 1-month old subscription (0.95),
multiply the 97 (Mar-19) subscriptions (that have a 0 month age) by the MMRR for a 0-month old subscription (1), and
add those three products together.
This could be calculated on the worksheet by entering in D9 the formula =B8*D4+C8*C4+D8*B4. This type of calculation (sum up the pair-wise products of two arrays) is often done with Excel's SUMPRODUCT function. Here we need to take one of the arrays in reverse order, which is not directly supported by Excel. You could enter new subscriptions in reverse order, but that's an ugly kludge. Fortunately, it is do-able with a combination of the OFFSET(), COLUMN() and N() worksheet functions (see here for details). The required formula for B9 is
=SUMPRODUCT($B4:B4,N(OFFSET(B8,0,-(COLUMN($B8:B8)-COLUMN($B8)),1,1)))
This can then be copy/pasted into the rest of row 9.
This model approach is pretty flexible: the churn rates (row 2) and subscription rates (row 8) can both be varied month to month; the total number of retained monthly subscriptions is calculated automatically.

Excel formula to calculate the sum of positive and negative change of products

I have excel table in csv with data from monitoring smart shelf. The shelf status is monitored every 2 mins. The data is the table with time status of products at given time during the day. Each column consists of numbers e.g. 1,4,3,2,2,2,0,0 etc. When the number is bigger than previous one (e.g. was 2 and now is 3) it means that someone added the product to the shelf, and when the number is less than previous one, it means that the product unit/s was sold.
Te problem is to construct the formula that will be count quantity sold and quantity added. I think that it should monitor the change of quantity whether is positive or negative and sum each positive and negative change.
I just started learning excel more complex formulas and I don't have any idea how to solve this problem. I count on your help
Sold
=SUMPRODUCT(A1:A7-A2:A8,--(A1:A7>A2:A8))
Stocked
=SUMPRODUCT(A2:A8-A1:A7,--(A2:A8>A1:A7))

Resources