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)
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)
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)
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