Calculating profit from trading stocks in awk

Viewed 61

I have task in shell, we can also use awk.
We got file with records about trading. It looks like this:

2021-07-29 23:43:13;TSM;buy;667.90;USD;306;65fb53f6-7943-11eb-80cb-8c85906a186d
2021-07-29 23:43:15;BTC;sell;50100;USD;5;65467d26-7943-11eb-80cb-8c85906a186d

We want to know the profit from trades. Third column tells, whether the stock was bought or sold. Fourth column is price per stock, sixth is number of stocks. I tried this, profit should be 46 122.6 USD, but instead, the output is 0. I am new in awk, so I probably messed up syntax.

a=$(awk -F ';' 'BEGIN{
    loss=0
    profit=0
    if ($3 == "buy"){
        $loss=($loss + $4*$6)
    } else {
        $profit=(expr $profit + $4*$6)
    }
    {print(profit - loss)}
    }' $FILE)
echo "stonks: $a"
1 Answers
awk -F ';' 'BEGIN{x=0} $3=="buy"{x=x-$4*$6}; $3=="sell"{x=x+$4*$6} END{print x}' file

or

awk -F ';' 'BEGIN{x=0} $3=="buy"{x-=$4*$6}; $3=="sell"{x+=$4*$6} END{print x}' file

Output:

46122.6
Related