def generate_random(cls, shape, n=None, prob=None, seed=None, **kwargs): """Generate signals randomly. If `n` is set, see `vectorbt.signals.nb.generate_rand_nb`. If `prob` is set, see `vectorbt.signals.nb.generate_rand_by_prob_nb`. `n` should be either a scalar or an array that will broadcast to the number of columns. `prob` should be either a single number or an array that will broadcast to match `shape`. `**kwargs` will be passed to pandas constructor. ## Example For each column, generate a variable number of signals: ```python-repl >>> pd.DataFrame.vbt.signals.generate_random((5, 3), n=[0, 1, 2], ... seed=42, index=sig.index, columns=sig.columns) a b c 2020-01-01 False False True 2020-01-02 False False True 2020-01-03 False False False 2020-01-04 False True False 2020-01-05 False False False ``` For each column and time step, pick a signal with 50% probability: ```python-repl >>> pd.DataFrame.vbt.signals.generate_random((5, 3), prob=0.5, ... seed=42, index=sig.index, columns=sig.columns) a b c 2020-01-01 True True True 2020-01-02 False True False 2020-01-03 False False False 2020-01-04 False False True 2020-01-05 True False True ``` """ flex_2d = True if not isinstance(shape, tuple): flex_2d = False shape = (shape, 1) elif isinstance(shape, tuple) and len(shape) == 1: flex_2d = False shape = (shape[0], 1) if n is not None and prob is not None: raise ValueError("Either n or prob should be set") if n is not None: n = np.broadcast_to(n, shape[1]) result = nb.generate_rand_nb(shape, n, seed=seed) elif prob is not None: prob = np.broadcast_to(prob, shape) result = nb.generate_rand_by_prob_nb(shape, prob, flex_2d, seed=seed) else: raise ValueError("At least n or prob should be set") if cls.is_series(): if shape[1] > 1: raise ValueError("Use DataFrame accessor") return pd.Series(result[:, 0], **kwargs) return pd.DataFrame(result, **kwargs)
def generate_random(cls, shape, n, seed=None, **kwargs): """See `vectorbt.signals.nb.generate_rand_nb`. `**kwargs` will be passed to pandas constructor. Example: For each column, generate two signals randomly: ```python-repl >>> print(pd.DataFrame.vbt.signals.generate_random((5, 3), 2, ... seed=42, index=sig.index, columns=sig.columns)) a b c 2020-01-01 False False True 2020-01-02 True True True 2020-01-03 False False False 2020-01-04 False True False 2020-01-05 True False False ```""" if not isinstance(shape, tuple): shape = (shape, 1) elif isinstance(shape, tuple) and len(shape) == 1: shape = (shape[0], 1) result = nb.generate_rand_nb(shape, n, seed=seed) if cls.is_series(): return pd.Series(result[:, 0], **kwargs) return pd.DataFrame(result, **kwargs)