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