Computing positions
The default method of function position computes a
position (i.e. the resulting balance) of a number of
transactions.
library("PMwR") amount <- c(1, 1, 1) position(amount)
3
Positive amounts increase the balance, and negative amounts decrease it. (Think of buying and selling a commodity.) You can also add the instrument to which a particular amount belongs.
instrument <- c("A", "A", "B") position(amount = amount, instrument = instrument)
A 2 B 1
Another way to get instrument information into the
position is to specify names for amount.
amount <- c(A = 1, B = 1, C = 1)
position(amount)
A 1 B 1 C 1
This is most useful if you want to 'declare' a position
(i.e. not really compute it from transactions). This
behaviour is controlled by the argument
use.names. Its default (NULL) works as follows: if
amount is named and no separate argument instrument
is specified, the names are interpreted as
instruments. If use.names is FALSE, names of
amount are ignored. (Ignoring names was the default
behaviour prior to PMwR version 0.11.)
amount <- c(A = 1, B = 1, C = 1) position(amount, use.names = FALSE)
3
The behaviour when use.names is TRUE is currently
experimental: the names are used even if instrument
is specified.
amount <- c(A = 1, B = 1, C = 1) position(amount, instrument = c("A", "A", "A"), use.names = TRUE)
A 1 B 1 C 1
Why is it experimental? The reason for adding
use.names was to allow fast and convenient
construction of single-period positions, such as the
example from above.
position(c(A = 1, B = 1, C = 1))
However, using names(amount) should remain a
shortcut, with the safe option being to specify
instrument explicitly. So a reasonable reasoning
would have been that whenever instrument is
specified, it is used. Thus, the TRUE may be removed
again.
amount may also be a matrix. The use case is a matrix
in which each column belongs to one instrument. But to
interpret a matrix in this way, information about the
instrument must be provided. When there is no such
information, position treats the matrix as a list of
transactions in a single instrument, but only as long
as it has only a single row or only a single column.
amount <- array(1:3, dim = c(1, 3))
position(amount)
position(t(amount))
6 6
position(amount, instrument = letters[1:3])
a 1 b 2 c 3
colnames(amount) <- letters[1:3]
amount
a b c
[1,] 1 2 3
position(amount)
a 1 b 2 c 3
If you instruct position to ignore the column names,
it treats the matrix as a list of transactions in a
single instrument, as expected.
position(amount, use.names = FALSE)
6
Providing as input a matrix of more than one row and more than one column, but no instrument information at all, raises an error.
amount <- array(1:6, dim = c(2, 3))
position(amount)
Error in position.default(amount) : amount is a matrix but instrument is missing
amount <- array(1:6, dim = c(2, 3)) colnames(amount) <- letters[1:3] amount
a b c
[1,] 1 3 5
[2,] 2 4 6
position(amount)
a 3 b 7 c 11