-
Notifications
You must be signed in to change notification settings - Fork 6
/
036_ratios_peg
executable file
·63 lines (50 loc) · 2.65 KB
/
036_ratios_peg
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
#!/usr/bin/env python2
import fnmatch, re
import os
import pandas as pd
from dateutil.relativedelta import relativedelta
import modules.config_details as conf_info
DATE_FORMAT = '%Y-%m-%d'
PE_DATE_COLUMN_NAME = 'Date'
EPS_DATE_COLUMN_NAME = 'Date'
csv_column_dateparse = lambda x: pd.datetime.strptime(x, DATE_FORMAT)
def get_ticker_eps(ticker):
eps_df = pd.read_csv(conf_info.ratios_dir + conf_info.get_eps_filename(ticker), parse_dates=[EPS_DATE_COLUMN_NAME], date_parser=csv_column_dateparse)
return eps_df
def calculate_peg_series(eps_df, pe_df):
peg_df = pd.DataFrame(columns=['Date','PEG'])
for index_pe_df,pe_row in pe_df.iterrows():
# finding relevant dates for the calculation
current_pe_date = pe_row[PE_DATE_COLUMN_NAME]
index_closest_current_eps = eps_df[EPS_DATE_COLUMN_NAME].searchsorted(current_pe_date)
one_quarter_before_pe_date = current_pe_date + relativedelta(months=-3)
index_closest_one_quarter_before_eps = eps_df[EPS_DATE_COLUMN_NAME].searchsorted(one_quarter_before_pe_date)
# getting the data according to the just found indexes
row_current_eps = eps_df.loc[index_closest_current_eps]
row_one_quarter_before_eps = eps_df.loc[index_closest_one_quarter_before_eps]
eps_current = row_current_eps['EPS'].item()
eps_one_quarter_before = row_one_quarter_before_eps['EPS'].item()
# calculating the PEG
eps_growth_rate = (eps_current - eps_one_quarter_before)
if (eps_growth_rate != 0):
current_peg = pe_row['PE_median'] / eps_growth_rate
# storing the PEG in the DataFrame
peg_df.loc[index_pe_df] = [current_pe_date,current_peg]
else:
# TODO something about 0 deltas?
current_peg = float('NaN')
print 'No PEG to save as the delta is 0'
return peg_df
def process_pe_ratios(files_dir):
pe_median_pattern = re.compile(conf_info.pe_median_filename_regex)
for file_name in os.listdir(files_dir):
if fnmatch.fnmatch(file_name, conf_info.pe_median_filename_glob):
current_ticker = pe_median_pattern.search(file_name).group(1)
print 'Processing P/E file:', file_name, 'for ticker', current_ticker
current_ticker_eps_df = get_ticker_eps(current_ticker)
current_ticker_pe_median_df = pd.read_csv(files_dir + file_name, parse_dates=[PE_DATE_COLUMN_NAME], date_parser=csv_column_dateparse)
peg_df = calculate_peg_series(current_ticker_eps_df, current_ticker_pe_median_df)
current_filename_with_path = conf_info.ratios_dir + conf_info.get_peg_filename(current_ticker)
print 'Saving PEG series to:', current_filename_with_path
peg_df.to_csv(current_filename_with_path, index=False)
process_pe_ratios(conf_info.ratios_dir)