R
R 中的投資組合管理
我一直在尋找可以讓我跟踪我的股票投資組合的 R 包 - 基本上我想輸入我擁有的股票,跟踪我所做的交易,計算我的未平倉頭寸和平均成本,未實現和已實現 P /L,等等……但我還沒有看到一個包可以做到這一點。有沒有人讀過/使用這些功能?謝謝。
您可以使用吸墨紙包做到這一點。我們用它來協調我們的交易。
它僅在 R-Forge 上可用,因此請參閱此 stackoverflow 問題以了解如何安裝它。執行“amzn_test”展示以獲取如何使用它的範例:
library(blotter) demo(amzn_test)
我維護的
PMwR
包提供了這樣的計算。該軟體包位於CRAN和GitHub / GitLab上。一些範常式式碼:
library("PMwR") trades <- read.table(text=" timestamp , instrument , amount , price 2019-06-25 , Amazon , 20 , 1878 2019-06-26 , Amazon , -10 , 1902 2019-07-01 , Amazon , -10 , 1921 2019-04-15 , Netflix , 20 , 362", header = TRUE, sep = ",", strip.white = TRUE, stringsAsFactors = FALSE) trades$timestamp <- as.Date(trades$timestamp) trades <- as.journal(trades) trades ## instrument timestamp amount price ## 1 Amazon 2019-06-25 20 1878 ## 2 Amazon 2019-06-26 -10 1902 ## 3 Amazon 2019-07-01 -10 1921 ## 4 Netflix 2019-04-15 20 362 ## ## 4 transactions
trades
是一個journal
,你的交易清單。summary(trades) ## journal: 4 transactions in 2 instruments ## ## instrument n avg buy avg sell first last ## Amazon 3 1878 1911.5 2019-06-25 2019-07-01 ## Netflix 1 362 NA 2019-04-15 2019-04-15
從此
journal
,您現在可以計算位置。position(trades) ## 2019-07-01 ## Amazon 0 ## Netflix 20 position(trades, drop.zero = TRUE) ## 2019-07-01 ## Netflix 20 position(trades, when = as.Date("2019-06-27")) ## 2019-06-27 ## Amazon 10 ## Netflix 20
您可以計算盈虧。
pl(trades) ## Amazon ## P/L total 670 ## average buy 1878 ## average sell 1911.5 ## cum. volume 40 ## ## Netflix ## P/L total NA ## average buy 362 ## average sell NA ## cum. volume 20 ## ## ‘P/L total’ is in units of instrument; ## ‘volume’ is sum of /absolute/ amounts. ## ‘sum(amount)’ is not zero for Netflix: specify ‘vprice’ to compute p/l.
由於 Netflix 中有一個未平倉頭寸,我們需要提供一個用於估值的價格 (
vprice
)。pl(trades, vprice = c(Netflix = 380)) ## Amazon ## P/L total 670 ## average buy 1878 ## average sell 1911.5 ## cum. volume 40 ## ## Netflix ## P/L total 360 ## average buy 362 ## average sell 380 ## cum. volume 20 ## ## ‘P/L total’ is in units of instrument; ## ‘volume’ is sum of /absolute/ amounts.
該函式
pl
還可以計算一段時間內的損益。pl(trades["Amazon"], along.timestamp = TRUE) ## Amazon ## timestamp 2019-06-25 2019-06-26 2019-07-01 ## P/L total 0 480 670 ## __ realised 0 240 670 ## __ unrealised 0 240 0 ## average buy 1878 ## average sell 1911.5 ## cum. volume 20 30 40 ## ## ‘P/L total’ is in units of instrument; ## ‘volume’ is sum of /absolute/ amounts.