def callback_graph(update, context): country_code = context.match.group(1) if country_code == WORLD_IDENT: country_code = None data = api.timeseries(country_code) if data: buffer = plot_timeseries(data) update.callback_query.answer() context.bot.send_photo(chat_id=update.callback_query.message.chat_id, photo=buffer) buffer.close() else: update.callback_query.answer() context.bot.send_message(chat_id=update.callback_query.message.chat_id, text=resolve('no_data', lang(update)))
def command_graph(update, context): if len(context.args) > 0: resolved = resolve_query_string(context.args[0]) if resolved: data = api.timeseries(resolved) elif WORLD_IDENT in context.args[0]: data = api.timeseries() else: update.message.reply_text(resolve('unknown_place', lang(update))) return else: if 'country' in context.chat_data: country_code = context.chat_data['country'] data = api.timeseries(country_code) else: data = api.timeseries() if data: buffer = plot_timeseries(data) update.message.reply_photo(photo=buffer) buffer.close() else: update.message.reply_text(resolve('no_data', lang(update)))
import glob import os import pickle import matplotlib.pyplot as plt from antlia import record from plot import plot_timeseries def get_metric(rec, start_index, stop_index, field, metric): indices = (rec.time > start_index) & (rec.time < stop_index) m = getattr(rec[indices][field], metric) return m() if __name__ == '__main__': with open('config.p', 'rb') as f: cd = pickle.load(f) pat = os.path.join(os.path.dirname(__file__), '../data/etrike/calibration/convbike/speed/*kph.csv') calfiles = glob.glob(pat) r = {} for f in calfiles: bn = os.path.basename(f) v = int(bn[:bn.index('kph')]) r[v] = record.load_file(f, cd['convbike']) plot_timeseries(r[v]) plt.show()
df = prices[0].get_frame(normalize=normalize) df.columns = [prices[0].ticker] for i in range(1, len(prices)): df2 = prices[i].get_frame(normalize=normalize) df2.columns = [prices[i].ticker] df = df.join(df2, how='outer') return df if __name__ == '__main__': valid_metrics = ['block_chain_work', 'block_num_tx'] parser = argparse.ArgumentParser( description= 'Compute timeseries correlation for a given metric across coins.') parser.add_argument('metrics', nargs='?', choices=valid_metrics, default=valid_metrics) args = parser.parse_args() if type(args.metrics) != list: args.metrics = [args.metrics] # Create coins coins = [Coin(ticker) for ticker in config.TICKERS] for metric in args.metrics: df = create_coin_frame(coins, metric, normalize='min_max') plot.plot_timeseries(metric, df) print df.corr()
def __init__(self, ticker, target='USD'): self.ticker = ticker self.prices = self._get_prices(target=target) def get_frame(self, normalize=None): """Return the price data frame, with the same normalization options as in Coin.""" # Get datetime-indexed timeseries data times = [] data = [] for t in sorted(self.prices.keys()): times.append(datetime.strptime(t, '%Y-%m-%d')) data.append(self.prices[t]) df = pd.DataFrame(data, index=times, columns=['price']) # Normalize columns self._normalize(df, normalize) return df if __name__ == '__main__': prices = [Price(ticker) for ticker in config.ALL_TICKERS] # Compute JOIN over price frames df = create_price_frame(prices, normalize='z_score') # `df` can be replaced with `df.pct_change()` or `pd.rolling_var(df, 7)` to track volatility plot.plot_timeseries('Prices', df) print df.corr()
for b in self.blocks: key = self._time_to_key(b.time) b.price = self.prices.get(key) def get_frame(self, *fields, **kwargs): """ Return the data frame that includes the given fields. Fields must be chosen from 'block_chain_work', 'block_num_tx', or 'price'. Min-max and Z-score normalization can be performed by passing in normalize='min_max' or normalize='z_score', respectively. """ data = [b.__dict__ for b in self.blocks] times = [b.time for b in self.blocks] df = pd.DataFrame(data, index=times, columns=fields) # Normalize columns normalize = kwargs.get('normalize', None) self._normalize(df, normalize) return df if __name__ == "__main__": parser = argparse.ArgumentParser( description='Compute and plot timeseries correlation for all metrics in a given coin.') parser.add_argument('ticker', choices=config.TICKERS.values()) args = parser.parse_args() coin = Coin(args.ticker) df = coin.get_frame('block_chain_work', 'block_num_tx', 'price') plot.plot_timeseries(args.ticker, df, window=100)
return df def create_price_frame(prices, normalize=None): df = prices[0].get_frame(normalize=normalize) df.columns = [prices[0].ticker] for i in range(1, len(prices)): df2 = prices[i].get_frame(normalize=normalize) df2.columns = [prices[i].ticker] df = df.join(df2, how='outer') return df if __name__ == '__main__': valid_metrics = ['block_chain_work', 'block_num_tx'] parser = argparse.ArgumentParser( description='Compute timeseries correlation for a given metric across coins.') parser.add_argument('metrics', nargs='?', choices=valid_metrics, default=valid_metrics) args = parser.parse_args() if type(args.metrics) != list: args.metrics = [args.metrics] # Create coins coins = [Coin(ticker) for ticker in config.TICKERS] for metric in args.metrics: df = create_coin_frame(coins, metric, normalize='min_max') plot.plot_timeseries(metric, df) print df.corr()
def get_frame(self, *fields, **kwargs): """ Return the data frame that includes the given fields. Fields must be chosen from 'block_chain_work', 'block_num_tx', or 'price'. Min-max and Z-score normalization can be performed by passing in normalize='min_max' or normalize='z_score', respectively. """ data = [b.__dict__ for b in self.blocks] times = [b.time for b in self.blocks] df = pd.DataFrame(data, index=times, columns=fields) # Normalize columns normalize = kwargs.get('normalize', None) self._normalize(df, normalize) return df if __name__ == "__main__": parser = argparse.ArgumentParser( description= 'Compute and plot timeseries correlation for all metrics in a given coin.' ) parser.add_argument('ticker', choices=config.TICKERS.values()) args = parser.parse_args() coin = Coin(args.ticker) df = coin.get_frame('block_chain_work', 'block_num_tx', 'price') plot.plot_timeseries(args.ticker, df, window=100)