question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

No current event loop in thread when running the example

See original GitHub issue

I tried to run the example in README.md, but I got a “No current event loop in thread” exception.

I have the following packages installed

  • Python 3.6.8
  • alpaca-backtrader-api 0.3
  • alpaca-trade-api 0.35
  • backtrader 1.9.74.123

Python script that I used:

import backtrader as bt
import alpaca_backtrader_api

from datetime import datetime

import sceret

class SmaCross(bt.SignalStrategy):
    def __init__(self):
        sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30)
        crossover = bt.ind.CrossOver(sma1, sma2)
        self.signal_add(bt.SIGNAL_LONG, crossover)

cerebro = bt.Cerebro()
cerebro.addstrategy(SmaCross)

store = alpaca_backtrader_api.AlpacaStore(
    key_id=sceret.api_key_id,
    secret_key=sceret.api_secret,
    paper=True
)

broker = store.getbroker()  # or just alpaca_backtrader_api.AlpacaBroker()
cerebro.setbroker(broker)

DataFactory = store.getdata # or use alpaca_backtrader_api.AlpacaData
data0 = DataFactory(dataname='AAPL', 
                    historical=True, 
                    fromdate=datetime(2015, 1,1), 
                    timeframe=bt.TimeFrame.TFrame("Days"))  # Supported timeframes: "Days"/"Minutes"
cerebro.adddata(data0)

cerebro.run(exactbars=1)
cerebro.plot()

The exception that I got.

Exception in thread Thread-97:
Traceback (most recent call last):
  File "C:\Users\SomeUser\Miniconda3\envs\alpaca-trade\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Users\SomeUser\Miniconda3\envs\alpaca-trade\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\SomeUser\Miniconda3\envs\alpaca-trade\lib\site-packages\alpaca_backtrader_api\alpacastore.py", line 309, in _t_streaming_events
    base_url=self.p.base_url)
  File "C:\Users\SomeUser\Miniconda3\envs\alpaca-trade\lib\site-packages\alpaca_backtrader_api\alpacastore.py", line 91, in __init__
    self.conn = tradeapi.StreamConn(api_key, api_secret, base_url)
  File "C:\Users\SomeUser\Miniconda3\envs\alpaca-trade\lib\site-packages\alpaca_trade_api\stream2.py", line 21, in __init__
    self.loop = asyncio.get_event_loop()
  File "C:\Users\SomeUser\Miniconda3\envs\alpaca-trade\lib\asyncio\events.py", line 694, in get_event_loop
    return get_event_loop_policy().get_event_loop()
  File "C:\Users\SomeUser\Miniconda3\envs\alpaca-trade\lib\asyncio\events.py", line 602, in get_event_loop
    % threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-97'.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
thedatadaviscommented, Jul 25, 2019

I had this issue as well.

The culprit appears to be in the alpaca-trade-api itself. Update the stream2.py module to create a new event loop if one is not running.

Change this:

# /site-packages/alpaca_trade_api/stream2.py
class StreamConn(object):
    def __init__(self, key_id=None, secret_key=None, base_url=None):
        self._key_id, self._secret_key = get_credentials(key_id, secret_key)
        base_url = re.sub(r'^http', 'ws', base_url or get_base_url())
        self._endpoint = base_url + '/stream'
        self._handlers = {}
        self._handler_symbols = {}
        self._base_url = base_url
        self._ws = None
        self.polygon = None
        self.loop = asyncio.get_event_loop() # where Runtime Error is occuring

To this:

# /site-packages/alpaca_trade_api/stream2.py
class StreamConn(object):
    def __init__(self, key_id=None, secret_key=None, base_url=None):
        self._key_id, self._secret_key = get_credentials(key_id, secret_key)
        base_url = re.sub(r'^http', 'ws', base_url or get_base_url())
        self._endpoint = base_url + '/stream'
        self._handlers = {}
        self._handler_symbols = {}
        self._base_url = base_url
        self._ws = None
        self.polygon = None

        # Add try block for get_event_loop()
        # If no current loop then create one
        try:
            self.loop = asyncio.get_event_loop()
        except:
            self.loop = asyncio.new_event_loop()
            asyncio.set_event_loop(self.loop)

Edit Re: Plotting

The sample backtest shows that the exactbars parameter should be set to either 0 or -1 or -2 to enable plotting.

Once you make this change, cerebro.plot() will return an array of charts. You can access the one from this example using cerebro.plot()[0][0]

# example_backtest.py

# ...

data0 = DataFactory(dataname='AAPL', historical=True, fromdate=datetime(2015, 1,1), timeframe=bt.TimeFrame.TFrame("Days"))  # Supported timeframes: "Days"/"Minutes"
cerebro.adddata(data0)

cerebro.run(exactbars=0) # or -1 or -2
cerebro.plot()[0][0]
0reactions
shlomikushchicommented, Apr 3, 2020

this issue should be resolved with the updated version on pypi. let me know if you still encounter issues. please note - you must have a funded account to do paper/live trading. you could do backtesting by getting the data not through polygon (polygon access requires a funded account) let me know if there are still issues

Read more comments on GitHub >

github_iconTop Results From Across the Web

RuntimeError: There is no current event loop in thread in ...
If the target callable is not a coroutine function, it will be run in a worker thread (due to historical reasons), hence the...
Read more >
How to fix Python asyncio RuntimeError: There is no current ...
You are trying to run asyncio.get_event_loop() in some thread other than the main thread – however, asyncio only generates an event loop for ......
Read more >
Event Loop — Python 3.11.1 documentation
Return the running event loop in the current OS thread. Raise a RuntimeError if there is no running event loop. This function can...
Read more >
runtimeerror: there is no current event loop in thread - You.com
1. Threads do not have an event loop, you simply need to use the main thread loop. t = Thread (target=run, args= [client ......
Read more >
RuntimeError: There is no current event loop in ... - GitHub
"""This example shows a streaming dashboard with Panel. Panel runs on top of the Tornado server. Tornado is a fast, asynchronous web server ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found