def direction_based_entry(mkt: MarketData, sig: Signal, direction_action_dict: dict) -> Trades: """Take positions. Args: mkt: Market data sig: Signal data direction_action_dict: Dictionary from signals to actions Result: Trades """ assert all([idx in mkt.index for idx in sig.index]) df = sig trades = [] # type: List[pd.Dataframe] for direction, action in direction_action_dict.items(): amount = action.act_on_amount() if amount == Action.Donothing.act_on_amount(): continue trades.append( pd.DataFrame( index=df[df["pred"] == direction.value].index, data=amount, columns=["amount"], )) df_trades = pd.concat(trades, axis=0).sort_index() df_trades.loc[:, "_id"] = range(len(df_trades.index)) t = from_dataframe(df_trades, df.symbol) return t
def _exit_by_max_holding_time( trades: Trades, df: pd.DataFrame, max_holding_time: pd.Timedelta, exit_condition: Callable[[pd.DataFrame, pd.Series, pd.Timestamp], bool], ) -> Trades: indices = [] # type: List[pd.Timestamp] exits = [] # type: List[Tuple[float, int]] for i in trades.ids: trade = trades.get_trade(i) if trade.sum() == 0: continue idx = trade.index[0] start = max(idx, df.index[0]) end = min(idx + max_holding_time, df.index[-1]) df_exit = df.loc[start:end] transaction = _exit_transaction(df_exit, trade, exit_condition) indices.append(transaction.timestamp) exits.append((transaction.amount, i)) df = pd.DataFrame(index=indices, data=exits, columns=["amount", "_id"]) return from_dataframe(df, symbol, currency_unit)
def filter_entry_by_time( trades: Trades, unit: str, container_set: tuple ) -> Type["Trades"]: """Filter trade which match conditions at least one element. -> e.g. for container_set = [1,2] and unit = 'hour' Trades of hour 1 or 2 will be return. Args: container_set: The results will only contain elements of time in this set unit: Can be 'hour', 'minute'... The results.time will be in the set Returns: Trades. """ sort = trades.sort_values("_id") df = pd.DataFrame( data=np.zeros((sort.shape[0], 3)), columns=["amount", "_id", "index"] ) j = 0 for i in range(0, sort.index.size, 2): entry_index = sort.index[i] exit_index = sort.index[i + 1] if ( getattr(entry_index, unit) in container_set or getattr(exit_index, unit) in container_set ): # This code is faster than an iloc. df.at[j, "amount"] = sort.iat[i, 0] df.at[j + 1, "amount"] = sort.iat[i + 1, 0] df.at[j, "_id"] = sort.iat[i, 1] df.at[j + 1, "_id"] = sort.iat[i + 1, 1] df.at[j, "index"] = entry_index df.at[j + 1, "index"] = exit_index j += 2 df = df.iloc[0:j, :].sort_values("index").set_index("index") df.index.name = None return from_dataframe(df, trades.symbol, trades.currency_unit)
def _exit( trades: Trades, df: pd.DataFrame, exit_condition: Callable[[pd.DataFrame, pd.Series], pd.Series], ) -> pd.Series: indices = [] # type: List[pd.Timestamp] exits = [] # type: List[Tuple[float, int]] for i in trades.ids: trade = trades.get_trade(i) if trade.sum() == 0: continue idx = trade.index[0] df_exit = df[idx <= df.index] transaction = _exit_transaction(df_exit, trade, exit_condition) indices.append(transaction.timestamp) exits.append((transaction.amount, i)) df = pd.DataFrame(index=indices, data=exits, columns=["amount", "_id"]) return from_dataframe(df, symbol)