Esempio n. 1
0
    async def load_symbol_data(
        self,
        symbol: str,
        days: int,
    ) -> None:
        start_date = date.today() - timedelta(days=days)
        _minute_data = get_historical_data_from_polygon_by_range(
            self.data_api, [symbol], start_date, "day")

        for index, row in _minute_data[symbol].iterrows():
            indicators: Dict = {}
            if self.indicators:
                for indicator in self.indicators:
                    if indicator == "mama":
                        mama, fama = MAMA(
                            _minute_data[symbol]["close"][:index].dropna())
                        indicators["mama"] = (
                            mama[-1] if not math.isnan(mama[-1]) else None)
                        indicators["fama"] = (
                            fama[-1] if not math.isnan(fama[-1]) else None)

            daily_bar = StockOhlc(
                symbol=symbol,
                symbol_date=index,
                open=row["open"],
                high=row["high"],
                low=row["low"],
                close=row["close"],
                volume=int(row["volume"]),
                indicators=indicators,
            )
            await daily_bar.save()

        tlog(f"saved {len(_minute_data[symbol].index)} days for {symbol}")
Esempio n. 2
0
    def _calc_indicator(self, OHLCV_input):
        """
        Calculates the EMA technical indicator using a wrapper for the TA-lib

        Args:
            :param OHLCV_input:  the dataframe with the Open, High, Low, Close and Volume values
            :type OHLCV_input: pandas DataFrame

        Returns:
            DataFrame with the indicators values.
        """
        try:
            close = OHLCV_input['close'].values[:, 0]
        except IndexError:
            close = OHLCV_input['close'].values

        return DataFrame(MAMA(close, self.__fastlimit, self.__slowlimit))
    async def run(
        self,
        symbol: str,
        shortable: bool,
        position: int,
        minute_history: df,
        now: datetime,
        portfolio_value: float = None,
        trading_api: tradeapi = None,
        debug: bool = False,
        backtesting: bool = False,
    ) -> Tuple[bool, Dict]:
        data = minute_history.iloc[-1]
        mama, fama = MAMA(minute_history["close"])

        if mama[-1] > fama[-1]:
            buy_price = data.close
            stop_price = data.close * 0.98
            target_price = data.close * 1.05

            stop_prices[symbol] = stop_price
            target_prices[symbol] = target_price

            if portfolio_value is None:
                if trading_api:
                    retry = 3
                    while retry > 0:
                        try:
                            portfolio_value = float(
                                trading_api.get_account().portfolio_value)
                            break
                        except ConnectionError as e:
                            tlog(
                                f"[{symbol}][{now}[Error] get_account() failed w/ {e}, retrying {retry} more times"
                            )
                            await asyncio.sleep(0)
                            retry -= 1

                    if not portfolio_value:
                        tlog(
                            "f[{symbol}][{now}[Error] failed to get portfolio_value"
                        )
                        return False, {}
                else:
                    raise Exception(
                        f"{self.name}: both portfolio_value and trading_api can't be None"
                    )

            shares_to_buy = (portfolio_value * config.risk //
                             (data.close - stop_prices[symbol]))
            if not shares_to_buy:
                shares_to_buy = 1

            buy_indicators[symbol] = {
                "mama": mama[-5:].tolist(),
                "fama": fama[-5:].tolist(),
            }

            tlog(
                f"[{self.name}][{now}] Submitting buy for {shares_to_buy} shares of {symbol} at {buy_price} target {target_prices[symbol]} stop {stop_prices[symbol]}"
            )

            return True, {
                "side": "buy",
                "qty": str(shares_to_buy),
                "type": "limit",
                "limit_price": str(buy_price),
            }

        if (await self.is_sell_time(now) and position
                and last_used_strategy[symbol].name == self.name
                and not open_orders.get(symbol)):
            mama, fama = MAMA(minute_history["close"])

            to_sell: bool = False
            if data.close < stop_prices[symbol]:
                reason = "stopped"
                to_sell = True
            elif data.close >= target_prices[symbol]:
                reason = "target reached"
                to_sell = True
            elif mama[-1] < fama[-1]:
                reason = "fama below mama"
                to_sell = True

            if to_sell:
                tlog(
                    f"[{self.name}][{now}] Submitting sell for {position} shares of {symbol} at market {data.close} w reason {reason}"
                )

                sell_indicators[symbol] = {
                    "mama": mama[-5:].tolist(),
                    "fama": fama[-5:].tolist(),
                    "reason": reason,
                }

                return (
                    True,
                    {
                        "side": "sell",
                        "qty": str(position),
                        "type": "market",
                    },
                )

        return False, {}
Esempio n. 4
0
    async def run(
        self,
        symbol: str,
        shortable: bool,
        position: int,
        now: datetime,
        minute_history: df,
        portfolio_value: float = None,
        debug: bool = False,
        backtesting: bool = False,
    ) -> Tuple[bool, Dict]:
        data = minute_history.iloc[-1]
        mama, fama = MAMA(minute_history["close"])

        if mama[-1] > fama[-1]:
            buy_price = data.close
            stop_price = data.close * 0.98
            target_price = data.close * 1.05

            stop_prices[symbol] = stop_price
            target_prices[symbol] = target_price

            shares_to_buy = ((portfolio_value * config.risk //
                              (data.close - stop_prices[symbol]))
                             if portfolio_value else 0)
            if not shares_to_buy:
                shares_to_buy = 1

            buy_indicators[symbol] = {
                "mama": mama[-5:].tolist(),
                "fama": fama[-5:].tolist(),
            }

            tlog(
                f"[{self.name}][{now}] Submitting buy for {shares_to_buy} shares of {symbol} at {buy_price} target {target_prices[symbol]} stop {stop_prices[symbol]}"
            )

            return True, {
                "side": "buy",
                "qty": str(shares_to_buy),
                "type": "limit",
                "limit_price": str(buy_price),
            }

        if (await self.is_sell_time(now) and position
                and last_used_strategy[symbol].name == self.name
                and not open_orders.get(symbol)):
            mama, fama = MAMA(minute_history["close"])

            to_sell: bool = False
            if data.close < stop_prices[symbol]:
                reason = "stopped"
                to_sell = True
            elif data.close >= target_prices[symbol]:
                reason = "target reached"
                to_sell = True
            elif mama[-1] < fama[-1]:
                reason = "fama below mama"
                to_sell = True

            if to_sell:
                tlog(
                    f"[{self.name}][{now}] Submitting sell for {position} shares of {symbol} at market {data.close} w reason {reason}"
                )

                sell_indicators[symbol] = {
                    "mama": mama[-5:].tolist(),
                    "fama": fama[-5:].tolist(),
                    "reason": reason,
                }

                return (
                    True,
                    {
                        "side": "sell",
                        "qty": str(position),
                        "type": "market",
                    },
                )

        return False, {}