Example #1
0
  def print_report(yahoo_tables, do_plot=False):
    """Given a yahoo stock table prints a report.

    average return, standard deviation, total return
    """
    results = []
    headers = ['Date Range', 'Average Return (%)', 'Total Return (%)', 'Standard deviation', 
               'Closing stock range']
    results.append({"cols": headers})

    total_returns = []
    for yahoo_table in yahoo_tables:
      try:
        closing_vals = yahoo_table.getAllClosing()
        dates = yahoo_table.getAllDates()
        first_col_title = '%s to %s' % (dates[0], dates[-1])
        (line, total_return) = Question1.create_report_line(closing_vals, first_col_title)
        results.append(line)
        total_returns.append(total_return)
        if do_plot:
          closing_vals = yahoo_table.getAllClosing()
          Plotter.plot(StockUtils.getPercentChanges(closing_vals)) 
      except Exception:
        pass
    # Only do this for more or one tables.
    if len(yahoo_tables) <= 1:
      return results
    # Compound your month to month returns.
    all_return = StockUtils.getCompoundedReturn(total_returns)
    gain = all_return - 1
    gain_line = {"cols": ['Total return by putting in each month style: %.2f percent.' % (
      gain * 100)]}
    results.append(gain_line)
    return results
Example #2
0
 def create_report_line(values, first_col_title):
   avg_return = StockUtils.getAverageReturn(values)
   total_return = StockUtils.getTotalReturn(values)
   stdev_return = StockUtils.getStdevReturn(values)
   closing_val_range = '%.2f to %.2f' % (values[0], values[-1])
   line = '%s\t%.2f\t%.2f\t%.2f\t%s' % (first_col_title, avg_return * 100, 
                                            total_return * 100, stdev_return * 100,
                                            closing_val_range)
   cols = {"cols": line.split("\t")}
   return (cols, total_return)
Example #3
0
 def getInformation(self, tbl):
   """Gets information tuple given a table of information."""
   values = tbl.getAllClosing()
   avg_return = StockUtils.getAverageReturn(values)
   total_return = StockUtils.getTotalReturn(values)
   stdev_return = StockUtils.getStdevReturn(values)
   info = {}
   info['avg_return'] = self.fformat(avg_return)
   info['total_return'] = self.fformat(total_return)
   info['stdev_return'] = self.fformat(stdev_return)
   dates = tbl.getAllDates()
   date_range = '%s to %s' % (dates[0], dates[-1])
   info['date_range'] = date_range
   closing_val_range = '%.2f to %.2f' % (values[0], values[-1])
   info['closing_range'] = closing_val_range
   return info
Example #4
0
 def get_return(self, stock):
   """Gets the return on a particular stock for the particular
      start_date and end_date.
       
      If one had a 5% gain, this will return 1.05
      If one had a 10% loss, this will return 0.9
   """
   ytable = YahooStockTable.make_data_table(stock, self.start_date, self.end_date)
   closing_values = ytable.getAllClosing()
   return StockUtils.getTotalReturn(closing_values)
Example #5
0
  def is_rebal_good(self, stocks, allocations, freq_days):
    """If I rebalance every freq_days, how does it affect my overall value?
    """
    all_rebal_vals = []
    for stock in stocks:
      rebal_vals = self.get_rebal_values(stock, freq_days)
      all_rebal_vals.append(rebal_vals)
    print 'Rebalance values:\n %s' % str(all_rebal_vals)

    # We need all the rebalance values to have the same length.
    # Assume we start off with a dollar.
    num_stocks = len(stocks)
    num_rebalances = len(all_rebal_vals[0])
    cur_value = 1
    for ind in range(0, num_rebalances - 1):
      returns = []
      # Get returns for stocks after each time period.
      for stock_ind in range(0, num_stocks):
        stock_rebal = all_rebal_vals[stock_ind] # Gets list of values.
        start = stock_rebal[ind]
        closing = stock_rebal[ind + 1]
        return_value = 1 + StockUtils.getTotalReturn([start, closing])
        returns.append(return_value)
      print 'Returns after rebalance %d is:\n %s' % (ind, str(returns))
      cur_return = Question4.get_returns_with_alloc(returns, allocations)
      cur_value = cur_value * cur_return
    print 'Rebalance return value: %.3f' % (cur_value)

    # Simple approach.
    simple_returns = []
    for stock_ind in range(0, num_stocks):
      stock_rebal = all_rebal_vals[stock_ind]
      cur_return = StockUtils.getTotalReturn(stock_rebal)
      simple_returns.append(cur_return)
    final_return = Question4.get_returns_with_alloc(simple_returns, allocations)
    print 'Simple return value: %.3f' % (1 + final_return)
Example #6
0
  def get_correlation(self, stocks):
    """Returns a correlation matrix defined by numpy.corrcoef.
      Basically if you pass in 3 stocks (0, 1, 2)
      Then corr[0][2] or corr[2][0] will tell the correlation of 0 and 2.
 
     Correlation is: Var(A * B) / Stdev(A) * Stdev(B)
    """
    lists_of_changes = []
    for stock in stocks:
      tbl = YahooStockTable.make_data_table(stock, self.start_date, self.end_date)
      closing = tbl.getAllClosing()
      pct_changes = StockUtils.getPercentChanges(closing)
      lists_of_changes.append(pct_changes)

    for changes in lists_of_changes:
      logging.info(self.fformat(changes))
    corr = numpy.corrcoef(lists_of_changes)
    return corr # correlation matrix