Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UnboundLocalError: cannot access local variable 'loop_limit' where it is not associated with a value #341

Open
jjonesdesign opened this issue Jan 3, 2024 · 12 comments

Comments

@jjonesdesign
Copy link

There appears to be an error from get_historical_prices when specifying a timestep other than 'minute' 'day' etc.

def on_trading_iteration(self):
        symbol = "AAPL"

        # Get 3 bars, each 15 minutes of time
        Last3_BarData = self.get_historical_prices(symbol,3,"5 minutes")

outputs error

apscheduler.executors.default: ERROR: Job "On Trading Iteration Main Thread (trigger: cron[second='*'], next run at: 2024-01-03 11:40:41 PST)" raised an exception
Traceback (most recent call last):
  File "C:\Python311\Lib\site-packages\apscheduler\executors\base.py", line 125, in run_job
    retval = job.func(*job.args, **job.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\lumibot\strategies\strategy_executor.py", line 274, in func_output
    result = func_input(self, *args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\lumibot\strategies\strategy_executor.py", line 298, in func_output
    result = func_input(self, *args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\lumibot\strategies\strategy_executor.py", line 211, in func_output
    return func_input(self, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\lumibot\strategies\strategy_executor.py", line 378, in _on_trading_iteration
    on_trading_iteration()
  File "C:\Python311\Lib\site-packages\lumibot\tools\decorators.py", line 62, in func_output
    frame, result = call_function_get_frame(func_input, *args, **kwargs)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\lumibot\tools\decorators.py", line 34, in call_function_get_frame
    result = func(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\Shadow\Documents\Python-Tradingbot\lumibot_swinghigh.py", line 48, in on_trading_iteration
    Last3_BarData = self.get_historical_prices(symbol,3,"5 minutes")
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\lumibot\strategies\strategy.py", line 2845, in get_historical_prices
    return self.broker.data_source.get_historical_prices(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\lumibot\data_sources\data_source.py", line 255, in get_historical_prices
    response = self._pull_source_symbol_bars(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\lumibot\data_sources\alpaca_data.py", line 297, in _pull_source_symbol_bars
    response = self._pull_source_bars(
               ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\lumibot\data_sources\alpaca_data.py", line 276, in _pull_source_bars
    data = self.get_barset_from_api(asset, parsed_timestep, quote=quote, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\site-packages\lumibot\data_sources\alpaca_data.py", line 197, in get_barset_from_api
    while loop_limit / limit <= 64 and len(df) < limit:
          ^^^^^^^^^^
UnboundLocalError: cannot access local variable 'loop_limit' where it is not associated with a value

I followed the documentation here: https://lumibot.lumiwealth.com/strategy_methods.data/lumibot.strategies.strategy.Strategy.get_historical_prices.html

@jjonesdesign
Copy link
Author

It appears that 'loop_limit' has no default value, and isn't getting set if 'start' is not none.

https://github.com/Lumiwealth/lumibot/blob/dev/lumibot/data_sources/alpaca_data.py

@grzesir
Copy link
Contributor

grzesir commented Jan 3, 2024 via email

@jjonesdesign
Copy link
Author

@grzesir Thanks for the reply.

That would make sense if it's not implemented yet :D I was looking around to see if I could implement a solution but not currently confident enough in python to try and do something I could commit.

I am currently using 1 minute increments but didn't know about the pandas agg() function. Appreciate the feedback!

@grzesir
Copy link
Contributor

grzesir commented Jan 4, 2024 via email

@jjonesdesign
Copy link
Author

jjonesdesign commented Jan 4, 2024

@grzesir ChatGPT has been a trainwreck LOL. I don't think it fully understands Pandas and the DataFrame's. Maybe I am just using it wrong.

I have been playing with it all day and have just now gotten things working properly as I was needing them. It took some work, but having a final result is a good reward.

How would one go about contributing to the lumibot docs page? I see a few things that are off (or didn't work). As a sign of appreciation for your library I would be happy to make some fixes and maybe add some code examples that I got working for future users.

Example: https://lumibot.lumiwealth.com/backtesting.polygon.html

Here’s another example but for for stocks:

my_strat = MyStrategy(
      broker=broker,
      backtesting_start=backtesting_start,
      backtesting_end=backtesting_end,
      benchmark_asset=Asset(symbol="BTC", asset_type="crypto")
)

Should be:

my_strat = MyStrategy(
        broker=broker,
        backtesting_start=backtesting_start,
        backtesting_end=backtesting_end,
        benchmark_asset=Asset(symbol="SPY", asset_type="stock")
)

Thanks.

@grzesir
Copy link
Contributor

grzesir commented Jan 4, 2024 via email

@jjonesdesign
Copy link
Author

@grzesir I tried several different prompts. It's not that the output wasn't helpful, it was that chatgpt didn't seem to know how to properly call the DataFrame constructor with all the needed parameters. I ended up finding a solution more closely related to the examples on the docs, but just a bit different, which means I didn't even use the output from chatgpt.

I also didn't include anything about ohlc, completely slipped my mind to include :/

I don't want to keep cluttering this submission up, but know I appreciate your timely and helpful responses. I will be jumping into the discord, can provide some of the feedback on issues I was having from the docs.

Thanks!

@grzesir
Copy link
Contributor

grzesir commented Jan 4, 2024 via email

@jjonesdesign
Copy link
Author

@grzesir Appreciate it. This is what I got working

# Get 3, 15 minute blocks of data for multiple symbols
TickersToWatch = ["SPY","AAPL"]
data = self.get_historical_prices_for_assets(TickersToWatch, 45, "minute", include_after_hours=False)
    # Resample Bars data into 15 minute samples.
    for i,v in data.items():
        df = v.df
        resampled_df = df.resample('15T').agg({
            'open': 'first',
            'high': 'max',
            'low': 'min',
            'close': 'last',
            'volume': 'sum'
        }).dropna()

        print(resampled_df)

The example here: https://lumibot.lumiwealth.com/strategy_methods.data/lumibot.strategies.strategy.Strategy.get_historical_prices_for_assets.html

# Get the data for AAPL and GOOG for the last 30 minutes
bars =  self.get_historical_prices_for_assets(["AAPL", "GOOG"], 30, "minute")
for asset in bars:
    self.log_message(asset.df)

Just didn't seem to work. It would throw the error asset has no df. Guessing it's a setup issue on my end. But I got it working one way or another :D

@grzesir
Copy link
Contributor

grzesir commented Jan 4, 2024 via email

@jjonesdesign
Copy link
Author

@grzesir I am currently running backtesting using Polygon for the data.

My plan is to run my strategy every 15 minutes during live market. starting with paper of course.

Now that I am getting the data how I want it, I am working on building out the buy/sell logics.

@jjonesdesign
Copy link
Author

@grzesir fatal: unable to access 'https://github.com/Lumiwealth/lumibot.git/': The requested URL returned error: 403
😢

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants