r - dataframe math to calculate profit based on indicator -


simple explanation: goal figure out how profit column shown below. trying calculate difference in val every pair of changing values (-1 1 , 1 -1).

  1. if starting indicator 1 or -1 store value.
  2. find next indicator opposite (so -1 on row 3). save val. subtract first value (.85.-.84). store in profit column.
  3. repeat

specific case

  1. go until find next opposite val (on row 4). save value. subtract values, save in profit column. ()
  2. go until find next opposite val (on row 8). save value. subtract values, save in profit column. financial explanation (if useful) trying write function calculate profit given column of values , column of indicators (buy/sell/hold). know implemented in few of big packages (quantmod, quantstrat), cant seem find simple way it.

    df<- 

    data.frame(val=c(.84,.83,.85,.83,.83,.84,.85,.81),indicator=c(1,0,-1,1,0,1,1,-1))

    df val      indicator  profit 1 0.84         1       na 2 0.83         0       na 3 0.85        -1       .01  based on: (.85-.84) 1 one -1 4 0.83         1       .02  based on (.85-.83) -1 1 5 0.83         0       na  6 0.84         1       na  7 0.85         1       na 8 0.81        -1       -.02  based on (.81-.83) last change (row 4)  

notes

  • multiple indicators should ignored (1111) means nothing beyond first 1 should stored. (line 4 stored, lines 5,6,7 not)
  • ignore 0, holds not change profit calculation

i happy provide more info if needed.

it easier me work out in head after splitting problem 2 parts, correspond 2 loops shown below. first part involves flagging rows there change in indicator value, while second part involves subtracting val's relevant rows (i.e., selected in part 1). fyi, assume meant put -.02 row 4 in example? if not, please clarify rows subtracted when calculating profit.

data.frame(val=c(.84,.83,.85,.83,.83,.84,.85,.81),            indicator=c(1,0,-1,1,0,1,1,-1)) -> x  x$num <- seq_along(x$val) x$rollingprof <- na # start indicator = 1  indicator <- 1 value <- .84  (i in 1:(nrow(x) - 1)) {             x[i + 1, "indicator"] -> next_     if (indicator * -1 == next_) {         1 -> x[i + 1, "rollingprof"]         indicator <- next_     }  }  x[!is.na(x$rollingprof), c("val", "num")] -> q (i in 2:nrow(q)) {     q[i, "val"] - q[i - 1, "val"] -> q[i, "change"] } 

Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -