def run(self): self.ts = pf.fetch_timeseries(self.symbol) self.ts = pf.select_tradeperiod(self.ts, self.start, self.end, use_adj=True) # Add technical indicator: 200 sma regime filter self.ts['regime'] = \ pf.CROSSOVER(self.ts, timeperiod_fast=1, timeperiod_slow=200) # Add technical indicator: instrument risk, i.e. annual std self.ts['vola'] = \ pf.VOLATILITY(self.ts, lookback=20, time_frame='yearly') # Add technical indicator: X day sma sma = SMA(self.ts, timeperiod=self.sma) self.ts['sma'] = sma # Add technical indicator: X day high, and X day low period_high = pd.Series(self.ts.close).rolling(self.period).max() period_low = pd.Series(self.ts.close).rolling(self.period).min() self.ts['period_high'] = period_high self.ts['period_low'] = period_low self.ts, self.start = pf.finalize_timeseries(self.ts, self.start) self.tlog = pf.TradeLog(self.symbol) self.dbal = pf.DailyBal() self._algo()
def volatility_graph(rets, labels, points_to_plot=None): def _boxplot(volas, labels): fig = plt.figure(figsize=(12, 8)) axes = fig.add_subplot(111, ylabel='Volatility') plt.ylim(0, 1) plt.boxplot(volas, labels=labels) def _volas_plot(volas, labels): fig = plt.figure(figsize=(14,10)) axes = fig.add_subplot(111, ylabel='Volatility') for i, vola in enumerate(volas): axes.plot(vola, label=labels[i]) plt.legend(loc='best') # default is to plot all points (days) if points_to_plot is None: points_to_plot = 0; # get volatility for each return set volas = [] for ret in rets: volas.append(pf.VOLATILITY(ret[-points_to_plot:]).dropna()) # build metrics dataframe index = [] columns = labels data = [] # add metrics metrics = ['avg', 'median', 'min', 'max', 'std', 'last'] for metric in metrics: index.append(metric) if metric == 'avg': data.append(vola.mean() for vola in volas) elif metric == 'median': data.append(vola.median() for vola in volas) elif metric == 'min': data.append(vola.min() for vola in volas) elif metric == 'max': data.append(vola.max() for vola in volas) elif metric == 'std': data.append(vola.std() for vola in volas) elif metric == 'last': data.append(vola[-1] for vola in volas) df = pd.DataFrame(data, columns=columns, index=index) _boxplot(volas, labels) _volas_plot(volas, labels) return df
def run(self): self.ts = pf.fetch_timeseries(self.symbol) self.ts = pf.select_tradeperiod(self.ts, self.start, self.end) # add regime filter self.ts['regime'] = \ pf.CROSSOVER(self.ts, timeperiod_fast=self.timeperiod_fast, timeperiod_slow=self.timeperiod_slow, band=self.percent_band) # Add technical indicator: volatility self.ts['vola'] = pf.VOLATILITY(self.ts) self.ts, self.start = pf.finalize_timeseries(self.ts, self.start) self.tlog = pf.TradeLog(self.symbol) self.dbal = pf.DailyBal() self._algo()
def volatility_graphs(dbals, labels, points_to_plot=None): """ Plot volatility graphs. The first graph is a boxplot showing the differences between 2 or more returns. The second graph shows the volatility plotted for 2 or more returns. Parameters ---------- dbals : list of pd.DataFrame A list of daily closing balances (or daily instrument closing prices) indexed by date. labels : list of str A list of labels. points_to_plot : int, optional Define how many points (trading days) we intend to plot (default is None, which implies plot all points or days). Returns ------- pf.DataFrame Statistics comparing the `dbals`. Examples -------- >>> df = pf.volatility_graph([ts, dbal], ['SPY', 'Strategy'], points_to_plot=5000) >>> df """ def _boxplot(volas, labels): """ Plot a volatility boxplot. """ fig = plt.figure(figsize=(12, 8)) axes = fig.add_subplot(111, ylabel='Volatility') plt.ylim(0, 1) plt.boxplot(volas, labels=labels) def _volas_plot(volas, labels): """ Plot volatility. """ fig = plt.figure(figsize=(14, 10)) axes = fig.add_subplot(111, ylabel='Volatility') for i, vola in enumerate(volas): axes.plot(vola, label=labels[i]) plt.legend(loc='best') if points_to_plot is None: points_to_plot = 0 # Get volatility for each dbal set. volas = [] for dbal in dbals: volas.append(pf.VOLATILITY(dbal[-points_to_plot:]).dropna()) # Build metrics dataframe. index = [] columns = labels data = [] # Add metrics. metrics = ['avg', 'median', 'min', 'max', 'std', 'last'] for metric in metrics: index.append(metric) if metric == 'avg': data.append(vola.mean() for vola in volas) elif metric == 'median': data.append(vola.median() for vola in volas) elif metric == 'min': data.append(vola.min() for vola in volas) elif metric == 'max': data.append(vola.max() for vola in volas) elif metric == 'std': data.append(vola.std() for vola in volas) elif metric == 'last': data.append(vola[-1] for vola in volas) df = pd.DataFrame(data, columns=columns, index=index) _boxplot(volas, labels) _volas_plot(volas, labels) return df
def _volatility(ts, ta_param, input_column): return pf.VOLATILITY(ts, price=input_column)