There are many ways to calculate the return, and every way will give you a different results in terms of a percentage-value.
One way to always get something meaningful - count the cash. You had 977 (+ 31) and in the end you have 1.370, which means you have earned 363 dollars.
But what is your return in terms of percentage?
One way to look at it, is by pretending that it is a fund in which you invest 1 dollar. What is the fund worth in the beginning and in the end? The tricky part in your example is, you injected new capital into the equation.
Initially you invested 977 dollars which later, in the second period became worth 1.473. You then sold off 200 shares for 950 dollars. Remember your portfolio is still worth 1.473, split between 950 in cash and 523 in Shares. So far so good - still easy to calculate return (1.473 / 977 -1 = 50.8% return).
Now you buy share for 981 dollars, but you only had 950 in cash? We now need to consider 2 scenarios. Either you (or someone else) injected 31 dollars into the fund - or you actually had the 31 dollars in the fund to begin with. If you already had the cash in the fund to begin with, your initial investment is 1.008 and not 977 (977 in shares and 31 in cash). In the end the value of the fund is 1.370, which means your return is 1.370 / 1.007 = 36%.
Consider if the 31 dollars was paid in to the fund by someone other than you. You will then need to recalculate how much you each own of the fund.
Just before the injection, the fund was worth 950 in cash and 387 in stock (310 - 200 = 110 x 3.54) = 1.339 dollars - then 31 dollars are injected, bringing the value of the fund up to 1.370. The ownership of the fund is split with 1.339 / 1.370 = 97.8% of the value for the old capital and 2.2% for the new capital.
If the value of the fund was to change from here, you could calculate the return for each investor individually by applying their share of the funds value respective to their investment.
Because the value of the fund has not changed since the last period (bullet 3), the return on the original investment is (977 / 1.339 - 1 = 37.2%) and the return on the new capital is (31 / 31 = 0%).
If you (and not someone else) injected the 31 dollar into the fund, you will need to calculate the weight of each share of capital in each period and get the average return for each period to get to a total return. In this specific case you will still get 37.2% return - but it gets even more comlex for each time you inject new capital.