def evaluate(self, db, args): dates_expr = f'trade_dates.{args.date}.2.lag' ma_l = stocklab.evaluate( f'moving_average.{args.stock_id}.(${dates_expr}).8') ma_s = stocklab.evaluate( f'moving_average.{args.stock_id}.(${dates_expr}).3') ml = ma_l[1] - ma_l[0] ms = ma_s[1] - ma_s[0] cross = (ma_l[1] - ma_s[1]) * (ma_l[0] - ma_s[0]) <= 0 bear = ml > ms bull = ml < ms return (0 if not cross else 1 if bull else -1 if bear else 0)
def evaluate(self, db, args): n = args.n days = args.days + n prices = np.asarray(stocklab.evaluate( f'ohlc.{args.stock_id}.($trade_dates.{args.date}.{days}.lag)' ))[:,3] deltas = np.diff(prices) seed = deltas[:n - 1] up = seed[seed > 0].sum() / n down = -seed[seed < 0].sum() / n rs = up / down rsi = np.zeros_like(prices) rsi[:n] = 100. - 100. / (1. + rs) for i in range(n, len(prices)): delta = deltas[i - 1] # cause the diff is 1 shorter if delta > 0: upval = delta downval = 0. else: upval = 0. downval = -delta up = (up * (n - 1) + upval) / n down = (down * (n - 1) + downval) / n rs = up / down rsi[i] = 100. - 100. / (1. + rs) return rsi[n:]
def evaluate(self, db, args): brokers = stocklab.evaluate( f'stock_brokers.{args.stock_id}._.{args.date}.{args.n_days}') force_list = np.asarray( [b['buy_amt'] - b['sell_amt'] for bid, b in brokers.items()]) if 'buy' == args.buy_or_sell: return force_list[force_list > 0] else: return -force_list[force_list < 0]
def evaluate(self, db, args): bsf = stocklab.evaluate( f'tendency.{args.mode}.{args.stock_id}.{args.date}.{args.days}') bsf = bsf[bsf > args.min_force] def normalize(v): norm = np.linalg.norm(v) if norm == 0: return v return v / norm return normalize(bsf).var() if len(bsf) else 0.0
def _eval(self, path, peek=False): use_cache = 'disable_cache' not in self.spec or not self.spec['disable_cache'] if path in self.cache and use_cache and not peek: return self.cache[path] assert not re.search(r'\(((?!\)).)*?\(', path), f'expression cannot have nested parentheses: {path}' splited = [e.strip('()') for e in re.split(r'(\(.*?\)|\.)', path) if e and e != '.'] mod_name = splited[0] assert self.name == mod_name, f'{splited}' arg_spec = self.spec['args'] assert self.args_validator(arg_spec) assert len(arg_spec) == len(splited) - 1, f'invalid expression: {path}' from collections.abc import Iterable _replace = lambda t, i, elem: t[:i] + [elem] + t[i+1:] for i in range(len(splited)): field = splited[i] try: float(field) continue except ValueError: pass if '$' != field[0]: continue values = stocklab.metaevaluate(field.lstrip('$')) assert isinstance(values, Iterable) return [ stocklab.evaluate('.'.join( [f'({s})' for s in _replace(splited, i, str(val))] )) for val in values] args_list = tuple(splited[1:]) args = stocklab.Args(args_list, arg_spec) result = self._eval_in_context(args, peek=peek) if not peek: assert self.type_validator(result) if use_cache: self.cache[path] = result return result
rand_sim = random_simulate( date, days, verbose=True, dates_expr=lambda d, n: f'trade_dates.{d}.{n}.lag', ohlc_expr=lambda s, d: f'ohlc.{s}.{d}', sign_expr=lambda s, d: f'my_sign.{s}.{d}', #stocks_expr='stocks.1702' ) stock_id, gain = next(rand_sim) print(f'stock_id: {stock_id}, gain: {gain:.3}') # plot it dates_expr = f'trade_dates.{date}.{days}.lag' dates = stocklab.metaevaluate(dates_expr) ohlcs = np.asarray(stocklab.evaluate(f'ohlc.{stock_id}.(${dates_expr})')) prices = ohlcs[:, 3] signs = stocklab.evaluate(f'my_sign.{stock_id}.(${dates_expr})') plot(dates, ohlcs, signs, aux={ 'ma_l': stocklab.evaluate(f'moving_average.{stock_id}.(${dates_expr}).8'), 'ma_s': stocklab.evaluate(f'moving_average.{stock_id}.(${dates_expr}).3') }, top_aux={ 'volumn': stocklab.evaluate(f'volumn.{stock_id}.(${dates_expr})'), })
def evaluate(self, db, args): return np.asarray( stocklab.evaluate( f'ohlc.{args.stock_id}.($trade_dates.{args.date}.{args.N}.lag)' ))[:, 3].mean()
def _eval(expr): if self.meta: return stocklab.metaevaluate(str(expr)) else: return stocklab.evaluate(str(expr))
import numpy as np import logging import stocklab from stocklab.datetime import Date from stocklab.utils import * #stocklab.change_log_level(logging.DEBUG) date = stocklab.metaevaluate('nearest.20200424') days = 100 stock_id = 3034 # plot it dates_expr = f'trade_dates.{date}.{days}.lag' dates = stocklab.metaevaluate(dates_expr) ohlcs = np.asarray(stocklab.evaluate(f'ohlc.{stock_id}.(${dates_expr})')) ma_l = np.asarray( stocklab.evaluate(f'moving_average.{stock_id}.(${dates_expr}).8')) ma_s = np.asarray( stocklab.evaluate(f'moving_average.{stock_id}.(${dates_expr}).3')) plot(dates, ohlcs, aux={ 'ma_l': ma_l, 'ma_s': ma_s }, top_aux={'macd': ma_l - ma_s})
def _sim(stock_id): ohlcs = np.asarray( stocklab.evaluate(ohlc_expr(stock_id, f'(${dates_expr})'))) prices = ohlcs[:, 3] signs = stocklab.evaluate(sign_expr(stock_id, f'(${dates_expr})')) return simulate(dates, signs, prices, verbose)