Blocks of Stock. A block of stock as a number of attributes, including a
purchase date, a purchase price, a number of shares, and a ticker
symbol. We can record these pieces of information in a
tuple for each block of stock and do a
number of simple operations on the blocks.
Let's dream that we have the following portfolio.
Purchase Date
Purchase Price
Shares
Symbol
Current Price
25 Jan 2001
43.50
25
CAT
92.45
25 Jan 2001
42.80
50
DD
51.19
25 Jan 2001
42.10
75
EK
34.87
25 Jan 2001
37.58
100
GM
37.58
We can represent each block of stock as a 5-tuple with
purchase date, purchase price, shares, ticker symbol and current
price.
Develop a function that examines each block, multiplies shares
by purchase price and determines the total purchase price of the
portfolio.
Develop a second function that examines each block, multiplies
shares by purchase price and shares by current price to determine
the total amount gained or lost.
Mean. Computing the mean of a list of
values is relatively simple. The mean is the sum of the values
divided by the number of values in the
list. Since the statistical formula is so
closely related to the actual loop, we'll provide the formula,
followed by an overview of the code.
Equation 13.1. Mean
The definition of the Σ mathematical operator leads us to the
following method for computing the mean:
Procedure 13.1. Computing Mean
intialize sum, s, to zero
for each value, i, in the range 0 to
the number of values in the list,
n:
add element xi to s
return s divided by the number of
elements, n
Standard Deviation. The standard deviation can be done a few ways, but we'll use
the formula shown below. This computes a deviation measurement as
the square of the difference between each sample and the mean. The
sum of these measurements is then divided by the number of values
times the number of degrees of freedom to get a standardized
deviation measurement. Again, the formula summarizes the loop, so
we'll show the formula followed by an overview of the code.
Equation 13.2. Standard Deviation
The definition of the Σ mathematical operator leads us to the
following method for computing the standard deviation:
Procedure 13.2. Computing Standard Deviation
compute the mean, m
intialize sum, s, to zero
for each value, xi in the list:
compute the difference from the mean,
d as
xi -
m
add d2 to s. This
is typically done as
d*d in Java, since
there is no “squared” operator. In Python, this
can be d**2.
compute the variance as s divided by
(n - 1). This n - 1
value reflects the statistical notion of “degrees of
freedom”, which is beyond the scope of this book.