title: Is there a python library to calculate time weighted returns based on portfolio weights and stock prices?
body: <p>I have a question in regards to calculating Time-weighted returns in Python.
  Is there any library in python to calculate time-weighted returns?
  Or is there any way to calculate time weight using the portfolio weightage and daily stock price?</p>
  
  <p>I have actually written a code but would want to seek advice on this question before I continue.</p>
  
  <p>Thanks</p>
  
  <p>Using these assumptions for my question.</p>
  
  <p><strong>Assumption1:</strong> </p>
  
  <p>Period 1: $5K (20%) @ 5,000 shares at $1 each</p>
  
  <p>Period 2: $10K (Period 1+2 = 60%) @ 5,000 shares at $2 each</p>
  
  <p>Period 3: $10K (100%)</p>
  
  <p><strong>Assumption 2:</strong> </p>
  
  <p>Period 1: Share price at $1, (Jan price)</p>
  
  <p>Period 2: Share price at $2, (Aug price)</p>
  
  <p>After searching in google, most solutions are calculated using the amounts. Assuming calculation in Dec 31 and share price is $1.3 at Dec 31</p>
  
  <p>Period 1: ((5,000 shares * $2)-5000 shares *$1)/$5000 = (10,000-5000)/5000 = 100%</p>
  
  <p>Period 2: (10,000 shares * $1.3)- ((5,000 shares * $2)+$10,000)/((5,000 shares * $2)+$10,000) = ($13,000-($20,000))/$20,000 = -35%</p>
  
  <p>Time weighted for 2 period = ((1.1)*(0.65)) -1 = -0.29%</p>
  
  <pre><code>ticker = "TOT"
  df_period = [] # To store dataframes of each period
  time_wgt_period = [] # To store time period values
  product = 1 
  
  def absoluteReturn(DF):
  
      absoluteReturn = ((DF["Adj Close"][-1]-DF["Adj Close"][0])/DF["Adj Close"][0])
  
      return absoluteReturn
  
  # Get all different investment periods 
  period1 = pdr.DataReader(ticker, data_source='yahoo', start=datetime.datetime(2013, 4, 26), end=datetime.datetime(2013, 6, 25))
  period2 = pdr.DataReader(ticker, data_source='yahoo', start=datetime.datetime(2013, 6, 26), end=datetime.datetime(2015, 1, 8))
  period3 = pdr.DataReader(ticker, data_source='yahoo', start=datetime.datetime(2015, 1, 9),  end=datetime.datetime(2016, 1, 17))
  period4 = pdr.DataReader(ticker, data_source='yahoo', start=datetime.datetime(2016, 2, 18), end=date.today())
  
  #Append all dataframe periods in a list so I can loop to call the CAGR function
  df_period.append(period1)
  df_period.append(period2)
  df_period.append(period3)
  df_period.append(period4)
  
  # Using for loop to call absolute return function and plus 1 to get time weighted values
  for i in df_period:
      time_wgt_period.append(absoluteReturn(i)+1)
  
  #weights = np.array([0.20, 0.20, 0.20, 0.40,])
  #np.dot(annualReturn_period, weights)    
  
  # Using for loop to get nultiply each time period value
  for k in time_wgt_period:
      #print("Product value: " + str(product) + "*" + str(k))
      product = k*product
  
  
  print ("Time Weighted Return for " +ticker+": "+str(round((product-1), 2) * 100) + "%")
  </code></pre>