def plot_index(index_name, benchmark_name): # Load Index Data File index_path = c.path_dict['index'] index_file = c.file_dict['index_r'] % index_name df = u.read_csv(index_path + index_file) # Plot Figure fig, (ax1, ax2, ax3) = plt.subplots(3, sharex=True) fig.set_size_inches(32, 18) # Define Font font = { 'family': 'serif', 'color': 'black', 'weight': 'normal', 'size': 18, } # Plot Sub-figure 1 title = '%s vs. %s' % (index_name, benchmark_name) ax1.set_title(title, fontdict=font) ax1.set_xlabel('', fontdict=font) ax1.set_ylabel('Ratio', fontdict=font) for column in ['ratio', 'b_ratio']: df.plot(x='date', y=column, ax=ax1) # Plot Sub-figure 2 title = 'Index %s' % index_name ax2.set_title(title, fontdict=font) ax2.set_xlabel('', fontdict=font) ax2.set_ylabel('Close Price', fontdict=font) df.plot(x='date', y='index', ax=ax2) # Plot Sub-figure 3 title = 'Index %s' % benchmark_name ax3.set_title(title, fontdict=font) ax3.set_xlabel('', fontdict=font) ax3.set_ylabel('Close Price', fontdict=font) df.plot(x='date', y='b_index', ax=ax3) # Common Format for Both Sub-figures for ax in [ax1, ax2, ax3]: ax.grid(True) fig.autofmt_xdate() fig.tight_layout() plt.setp(plt.gca().get_xticklabels(), rotation=30) plt.show() # Save Figure fig_key = 'fig_index' fig_path = c.path_dict[fig_key] fig_file = c.file_dict[fig_key] % (index_name + '_' + u.dateToStr(u.today())) u.saveFigure(fig, fig_path, fig_file)
def plot_index_series(index_names, series_name, benchmark_name): # Load Index Data Files series_path = c.path_dict['index'] series_file = c.file_dict['index_r'] % series_name df = u.read_csv(series_path + series_file) # Plot Figure fig = plt.figure(figsize=(32, 18), dpi=72, facecolor="white") axes = plt.subplot(111) axes.cla() # Clear Axes # Define Font font = { 'family': 'serif', 'color': 'black', 'weight': 'normal', 'size': 18, } # Plot Sub-figure 1 title = '%s vs. %s' % (series_name, benchmark_name) plt.title(title, fontdict=font) axes.set_xlabel('', fontdict=font) axes.set_ylabel('Ratio', fontdict=font) df.plot(x='date', y='ratio_benchmark', ax=axes, color='grey', lw=2.0, ls='--') index_number = len(index_names) for i in range(index_number): index_name = index_names[i] column = 'ratio_' + index_name df.plot(x='date', y=column, ax=axes) # Common Format for Both Sub-figures axes.grid(True) fig.autofmt_xdate() fig.tight_layout() plt.setp(plt.gca().get_xticklabels(), rotation=30) plt.show() # Save Figure fig_key = 'fig_index' fig_path = c.path_dict[fig_key] fig_file = c.file_dict[fig_key] % (series_name + '_' + u.dateToStr(u.today())) u.saveFigure(fig, fig_path, fig_file)
def plot_HPE(stock_id, period, ratio): # Check Input Parameters if not isinstance(stock_id, str) or not isinstance(period, str): print('Incorrect type of one or more input parameters!') raise SystemExit # Check Period period_types = ['W', 'M', 'Q'] if not period in period_types: print('Un-supported period type - should be one of:', period_types) raise SystemExit # Check Ratio ratio_types = ['PE', 'EP'] if not ratio in ratio_types: print('Un-supported ratio type - should be one of:', ratio_types) raise SystemExit # Check Pre-requisite: HPE File key = 'hpe' if ratio == 'PE' else 'hep' path = c.path_dict[key] % period file = c.file_dict[key] % (period, stock_id) hpe_fullpath = path + file if not u.hasFile(hpe_fullpath): print('Require File Exists:', hpe_fullpath) raise SystemExit # Load Data File hpe = loadHPE(stock_id=stock_id, period=period, ratio=ratio) # Plot Figure fig, (ax1, ax2) = plt.subplots(2, sharex=True) # fig = plt.figure() fig.set_size_inches(32, 18) # Plot Sub-figure 1 # ax1 = plt.subplot(211) ratio_name = 'P/E Ratio' if ratio == 'PE' else 'E/P Ratio' title = ratio_name + ' Ratio of Stock %s' % stock_id ax1.set_title(title, fontsize=14) ax1.set_xlabel('') ax1.set_ylabel(ratio_name) if ratio == 'PE': # hpe.plot(x='date', y='pe_high', ax=ax1) hpe.plot(x='date', y='pe_close', ax=ax1) # hpe.plot(x='date', y='pe_low', ax=ax1) else: # hpe.plot(x='date', y='ep_high', ax=ax1) hpe.plot(x='date', y='ep_close', ax=ax1) # hpe.plot(x='date', y='ep_low', ax=ax1) # Plot Sub-figure 2 # ax2 = plt.subplot(212) ax2.set_title('Price of Stock %s' % stock_id, fontsize=14) ax2.set_xlabel('') ax2.set_ylabel('Price') # hpe.plot(x='date', y='high', ax=ax2) hpe.plot(x='date', y='close', ax=ax2) # hpe.plot(x='date', y='low', ax=ax2) # Common Format for Both Sub-figures for ax in [ax1, ax2]: ax.grid(True) fig.autofmt_xdate() fig.tight_layout() plt.setp(plt.gca().get_xticklabels(), rotation=30) plt.show() # Save Figure fig_key = 'fig_hpe' if ratio == 'PE' else 'fig_hep' fig_path = c.path_dict[fig_key] % period fig_file = c.file_dict[fig_key] % (period, stock_id) u.saveFigure(fig, fig_path, fig_file)
def plot_coefficient_price(stock_ids, allprice, postfix, series_name, benchmark_name): # If want to debug benchmark only (without stocks), set below flag to True. debug_benchmark_only = False # Extract Stock Prices and Normalize Them row_number = len(allprice) stock_number = len(stock_ids) columns = ['date', benchmark_name] if not debug_benchmark_only: for i in range(stock_number): stock_id = u.stockID(stock_ids[i]) columns.append(stock_id) prices = u.createDataFrame(row_number, columns) prices['date'] = allprice['date'] prices[benchmark_name] = allprice['close'] if not debug_benchmark_only: for i in range(stock_number): stock_id = u.stockID(stock_ids[i]) prices[stock_id] = allprice['close_' + stock_id] if debug_benchmark_only: print('Original Price') print(prices) # Normalize Price for i in range(1, len(columns)): column = columns[i] prices[column] = normalize_price(prices[column]) if debug_benchmark_only: print('Normalized Price') print(prices) # Calculate Relative Price w.r.t. First Valid Price for i in range(1, len(columns)): column = columns[i] row = -1 for j in range(row_number): if not np.isnan(prices.ix[j, column]): # Find first valid price row = j break if row != -1: if debug_benchmark_only: print('Row =', row) ref_price = prices.ix[ row, column] # Need to be cached in the first place as it will be normalized to one later. for j in range(row, row_number): cur_price = prices.ix[j, column] if not np.isnan(cur_price): prices.ix[ j, column] = 1.0 + (cur_price - ref_price) / ref_price if debug_benchmark_only: print('Relative Price') print(prices) # Plot Figure fig = plt.figure(figsize=(32, 18), dpi=72, facecolor="white") axes = plt.subplot(111) axes.cla() # Clear Axes # Define Font font = { 'family': 'serif', 'color': 'black', 'weight': 'normal', 'size': 18, } # Plot Sub-figure 1 title = '%s vs. %s' % (series_name, benchmark_name) plt.title(title, fontdict=font) axes.set_xlabel('', fontdict=font) axes.set_ylabel('Ratio', fontdict=font) prices.plot(x='date', y=benchmark_name, ax=axes, color='grey', lw=2.0, ls='--') if not debug_benchmark_only: for i in range(stock_number): column = u.stockID(stock_ids[i]) prices.plot(x='date', y=column, ax=axes) # Common Format for Both Sub-figures axes.grid(True) fig.autofmt_xdate() fig.tight_layout() plt.setp(plt.gca().get_xticklabels(), rotation=30) plt.show() # Save Figure fig_key = 'fig_coef' fig_path = c.path_dict[fig_key] fig_name = '_'.join( [postfix, series_name, 'vs', benchmark_name, u.dateToStr(u.today())]) fig_file = c.file_dict[fig_key] % fig_name u.saveFigure(fig, fig_path, fig_file)