-
Notifications
You must be signed in to change notification settings - Fork 6
/
040_ticker_plots
executable file
·135 lines (118 loc) · 5.07 KB
/
040_ticker_plots
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#!/usr/bin/env python2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import pandas as pd
import modules.config_details as conf_info
import modules.tickers_helpers as helpers
dates_formatter = '%Y-%m-%d'
dateparse = lambda x: pd.datetime.strptime(x, dates_formatter)
def load_df(path, ticker, date_field):
if (False == isinstance(path, basestring)):
dfs = []
for curr_path in path:
file_path = curr_path + ticker.upper() + '.csv'
curr_df = pd.read_csv(file_path, parse_dates=[date_field], date_parser=dateparse)
dfs.append(curr_df)
merged_df = pd.concat(dfs)
return merged_df
else:
file_path = path + ticker.upper() + '.csv'
df = pd.read_csv(file_path, parse_dates=[date_field], date_parser=dateparse)
return df;
def build_plot(cur_dict, ticker, num_rows_num_cols_tuple, shared_axis):
current_df = load_df(cur_dict['path_prefixes'], ticker, cur_dict['date_field_name'])
ax = plt.subplot2grid(num_rows_num_cols_tuple, (cur_dict['row_position'], 0), rowspan=cur_dict['rowspan'])
if (shared_axis):
ax = plt.subplot2grid(num_rows_num_cols_tuple, (cur_dict['row_position'], 0), rowspan=cur_dict['rowspan'], sharex=shared_axis)
# print 'Shared axis!'
ax.plot(current_df[cur_dict['date_field_name']],current_df[cur_dict['value_field_name']])
ax.grid(True)
ax.yaxis.set_major_locator(mticker.MaxNLocator(nbins='5', prune='upper'))
plt.ylabel(cur_dict['y_label'], rotation=0)
# ax.text(0,0, cur_dict['y_label'], va='top', transform=ax.transAxes)
return ax
eps_dict = {
'path_prefixes' : conf_info.ratios_dir + conf_info.eps_filename_prefix,
'date_field_name' : 'Date',
'value_field_name' : 'EPS',
'y_label' : 'EPS',
'row_position' : 0,
'rowspan' : 1
}
peg_dict = {
'path_prefixes' : conf_info.ratios_dir + conf_info.peg_filename_prefix,
'date_field_name' : 'Date',
'value_field_name' : 'PEG',
'y_label' : 'PEG',
'row_position' : 1,
'rowspan' : 1
}
pe_median_dict = {
'path_prefixes' : conf_info.ratios_dir + conf_info.pe_median_filename_prefix,
'date_field_name' : 'Date',
'value_field_name' : 'PE_median',
'y_label' : 'P/E',
'row_position' : 2,
'rowspan' : 1
}
outstanding_shares_dict = {
'path_prefixes' : conf_info.fundamentals_dir + conf_info.out_shares_filename_prefix,
'date_field_name' : 'Date',
'value_field_name' : 'Value',
'y_label' : 'Outstanding \n shares',
'row_position' : 3,
'rowspan' : 1
}
closing_price_dict = {
'path_prefixes' : [conf_info.stock_prices_dir + conf_info.stock_prices_ticker_pre_filename_prefix, conf_info.stock_prices_dir + conf_info.stock_prices_ticker_post_filename_prefix],
'date_field_name' : 'Date',
'value_field_name' : 'Adj Close',
'y_label' : 'Stock \n closing price',
'row_position' : 4,
'rowspan' : 3
}
series_dicts = {
'eps_data': eps_dict,
'peg_data': peg_dict,
'pe_median_data': pe_median_dict,
'outstanding_shares_data': outstanding_shares_dict,
'closing_price_data': closing_price_dict
}
def get_total_graph_rows(dictionaries):
available_series = dictionaries.keys()
rows_each = map(lambda curr_series: dictionaries[curr_series]['rowspan'], available_series)
return reduce(lambda x, y: x+y, rows_each)
def get_plt(dicts, ticker):
total_rows = get_total_graph_rows(dicts)
num_rows_num_cols_tuple = (total_rows,1)
plt.suptitle(ticker + ' ticker')
ax_eps = build_plot(dicts['eps_data'], ticker, num_rows_num_cols_tuple, None)
ax_peg = build_plot(dicts['peg_data'], ticker, num_rows_num_cols_tuple, ax_eps)
ax_pe_median = build_plot(dicts['pe_median_data'], ticker, num_rows_num_cols_tuple, ax_eps)
ax_outstanding_shares = build_plot(dicts['outstanding_shares_data'], ticker, num_rows_num_cols_tuple, ax_eps)
ax_closing_price = build_plot(dicts['closing_price_data'], ticker, num_rows_num_cols_tuple, ax_eps)
plt.xlabel('Date')
plt.xticks(rotation=45)
plt.setp(ax_eps.get_xticklabels(), visible=False)
plt.setp(ax_pe_median.get_xticklabels(), visible=False)
plt.setp(ax_peg.get_xticklabels(), visible=False)
plt.setp(ax_outstanding_shares.get_xticklabels(), visible=False)
plt.subplots_adjust(left=.16,right=.96,top=.94,bottom=.16,hspace=0)
ticker_fig = plt.gcf() # for "get current figure"
ticker_fig.savefig(conf_info.graphs_dir + conf_info.get_tickers_plot_filename(ticker), dpi=300, format='png')
return plt
def store_plot(dicts, ticker):
ticker_plt = get_plt(dicts, ticker)
# ticker_plt.show()
ticker_plt.cla() # clears the current axes if you have multiple subplots in the same figure
ticker_plt.clf() # clear figure
def store_plots(dicts, tickers):
for ticker in tickers:
try:
print 'Processing ticker:', ticker
store_plot(dicts, ticker)
except Exception, e:
print 'Failed to process ticker: ' + ticker + ' ~~~', str(e)
store_plots(series_dicts, helpers.get_all_tickers_lists_csv_files())