def bollinger_band(self, tick, window=20, k=2, mi_only=False): """ Return four arrays for Bollinger Band. The first one is the moving average. The second one is the upper band. The thrid one is the lower band. The fourth one is the Bollinger value. If mi_only, then return the moving average only. """ ldt_timestamps = self.ldt_timestamps() pre_timestamps = ut.pre_timestamps(ldt_timestamps, window) # ldf_data has the data prior to our current interest. # This is used to calculate moving average for the first window. ldf_data = ut.get_tickdata([tick], pre_timestamps) merged_data = pd.concat([ldf_data[tick]['close'], self['close']]) bo = dict() bo['mi'] = pd.rolling_mean(merged_data, window=window)[ldt_timestamps] if mi_only: return bo['mi'] else: sigma = pd.rolling_std(merged_data, window=window) bo['hi'] = bo['mi'] + k * sigma[ldt_timestamps] bo['lo'] = bo['mi'] - k * sigma[ldt_timestamps] bo['ba'] = (merged_data[ldt_timestamps] - bo['mi']) / (k * sigma[ldt_timestamps]) return bo
def bollinger_band(self, tick, window=20, k=2, nml=False, mi_only=False): """ Return four arrays for Bollinger Band. The first one is the moving average. The second one is the upper band. The thrid one is the lower band. The fourth one is the Bollinger value. If mi_only, then return the moving average only. """ ldt_timestamps = self.index dt_timeofday = dt.timedelta(hours=16) days_delta = dt.timedelta(days=(np.ceil(window*7/5)+5)) dt_start = ldt_timestamps[0] - days_delta dt_end = ldt_timestamps[0] - dt.timedelta(days=1) pre_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday) # ldf_data has the data prior to our current interest. # This is used to calculate moving average for the first window. ldf_data = ut.get_tickdata([tick], pre_timestamps) if nml: ma_data = pd.concat([ldf_data[tick]['nml_close'], self['nml_close']]) else: ma_data = pd.concat([ldf_data[tick]['close'], self['close']]) bo = dict() bo['mi'] = pd.rolling_mean(ma_data, window=window)[ldt_timestamps] if mi_only: return bo['mi'] else: sigma = pd.rolling_std(ma_data, window=window) bo['up'] = bo['mi'] + k * sigma[ldt_timestamps] bo['lo'] = bo['mi'] - k * sigma[ldt_timestamps] bo['ba'] = (ma_data[ldt_timestamps] - bo['mi']) / (k * sigma[ldt_timestamps]) return bo
def bollinger_band(self, tick, window=20, k=2, nml=False, mi_only=False): """ Return four arrays for Bollinger Band. The first one is the moving average. The second one is the upper band. The thrid one is the lower band. The fourth one is the Bollinger value. If mi_only, then return the moving average only. """ ldt_timestamps = self.index dt_timeofday = dt.timedelta(hours=16) days_delta = dt.timedelta(days=(np.ceil(window * 7 / 5) + 5)) dt_start = ldt_timestamps[0] - days_delta dt_end = ldt_timestamps[0] - dt.timedelta(days=1) pre_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday) # ldf_data has the data prior to our current interest. # This is used to calculate moving average for the first window. ldf_data = ut.get_tickdata([tick], pre_timestamps) if nml: ma_data = pd.concat( [ldf_data[tick]['nml_close'], self['nml_close']]) else: ma_data = pd.concat([ldf_data[tick]['close'], self['close']]) bo = dict() bo['mi'] = pd.rolling_mean(ma_data, window=window)[ldt_timestamps] if mi_only: return bo['mi'] else: sigma = pd.rolling_std(ma_data, window=window) bo['up'] = bo['mi'] + k * sigma[ldt_timestamps] bo['lo'] = bo['mi'] - k * sigma[ldt_timestamps] bo['ba'] = (ma_data[ldt_timestamps] - bo['mi']) / (k * sigma[ldt_timestamps]) return bo
def drawdown(self, tick, window=10): """ Find the peak within the retrospective window. Drawdown is the difference between the peak and the current value. """ ldt_timestamps = self.index pre_timestamps = ut.pre_timestamps(ldt_timestamps, window) # ldf_data has the data prior to our current interest. # This is used to calculate moving average for the first window. ldf_data = ut.get_tickdata([tick], pre_timestamps) merged_data = pd.concat([ldf_data[tick]['close'], self['close']]) total_timestamps = merged_data.index dd = pd.Series(index=ldt_timestamps) j = 0 for i in range(len(pre_timestamps), len(total_timestamps)): win_start = total_timestamps[i - window] win_end = total_timestamps[i] ts_value = merged_data[win_start:win_end] current = merged_data[win_end] peak = np.amax(ts_value) dd[j] = (peak-current)/peak j += 1 return dd
skipinitialspace=True) for row in order_reader: date = dt.datetime(int(row[0]), int(row[1]), int(row[2]), 16) o = Order(action=row[4], date=date, tick=row[3], shares=row[5]) order_list.append(o) # order_list needs to be sorted. Otherwise the algorithm won't work. date_list = [x.date for x in order_list] date_list.sort() dt_start = date_list[0] dt_end = date_list[-1] tick_set = sets.Set([x.tick for x in order_list]) ls_symbols = ['$SPX'] while (tick_set): ls_symbols.append(tick_set.pop()) ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday) all_stocks = get_tickdata(ls_symbols=ls_symbols, ldt_timestamps=ldt_timestamps) pf = Portfolio(equities=all_stocks, cash=cash, dates=ldt_timestamps, order_list=order_list) pf.sim() equity_col = ['buy', 'sell', 'close'] pf.csvwriter(csv_file=value_file, d=',', cash=False) print "Details of the Performance of the portfolio :" print "Data Range :", ldt_timestamps[0], "to", ldt_timestamps[-1] print "Sharpe Ratio of Fund :", pf.sharpe() print "Sortino Ratio of Fund :", pf.sortino() print "Sharpe Ratio of $SPX :", pf.equities['$SPX'].sharpe() print "Total Return of Fund :", pf.totalrtn() print " Total Return of $SPX :", pf.equities['$SPX'].totalrtn() print "Standard Deviation of Fund :", pf.std()
order_reader = csv.reader(csvfile, delimiter=',', skipinitialspace=True) for row in order_reader: date = dt.datetime(int(row[0]),int(row[1]), int(row[2]), 16) o = Order(action=row[4], date=date, tick=row[3], shares=row[5]) order_list.append(o) # order_list needs to be sorted. Otherwise the algorithm won't work. date_list = [x.date for x in order_list] date_list.sort() dt_start = date_list[0] dt_end = date_list[-1] tick_set = sets.Set([x.tick for x in order_list]) ls_symbols = ['$SPX'] while(tick_set): ls_symbols.append(tick_set.pop()) ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday) all_stocks = get_tickdata(ls_symbols=ls_symbols, ldt_timestamps=ldt_timestamps) pf = Portfolio(equities=all_stocks, cash=cash, dates=ldt_timestamps, order_list=order_list) pf.sim() equity_col = ['buy', 'sell', 'close'] pf.csvwriter(csv_file=value_file, d=',', cash=False) print "Details of the Performance of the portfolio :" print "Data Range :", ldt_timestamps[0], "to", ldt_timestamps[-1] print "Sharpe Ratio of Fund :", pf.sharpe() print "Sortino Ratio of Fund :", pf.sortino() print "Sharpe Ratio of $SPX :", pf.equities['$SPX'].sharpe() print "Total Return of Fund :", pf.totalrtn() print " Total Return of $SPX :", pf.equities['$SPX'].totalrtn() print "Standard Deviation of Fund :", pf.std() print " Standard Deviation of $SPX :", pf.equities['$SPX'].std() print "Average Daily Return of Fund :", pf.avg_dailyrtn() print "Average Daily Return of $SPX :", pf.equities['$SPX'].avg_dailyrtn()