def eventmodMain(): start_month, start_day, start_year, end_month, end_day, end_year = modDatesReturn.get_dates( ) dt_start = dt.datetime(start_year, start_month, start_day) dt_end = dt.datetime(end_year, end_month, end_day) ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt.timedelta(hours=16)) dataobj = da.DataAccess('Yahoo') ls_symbols = dataobj.get_symbols_from_list('mrtevent') ls_symbols.append('SPY') ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close'] ldf_data = dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys) d_data = dict(zip(ls_keys, ldf_data)) for s_key in ls_keys: d_data[s_key] = d_data[s_key].fillna(method='ffill') d_data[s_key] = d_data[s_key].fillna(method='bfill') d_data[s_key] = d_data[s_key].fillna(1.0) df_events = find_events(ls_symbols, d_data) print "Creating Study" ret = ep.eventprofiler(df_events, d_data, i_lookback=20, i_lookforward=20, s_filename='MyEventStudy.pdf', b_market_neutral=True, b_errorbars=True, s_market_sym='SPY') if ret == 0: print 'No events' basic.print_clrscr() basic.print_logo() eventmenuMain()
def bollingerplotMain(): '''Main Function''' # List of symbols #ls_symbols = ["AAPL", "GOOG", "IBM", "MSFT"] ls_symbols = list() symbol = str(raw_input('<<< Enter the list of symbol: ')) symbols = symbol.upper() ls_symbols.append(symbols) start_month,start_day,start_year,end_month,end_day,end_year = modDatesReturn.get_dates() # We need closing prices so the timestamp should be hours=16. dt_timeofday = dt.timedelta(hours=16) # Get a list of trading days between the start and the end. dt_start = dt.datetime(start_year, start_month, start_day) dt_end = dt.datetime(end_year, end_month, end_day) # Creating an object of the dataaccess class with Yahoo as the source. ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday) c_dataobj = da.DataAccess('Yahoo') # Keys to be read from the data, it is good to read everything in one go. ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close'] # Reading the data, now d_data is a dictionary with the keys above. # Timestamps and symbols are the ones that were specified before. ldf_data = c_dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys) d_data = dict(zip(ls_keys, ldf_data)) # Copying close price into separate dataframe to find rets df_close = d_data['close'] df_mean = pd.rolling_mean(d_data['close'], 20) df_std = pd.rolling_std(d_data['close'], 20) df_bollinger = (df_close - df_mean) / (df_std) print df_bollinger.tail() # Plotting the prices with x-axis=timestamps plt.clf() plt.subplot(211) plt.plot(ldt_timestamps, df_close[symbols], label=symbols) plt.legend() plt.ylabel('Price') plt.xlabel('Date') plt.xticks(size='xx-small') plt.xlim(ldt_timestamps[0], ldt_timestamps[-1]) plt.grid(axis='both') plt.subplot(212) plt.plot(ldt_timestamps, df_bollinger[symbols], label='Bollinger') plt.axhline(1.0, color='r') plt.axhline(-1.0, color='r') plt.legend() plt.ylabel('Bollinger') plt.xlabel('Date') plt.xticks(size='xx-small') plt.xlim(ldt_timestamps[0], ldt_timestamps[-1]) #plt.savefig('bollingerplot.pdf', format='pdf') plt.grid(axis='both') plt.show()
def eventmodMain(): start_month,start_day,start_year,end_month,end_day,end_year = modDatesReturn.get_dates() dt_start = dt.datetime(start_year, start_month, start_day) dt_end = dt.datetime(end_year, end_month, end_day) ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt.timedelta(hours=16)) dataobj = da.DataAccess('Yahoo') ls_symbols = dataobj.get_symbols_from_list('mrtevent') ls_symbols.append('SPY') ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close'] ldf_data = dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys) d_data = dict(zip(ls_keys, ldf_data)) for s_key in ls_keys: d_data[s_key] = d_data[s_key].fillna(method = 'ffill') d_data[s_key] = d_data[s_key].fillna(method = 'bfill') d_data[s_key] = d_data[s_key].fillna(1.0) df_events = find_events(ls_symbols, d_data) print "Creating Study" ret = ep.eventprofiler(df_events, d_data, i_lookback=20, i_lookforward=20, s_filename='MyEventStudy.pdf', b_market_neutral=True, b_errorbars=True, s_market_sym='SPY') if ret == 0: print 'No events' basic.print_clrscr() basic.print_logo() eventmenuMain()
def _read_data(symbols, dates): timeofday = dt.timedelta(hours=16) timestamps = du.getNYSEdays(dates[0], dates[-1] + dt.timedelta(days=1), timeofday) dataobj = da.DataAccess('Yahoo') close = dataobj.get_data(timestamps, symbols, "close", verbose=True) close = close.fillna(method='ffill') close = close.fillna(method='bfill') return close, timestamps
def daily(lfFunds): """ @summary Computes daily returns centered around 0 @param funds: A time series containing daily fund values @return an array of daily returns """ if type(lfFunds) == type(pd.Series()): ldt_timestamps = du.getNYSEdays(lfFunds.index[0], lfFunds.index[-1], dt.timedelta(hours=16)) lfFunds = lfFunds.reindex(index=ldt_timestamps, method='ffill') nds = np.asarray(deepcopy(lfFunds)) s= np.shape(nds) if len(s)==1: nds=np.expand_dims(nds,1) returnize0(nds) return(nds)
def __init__(self): # List of symbols self.ls_symbols = list() len_sym = basic.get_num_sym() for i in range(len_sym): symbols = str(raw_input('<<< Enter symbols:' )) self.ls_symbols.append(symbols) start_month,start_day,start_year,end_month,end_day,end_year = modDatesReturn.get_dates() dt_start = dt.datetime(start_year, start_month, start_day) dt_end = dt.datetime(end_year, end_month, end_day) # We need closing prices so the timestamp should be hours=16. dt_timeofday = dt.timedelta(hours=16) # Get a list of trading days between the start and the end. self.ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday) # Creating an object of the dataaccess class with Yahoo as the source. c_dataobj = da.DataAccess('Yahoo') # Keys to be read from the data, it is good to read everything in one go. ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close'] # Reading the data, now d_data is a dictionary with the keys above. # Timestamps and symbols are the ones that were specified before. ldf_data = c_dataobj.get_data(self.ldt_timestamps, self.ls_symbols, ls_keys) self.d_data = dict(zip(ls_keys, ldf_data)) # Getting the numpy ndarray of close prices. self.na_price = self.d_data['close'].values
def __init__(self): # List of symbols self.ls_symbols = list() len_sym = basic.get_num_sym() for i in range(len_sym): symbols = str(raw_input('<<< Enter symbols:')) self.ls_symbols.append(symbols) start_month, start_day, start_year, end_month, end_day, end_year = modDatesReturn.get_dates( ) dt_start = dt.datetime(start_year, start_month, start_day) dt_end = dt.datetime(end_year, end_month, end_day) # We need closing prices so the timestamp should be hours=16. dt_timeofday = dt.timedelta(hours=16) # Get a list of trading days between the start and the end. self.ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday) # Creating an object of the dataaccess class with Yahoo as the source. c_dataobj = da.DataAccess('Yahoo') # Keys to be read from the data, it is good to read everything in one go. ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close'] # Reading the data, now d_data is a dictionary with the keys above. # Timestamps and symbols are the ones that were specified before. ldf_data = c_dataobj.get_data(self.ldt_timestamps, self.ls_symbols, ls_keys) self.d_data = dict(zip(ls_keys, ldf_data)) # Getting the numpy ndarray of close prices. self.na_price = self.d_data['close'].values
def bollingerplotMain(): '''Main Function''' # List of symbols #ls_symbols = ["AAPL", "GOOG", "IBM", "MSFT"] ls_symbols = list() symbol = str(raw_input('<<< Enter the list of symbol: ')) symbols = symbol.upper() ls_symbols.append(symbols) start_month, start_day, start_year, end_month, end_day, end_year = modDatesReturn.get_dates( ) # We need closing prices so the timestamp should be hours=16. dt_timeofday = dt.timedelta(hours=16) # Get a list of trading days between the start and the end. dt_start = dt.datetime(start_year, start_month, start_day) dt_end = dt.datetime(end_year, end_month, end_day) # Creating an object of the dataaccess class with Yahoo as the source. ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday) c_dataobj = da.DataAccess('Yahoo') # Keys to be read from the data, it is good to read everything in one go. ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close'] # Reading the data, now d_data is a dictionary with the keys above. # Timestamps and symbols are the ones that were specified before. ldf_data = c_dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys) d_data = dict(zip(ls_keys, ldf_data)) # Copying close price into separate dataframe to find rets df_close = d_data['close'] df_mean = pd.rolling_mean(d_data['close'], 20) df_std = pd.rolling_std(d_data['close'], 20) df_bollinger = (df_close - df_mean) / (df_std) print df_bollinger.tail() # Plotting the prices with x-axis=timestamps plt.clf() plt.subplot(211) plt.plot(ldt_timestamps, df_close[symbols], label=symbols) plt.legend() plt.ylabel('Price') plt.xlabel('Date') plt.xticks(size='xx-small') plt.xlim(ldt_timestamps[0], ldt_timestamps[-1]) plt.grid(axis='both') plt.subplot(212) plt.plot(ldt_timestamps, df_bollinger[symbols], label='Bollinger') plt.axhline(1.0, color='r') plt.axhline(-1.0, color='r') plt.legend() plt.ylabel('Bollinger') plt.xlabel('Date') plt.xticks(size='xx-small') plt.xlim(ldt_timestamps[0], ldt_timestamps[-1]) #plt.savefig('bollingerplot.pdf', format='pdf') plt.grid(axis='both') plt.show()
def portfolioAnalyz(): ''' Main Function This method will analyze your performance of portfolio from date specified. Create Excel sheet with your portfolio allocation and it will be read by this method to perform analysis ''' # Reading the portfolio print '<<<(s) Update your portfolioanalyze.csv file..' if os.path.isfile("C:\MRT3.0\portfolioanalyze.csv"): na_portfolio = np.loadtxt('portfolioanalyze.csv', dtype='S5,f4', delimiter=',', comments="#", skiprows=1) else: print '<<<(w) File Not Found: portfolioanalyze.csv ' sleep(2) basic.go_back() # Sorting the portfolio by symbol name na_portfolio = sorted(na_portfolio, key=lambda x: x[0]) print na_portfolio # Create two list for symbol names and allocation ls_port_syms = [] lf_port_alloc = [] for port in na_portfolio: ls_port_syms.append(port[0]) lf_port_alloc.append(port[1]) # Creating an object of the dataaccess class with Yahoo as the source. c_dataobj = da.DataAccess('Yahoo') ls_all_syms = c_dataobj.get_all_symbols() # Bad symbols are symbols present in portfolio but not in all syms ls_bad_syms = list(set(ls_port_syms) - set(ls_all_syms)) if len(ls_bad_syms) != 0: print "<<<(w) Portfolio contains bad symbols : ", ls_bad_syms for s_sym in ls_bad_syms: i_index = ls_port_syms.index(s_sym) ls_port_syms.pop(i_index) lf_port_alloc.pop(i_index) # Reading the historical data. print '<<<(i) Reading Historical data...' #dt_end = dt.datetime(2011, 1, 1) #dt_start = dt_end - dt.timedelta(days=95) # Three years # We need closing prices so the timestamp should be hours=16. dt_timeofday = dt.timedelta(hours=16) start_month, start_day, start_year, end_month, end_day, end_year = modDatesReturn.get_dates( ) dt_start = dt.datetime(start_year, start_month, start_day) dt_end = dt.datetime(end_year, end_month, end_day) # Get a list of trading days between the start and the end. ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday) # Keys to be read from the data, it is good to read everything in one go. ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close'] # Reading the data, now d_data is a dictionary with the keys above. # Timestamps and symbols are the ones that were specified before. ldf_data = c_dataobj.get_data(ldt_timestamps, ls_port_syms, ls_keys) d_data = dict(zip(ls_keys, ldf_data)) # Copying close price into separate dataframe to find rets df_rets = d_data['close'].copy() # Filling the data. df_rets = df_rets.fillna(method='ffill') df_rets = df_rets.fillna(method='bfill') # Numpy matrix of filled data values na_rets = df_rets.values # returnize0 works on ndarray and not dataframes. tsu.returnize0(na_rets) # Estimate portfolio returns na_portrets = np.sum(na_rets * lf_port_alloc, axis=1) na_port_total = np.cumprod(na_portrets + 1) na_component_total = np.cumprod(na_rets + 1, axis=0) # Plotting the results plt.clf() #fig = plt.figure() #fig.add_subplot(111) plt.plot(ldt_timestamps, na_component_total) plt.plot(ldt_timestamps, na_port_total) ls_names = ls_port_syms ls_names.append('Portfolio') plt.legend(ls_names) plt.ylabel('Cumulative Returns') plt.xlabel('Date') #fig.autofmt_xdate(rotation=45) plt.show()
def bestPort(): '''Main Function''' # List of symbols #ls_symbols = ["AXP", "HPQ", "IBM", "HNZ"] ls_symbols = list() try: len_sym = input('<<< How many symbol(Works only for 4 symbols): ') if len_sym > 4 or len_sym <= 0 or len_sym < 4: print '<<<(w) Works only for 4 symbols..\n' basic.print_logo() basic.print_clrscr() basic.go_back() except ValueError: basic.print_logo() basic.print_clrscr() basic.go_back() except SyntaxError: basic.print_logo() basic.print_clrscr() basic.go_back() except NameError: basic.print_logo() basic.print_clrscr() basic.go_back() for i in range(len_sym): symbols = str(raw_input('<<< Enter the list of symbols: ')) ls_symbols.append(symbols) ## Start and End date of the charts start_month, start_day, start_year, end_month, end_day, end_year = modDatesReturn.get_dates( ) dt_start = dt.datetime(start_year, start_month, start_day) dt_end = dt.datetime(end_year, end_month, end_day) # Start and End date of the charts #dt_start = dt.datetime(2010, 1, 1) #dt_end = dt.datetime(2010, 12, 31) # We need closing prices so the timestamp should be hours=16. dt_timeofday = dt.timedelta(hours=16) # Get a list of trading days between the start and the end. ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday) # Creating an object of the dataaccess class with Yahoo as the source. c_dataobj = da.DataAccess('Yahoo') # Keys to be read from the data, it is good to read everything in one go. ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close'] # Reading the data, now d_data is a dictionary with the keys above. # Timestamps and symbols are the ones that were specified before. ldf_data = c_dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys) d_data = dict(zip(ls_keys, ldf_data)) # Copying close price into separate dataframe to find rets df_rets = d_data['close'].copy() # Filling the data. df_rets = df_rets.fillna(method='ffill') df_rets = df_rets.fillna(method='bfill') # Numpy matrix of filled data values na_rets = df_rets.values na_rets = na_rets / na_rets[0, :] lf_alloc = [0.0, 0.0, 0.0, 0.0] max_sharpe = -1000 final_stddev = -1000 final_daily_ret = -1000 final_cum_ret = -1000 best_portfolio = lf_alloc for i in range(0, 101, 10): left_after_i = 101 - i for j in range(0, left_after_i, 10): left_after_j = 101 - i - j for k in range(0, left_after_j, 10): left_after_k = 100 - i - j - k lf_alloc = [i, j, k, left_after_k] lf_alloc = [x * 0.01 for x in lf_alloc] stddev, daily_ret, sharpe, cum_ret = simulate( na_rets, lf_alloc) if sharpe > max_sharpe: max_sharpe = sharpe final_stddev = stddev final_cum_ret = cum_ret final_daily_ret = daily_ret best_portfolio = lf_alloc print "<<< Symbols : ", ls_symbols print "<<< Best Portfolio : ", best_portfolio print "<<< Statistics : Std. Deviation : ", final_stddev print "<<< Statistics : Daily Returns : ", final_daily_ret print "<<< Statistics : Cum. Returns : ", final_cum_ret print "<<< Statistics : Sharpe Ratio : ", max_sharpe
def portfolioAnalyz(): ''' Main Function This method will analyze your performance of portfolio from date specified. Create Excel sheet with your portfolio allocation and it will be read by this method to perform analysis ''' # Reading the portfolio print '<<<(s) Update your portfolioanalyze.csv file..' if os.path.isfile("C:\MRT3.0\portfolioanalyze.csv"): na_portfolio = np.loadtxt('portfolioanalyze.csv', dtype='S5,f4', delimiter=',', comments="#", skiprows=1) else: print '<<<(w) File Not Found: portfolioanalyze.csv ' sleep(2) basic.go_back() # Sorting the portfolio by symbol name na_portfolio = sorted(na_portfolio, key=lambda x: x[0]) print na_portfolio # Create two list for symbol names and allocation ls_port_syms = [] lf_port_alloc = [] for port in na_portfolio: ls_port_syms.append(port[0]) lf_port_alloc.append(port[1]) # Creating an object of the dataaccess class with Yahoo as the source. c_dataobj = da.DataAccess('Yahoo') ls_all_syms = c_dataobj.get_all_symbols() # Bad symbols are symbols present in portfolio but not in all syms ls_bad_syms = list(set(ls_port_syms) - set(ls_all_syms)) if len(ls_bad_syms) != 0: print "<<<(w) Portfolio contains bad symbols : ", ls_bad_syms for s_sym in ls_bad_syms: i_index = ls_port_syms.index(s_sym) ls_port_syms.pop(i_index) lf_port_alloc.pop(i_index) # Reading the historical data. print '<<<(i) Reading Historical data...' #dt_end = dt.datetime(2011, 1, 1) #dt_start = dt_end - dt.timedelta(days=95) # Three years # We need closing prices so the timestamp should be hours=16. dt_timeofday = dt.timedelta(hours=16) start_month,start_day,start_year,end_month,end_day,end_year = modDatesReturn.get_dates() dt_start = dt.datetime(start_year, start_month, start_day) dt_end = dt.datetime(end_year, end_month, end_day) # Get a list of trading days between the start and the end. ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday) # Keys to be read from the data, it is good to read everything in one go. ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close'] # Reading the data, now d_data is a dictionary with the keys above. # Timestamps and symbols are the ones that were specified before. ldf_data = c_dataobj.get_data(ldt_timestamps, ls_port_syms, ls_keys) d_data = dict(zip(ls_keys, ldf_data)) # Copying close price into separate dataframe to find rets df_rets = d_data['close'].copy() # Filling the data. df_rets = df_rets.fillna(method='ffill') df_rets = df_rets.fillna(method='bfill') # Numpy matrix of filled data values na_rets = df_rets.values # returnize0 works on ndarray and not dataframes. tsu.returnize0(na_rets) # Estimate portfolio returns na_portrets = np.sum(na_rets * lf_port_alloc, axis=1) na_port_total = np.cumprod(na_portrets + 1) na_component_total = np.cumprod(na_rets + 1, axis=0) # Plotting the results plt.clf() #fig = plt.figure() #fig.add_subplot(111) plt.plot(ldt_timestamps, na_component_total) plt.plot(ldt_timestamps, na_port_total) ls_names = ls_port_syms ls_names.append('Portfolio') plt.legend(ls_names) plt.ylabel('Cumulative Returns') plt.xlabel('Date') #fig.autofmt_xdate(rotation=45) plt.show()
def bestPort(): '''Main Function''' # List of symbols #ls_symbols = ["AXP", "HPQ", "IBM", "HNZ"] ls_symbols = list() try: len_sym = input('<<< How many symbol(Works only for 4 symbols): ') if len_sym > 4 or len_sym <= 0 or len_sym < 4: print '<<<(w) Works only for 4 symbols..\n' basic.print_logo() basic.print_clrscr() basic.go_back() except ValueError: basic.print_logo() basic.print_clrscr() basic.go_back() except SyntaxError: basic.print_logo() basic.print_clrscr() basic.go_back() except NameError: basic.print_logo() basic.print_clrscr() basic.go_back() for i in range(len_sym): symbols = str(raw_input('<<< Enter the list of symbols: ')) ls_symbols.append(symbols) ## Start and End date of the charts start_month,start_day,start_year,end_month,end_day,end_year = modDatesReturn.get_dates() dt_start = dt.datetime(start_year, start_month, start_day) dt_end = dt.datetime(end_year, end_month, end_day) # Start and End date of the charts #dt_start = dt.datetime(2010, 1, 1) #dt_end = dt.datetime(2010, 12, 31) # We need closing prices so the timestamp should be hours=16. dt_timeofday = dt.timedelta(hours=16) # Get a list of trading days between the start and the end. ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday) # Creating an object of the dataaccess class with Yahoo as the source. c_dataobj = da.DataAccess('Yahoo') # Keys to be read from the data, it is good to read everything in one go. ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close'] # Reading the data, now d_data is a dictionary with the keys above. # Timestamps and symbols are the ones that were specified before. ldf_data = c_dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys) d_data = dict(zip(ls_keys, ldf_data)) # Copying close price into separate dataframe to find rets df_rets = d_data['close'].copy() # Filling the data. df_rets = df_rets.fillna(method='ffill') df_rets = df_rets.fillna(method='bfill') # Numpy matrix of filled data values na_rets = df_rets.values na_rets = na_rets / na_rets[0, :] lf_alloc = [0.0, 0.0, 0.0, 0.0] max_sharpe = -1000 final_stddev = -1000 final_daily_ret = -1000 final_cum_ret = -1000 best_portfolio = lf_alloc for i in range(0, 101, 10): left_after_i = 101 - i for j in range(0, left_after_i, 10): left_after_j = 101 - i - j for k in range(0, left_after_j, 10): left_after_k = 100 - i - j - k lf_alloc = [i, j, k, left_after_k] lf_alloc = [x * 0.01 for x in lf_alloc] stddev, daily_ret, sharpe, cum_ret = simulate(na_rets, lf_alloc) if sharpe > max_sharpe: max_sharpe = sharpe final_stddev = stddev final_cum_ret = cum_ret final_daily_ret = daily_ret best_portfolio = lf_alloc print "<<< Symbols : ", ls_symbols print "<<< Best Portfolio : ", best_portfolio print "<<< Statistics : Std. Deviation : ", final_stddev print "<<< Statistics : Daily Returns : ", final_daily_ret print "<<< Statistics : Cum. Returns : ", final_cum_ret print "<<< Statistics : Sharpe Ratio : ", max_sharpe