Advertisement
TwoR

Kill 2008 DD

Mar 20th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.97 KB | None | 0 0
  1. library(QuantTools)
  2.  
  3. # Функция для рассчета портфеля
  4. calc_simple_portfolio = function( assets, weights, full = F ){
  5.  
  6.   setorder(assets, date)
  7.  
  8.   # start and end date of assets
  9.   start_date = max(assets[, date[1] , by = symbol]$V1)
  10.   end_date   = min(assets[, date[.N], by = symbol]$V1)
  11.   assets = assets[date %bw% c(start_date, end_date)]
  12.  
  13.   assets.matrix = dcast(assets, date ~ symbol, value.var = "return", mean, fill = 0)
  14.   assets.matrix = assets.matrix[, .SD * weights, date]
  15.   assets.matrix[, return := rowSums(.SD[,-1])]
  16.   if(full)
  17.     assets.matrix[]
  18.   else
  19.     assets.matrix[, .(date, return)]
  20.  
  21. }
  22.  
  23.  
  24. # Названия бумаг
  25. symbols = sort(c( "MAGN", "GMKN", "TATN"))
  26.  
  27. # Собираем данные с финама
  28. candles = lapply( symbols, function( s ) get_finam_data( s, from = '2007-01-01', to = '2007-12-31')[, .( date, close, symbol = s ) ] )
  29. # Объединяем данные в одну таблицу
  30. candles = rbindlist( candles )
  31. # Считаем доходности
  32. candles[, return := close / shift( close, fill = close[1] ) - 1, by = symbol ]
  33.  
  34. # Считаем портфель
  35. portfolio = calc_simple_portfolio(candles, c( 0.33, 0.33, 0.33 ) )
  36.  
  37. # Рисуем график
  38. plot_dts(portfolio[,.(date, pnl = cumprod(1+return))])
  39.  
  40.  
  41.  
  42. dt = fread("
  43. from          to            assets
  44. 2007-01-01    2007-12-31    MAGN,GMKN,TATN
  45. 2008-01-01    2008-12-31    MAGN,GMKN
  46. ")
  47.  
  48. dt = dt[,{
  49.  
  50.   symbols = unlist(strsplit(assets, ","))
  51.   n_symb = length(symbols)
  52.  
  53.   candles = lapply( symbols, function( s ) get_finam_data( s, from = from, to = to)[, .( date, close, symbol = s ) ] )
  54.   candles = rbindlist( candles )
  55.  
  56.   # Считаем доходности
  57.   candles[, return := close / shift( close, fill = close[1] ) - 1, by = symbol ]
  58.  
  59.   # Считаем портфель
  60.   calc_simple_portfolio(candles, rep(1/n_symb, n_symb) )
  61.  
  62.  
  63. }, by = from]
  64.  
  65. plot_dts(dt[,.(date, pnl = cumprod(1+return))])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement