-
Notifications
You must be signed in to change notification settings - Fork 241
Description
Hi, when i running an example code in backtesting mode i receive this error message:
2025-05-27 10:04:51,011: yfinance: ERROR: $^IRX: possibly delisted; no price data found (1d 1926-06-21 -> 2025-05-27)
2025-05-27 10:04:51,987: yfinance: ERROR: 429 Client Error: Too Many Requests for url: https://query2.finance.yahoo.com/v10/finance/quoteSummary/%5EIRX?modules=financialData%2CquoteType%2CdefaultKeyStatistics%2CassetProfile%2CsummaryDetail&corsDomain=finance.yahoo.com&formatted=false&symbol=%5EIRX&crumb=Edge%3A+Too+Many+Requests
2025-05-27 10:04:51,995: asyncio: WARNING: [Momentum] Cannot plot returns because the benchmark returns are missing
I check on yahoo finnancials and the ^IRX ticker is not listed, if it possible to change to some thing similar like ^TNX ticker?
I tryed to set the Risk free rate but it is ignored at backtesting.
I updated all the libraries.
This is the code i was trying:
from datetime import datetime
import pandas as pd
from lumibot.strategies.strategy import Strategy
from lumibot.traders import Trader
from lumibot.brokers import Alpaca
from lumibot.backtesting import YahooDataBacktesting
import credentials
class TLTStrategy(Strategy):
def initialize(self):
self.sleeptime = 86400 # Ejecutar una vez al día
self.symbol = "TLT"
self.asset = ""
self.quantity = 1
self.last_trade_date = None
self.trade_direction = None # 'long' o 'short'
def on_trading_iteration(self):
today = pd.Timestamp.today().normalize()
# Entrar en posición corta el primer día del mes
if today.is_month_start and self.trade_direction != 'short':
self.enter_position('short')
# Salir de la posición corta cinco días después
elif self.trade_direction == 'short' and self.last_trade_date and (today - self.last_trade_date).days == 5:
self.exit_position()
# Entrar en posición larga siete días antes del fin de mes
elif (pd.Timestamp(today + pd.offsets.MonthEnd()).day - today.day == 7) and self.trade_direction != 'long':
self.enter_position('long')
# Salir de la posición larga un día antes del fin de mes
elif (pd.Timestamp(today + pd.offsets.MonthEnd()).day - today.day == 1) and self.trade_direction == 'long':
self.exit_position()
self.await_market_to_close()
def enter_position(self, direction):
if direction == 'short':
if self.asset:
self.submit_order(self.create_order(self.asset, self.quantity, "sell"))
self.quantity = int(self.portfolio_value // self.get_last_price(self.symbol))
self.submit_order(self.create_order(self.symbol, self.quantity, "short"))
self.last_trade_date = pd.Timestamp.today().normalize()
self.trade_direction = 'short'
self.asset = self.symbol
elif direction == 'long':
if self.asset:
self.submit_order(self.create_order(self.asset, self.quantity, "sell"))
self.quantity = int(self.portfolio_value // self.get_last_price(self.symbol))
self.submit_order(self.create_order(self.symbol, self.quantity, "buy"))
self.last_trade_date = pd.Timestamp.today().normalize()
self.trade_direction = 'long'
self.asset = self.symbol
self.log_message(f"Entrando en posición {direction} en {self.asset}.")
def exit_position(self):
if self.asset:
self.submit_order(self.create_order(self.asset, self.quantity, "sell"))
self.asset = None
self.quantity = 0
self.trade_direction = None
self.log_message(f"Saliendo de posición en {self.asset}.")
def on_abrupt_closing(self):
self.sell_all()
Estrategia Buy and Hold para SPY
class BuyAndHold(Strategy):
def initialize(self, symbol):
self.symbol = symbol
def on_trading_iteration(self):
if self.get_position(self.symbol).quantity == 0:
self.submit_order(self.create_order(self.symbol, int(self.portfolio_value // self.get_last_price(self.symbol)), "buy"))
self.await_market_to_close()
if name == "main":
is_live = False
if not is_live:
# Backtest de la estrategia TLT
backtesting_start = datetime(2004, 1, 1)
backtesting_end = datetime(2024, 12, 1)
# Configurar una tasa libre de riesgo fija y retraso para evitar error 429
YahooDataBacktesting.sleep_time = 1 # Retraso de 1 segundo entre solicitudes
try:
tlt_results = TLTStrategy.backtest(
YahooDataBacktesting,
backtesting_start,
backtesting_end,
benchmark_asset="SPY",
logfile="./log.txt",
risk_free_rate=0.02 # Tasa libre de riesgo fija (2%)
)
print("Resultados de la estrategia TLT:")
print(tlt_results)
except Exception as e:
print(f"Error durante el backtesting: {e}")
else:
# Ejecutar la estrategia TLT en vivo
trader = Trader()
broker = Alpaca(credentials.ALPACA_CONFIG)
# Estrategia TLT
tlt_strategy = TLTStrategy(broker)
trader.add_strategy(tlt_strategy)
trader.run_all()