title: How to write a function for position sizing for investment portfolio
body: <p>I'm trying to write a function that applies position-sizing analysis for a portfolio of assets and I'm stuck on some basic coding in R. The basic set-up for one asset to determine the % allocation for the portfolio is a simple ratio:</p>
  
  <p><strong>fixed risk % for asset / asset's volatility</strong></p>
  
  <p>It's tricky with multiple assets because the total allocation % can't exceed 100%. Here's what I have so far, but I can't figure out how to finesse the code so that it makes sense in a total portfolio context. Any suggestions? Thanks in advance!</p>
  
  <pre><code># start by downloading 2 assets
  library(tseries)
  library(TTR)
  library(quantmod)
  library(PerformanceAnalytics)
  
  symbols = c("SPY","AGG")
  getSymbols(symbols, src='yahoo', from='2003-12-31')
  spy &lt;-Ad(SPY)
  agg &lt;-Ad(AGG)
  
  # calculate daily % return and rolling 100-day volatility (std dev)
  spy.ret &lt;-na.omit(ROC(spy,1,"discrete"))
  agg.ret &lt;-na.omit(ROC(agg,1,"discrete"))
  
  # calculate annualized volatility 
  spy.sd &lt;-na.omit(rollapplyr(spy.ret,100,sd))*sqrt(252)
  agg.sd &lt;-na.omit(rollapplyr(agg.ret,100,sd))*sqrt(252)
  
  # calculate position size (as %) for each asset with fixed 2% risk factor
  # to determine fraction of the account size
  spy.pos.size &lt;-.02/spy.sd
  agg.pos.size &lt;-.02/agg.sd
  
  # combine position size data and
  # sum for aggregate portfolio allocation
  spy.agg.pos.size &lt;-cbind(spy.pos.size,agg.pos.size)
  port.pos.size &lt;-apply(spy.agg.pos.size,1,sum)
  </code></pre>
  
  <p>Check the max allocation total: shows that the % exceeds 100% (i.e., 1.0)</p>
  
  <pre><code>&gt; max(port.pos.size)
  [1] 1.131178
  </code></pre>
  
  <p>Any recommendations on how to keep total allocation at/below 100% while retaining the allocation recommendations in the individual position size calculations for each asset? Thanks again!!!</p>