This script is also included in my book, Stock Trading Riches, which is available on Amazon.com, and outlines my complete stock trading system.
You can learn more about my book at my trading book's website.
Basically, the technique is to buy a certain control value (in our case $2,000) worth of the stock and then, for each new price, buy or sell shares until we get back to the control value. We will not always rebalance back exactly to the control due to rounding errors, since we cannot own fractional shares of a stock.
Here is the program:
awk '
BEGIN {
control = 2000
cash = control
orig = control
}
{
price = $1
value = shares * price + cash
shares = int(control / price)
cash = value - shares * price
if (cash < 0)
{
value += -1*cash
orig += -1*cash
cash = 0
}
print price" "shares" "cash" "value" "orig
}
In the begin part (before the file of prices are read in), we set "control" to be the starting amount ($2000). Then, we set the "cash" and "orig" (amount invested) to also be $2,000. So, at stage 0 (before we start reading in the file of prices) we have defined that we will hold $2000 worth of the stock and we will not start with any extra cash - only the $2000 needed for our intial purchase.
Now, we come to the main section. Since there is no pattern before the brackets, it means that the steps contained in this second set of brackets will be applied to each line in the file.
We first set price to be the first field in the file. Our assumption is that each line in the file consists of only a stock price. We ignore everything else on the line.
Then, we caculate the current value of the account. This will be all shares of stock owned, multiplied by the current stock price, plus any cash. When we read in the first price from the file (line 1), this calculation will be:
value = 0 * first_price + 2000 = 2000
This is because we start out with no stock, and all our starting money in cash.
Then, we set the number of shares to be the control (2000) divided by the share price, and we round. So, for example, if the first price was $10, then we would change shares from 0 to 2000/10 = 200.
Next, we adjust cash to reflect buying/selling to reach our new share value (and establish a stock value equal to the control). In the above example, the first price is $10, so we changed shares from 0 to 200. Now we would set cash = value - shares * price = 2000 - 200*10 = 0 (remember multiplication is done before subtraction).
In the next step, we check if cash is negative. This would mean that the stock price went down, we bought more stock, and did not have the cash to pay for it. We now have to add more cash into the account and need to update the value and orig (which is the amount we invested).
Finally, after processing each price, we print out the status of the account.
Here is an example , as applied to Amazon.com (AMZN) yearly prices.
0 comments:
Post a Comment