Giter Club home page Giter Club logo

mltradingbot's Introduction

TraderBot

Build a trader bot which looks at sentiment of live news events and trades appropriately.

See it live and in action ๐Ÿ“บ

Startup ๐Ÿš€

  1. Create a virtual environment conda create -n trader python=3.10
  2. Activate it conda activate trader
  3. Install initial deps pip install lumibot timedelta alpaca-trade-api==3.1.1
  4. Install transformers and friends pip install torch torchvision torchaudio transformers
  5. Update the API_KEY and API_SECRET with values from your Alpaca account
  6. Run the bot python tradingbot.py

N.B. Torch installation instructions will vary depending on your operating system and hardware. See here for more: PyTorch Installation Instructions

If you're getting an SSL error when you attempt to call out to the Alpaca Trading api, you'll need to install the required SSL certificates into your machine.

  1. Download the following intermediate SSL Certificates, these are required to communicate with Alpaca
  1. Once downloaded, change the file extension of each file to .cer
  2. Double click the file and run through the wizard to install it, use all of the default selections.

# Other References ๐Ÿ”—

-Lumibot:trading bot library, makes lifecycle stuff easier .

Who, When, Why?

๐Ÿ‘จ๐Ÿพโ€๐Ÿ’ป Author: Nick Renotte
๐Ÿ“… Version: 1.x
๐Ÿ“œ License: This project is licensed under the MIT License

mltradingbot's People

Contributors

nicknochnack avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mltradingbot's Issues

Issue with version control - lumibot.backtesting not working!

I was folloing the instructions, I have created conda env and all required installed successfully with no error.

conda create -n trader python=3.10
conda activate trader
pip install lumibot timedelta alpaca-trade-api
pip install torch torchvision torchaudio transformers

I've added my alpaca API key then when I run tradingbot.py hit the following error, which seems to be associated with

(trader) (base) someuser@trading_bot % (trader) % /opt/homebrew/Caskroom/miniconda/base/envs/trader/bin/python /Users
/ahmedalhendi/Dropbox/Mac/Desktop/trading_bot/tradingbot.py
ERROR:yfinance:Failed to get ticker '^IRX' reason: HTTPSConnectionPool(host='fc.yahoo.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x17c5f63e0>: Failed to establish a new connection: [Errno 61] Connection refused'))
ERROR:yfinance:^IRX: No price data found, symbol may be delisted (period=7d)
ERROR:root:Error getting the risk free rate: unsupported operand type(s) for /: 'NoneType' and 'int'
Starting backtest for MLTrader...
ERROR:yfinance:Failed to get ticker '^IRX' reason: HTTPSConnectionPool(host='fc.yahoo.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x17c5f4e20>: Failed to establish a new connection: [Errno 61] Connection refused'))
ERROR:yfinance:^IRX: No price data found, symbol may be delisted (period=7d)
ERROR:root:Error getting the risk free rate: unsupported operand type(s) for /: 'NoneType' and 'int'
INFO:backtest_stats:Starting backtest...
Progress |-----------------------------------------------------------------------------|   0.10%  [Elapsed: 0:00:00 ETA: 0:09:26] 2024-01-30 22:54:08,593: yfinance: ERROR: Failed to get ticker 'SPY' reason: HTTPSConnectionPool(host='fc.yahoo.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x17f659540>: Failed to establish a new connection: [Errno 61] Connection refused'))
2024-01-30 22:54:08,593: yfinance: ERROR: SPY: No timezone found, symbol may be delisted
2024-01-30 22:54:08,597: root: ERROR: YAHOO did not return data for symbol SPY. Make sure this symbol is valid.
2024-01-30 22:54:08,597: root: ERROR: unsupported operand type(s) for /: 'float' and 'NoneType'
2024-01-30 22:54:08,598: root: ERROR: Traceback (most recent call last):
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 831, in run
    self._run_trading_session()
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 782, in _run_trading_session
    self._on_trading_iteration()
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 274, in func_output
    result = func_input(self, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 298, in func_output
    result = func_input(self, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 87, in func_output
    return func_input(self, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 378, in _on_trading_iteration
    on_trading_iteration()
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/tools/decorators.py", line 62, in func_output
    frame, result = call_function_get_frame(func_input, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/tools/decorators.py", line 30, in call_function_get_frame
    result = func(*args, **kwargs)
  File "/Users/ahmedalhendi/Dropbox/Mac/Desktop/trading_bot/tradingbot.py", line 49, in on_trading_iteration
    cash, last_price, quantity = self.position_sizing()
  File "/Users/ahmedalhendi/Dropbox/Mac/Desktop/trading_bot/tradingbot.py", line 31, in position_sizing
    quantity = round(cash * self.cash_at_risk / last_price,0)
TypeError: unsupported operand type(s) for /: 'float' and 'NoneType'

Exception in thread MLTrader:
Traceback (most recent call last):
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 831, in run
    self._run_trading_session()
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 782, in _run_trading_session
    self._on_trading_iteration()
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 274, in func_output
    result = func_input(self, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 298, in func_output
    result = func_input(self, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 87, in func_output
    return func_input(self, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 378, in _on_trading_iteration
    on_trading_iteration()
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/tools/decorators.py", line 62, in func_output
    frame, result = call_function_get_frame(func_input, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/tools/decorators.py", line 30, in call_function_get_frame
    result = func(*args, **kwargs)
  File "/Users/ahmedalhendi/Dropbox/Mac/Desktop/trading_bot/tradingbot.py", line 49, in on_trading_iteration
    cash, last_price, quantity = self.position_sizing() 
  File "/Users/ahmedalhendi/Dropbox/Mac/Desktop/trading_bot/tradingbot.py", line 31, in position_sizing
    quantity = round(cash * self.cash_at_risk / last_price,0)
TypeError: unsupported operand type(s) for /: 'float' and 'NoneType'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 844, in run
    raise RuntimeError("Exception encountered, stopping BackTest.") from e
RuntimeError: Exception encountered, stopping BackTest.

Creating indicators plot...

After that I tried to track down the issue so I started with example here on https://lumibot.lumiwealth.com/backtesting.yahoo.html

from datetime import datetime

from lumibot.backtesting import BacktestingBroker, YahooDataBacktesting
from lumibot.strategies import Strategy
from lumibot.traders import Trader


# A simple strategy that buys AAPL on the first day
class MyStrategy(Strategy):
    def on_trading_iteration(self):
        if self.first_iteration:
            aapl_price = self.get_last_price("AAPL")
            quantity = self.portfolio_value // aapl_price
            order = self.create_order("AAPL", quantity, "buy")
            self.submit_order(order)


# Pick the dates that you want to start and end your backtest
# and the allocated budget
backtesting_start = datetime(2020, 11, 1)
backtesting_end = datetime(2020, 12, 31)

# Run the backtest
trader = Trader(backtest=True)
data_source = YahooDataBacktesting(
    datetime_start=backtesting_start,
    datetime_end=backtesting_end,
)
broker = BacktestingBroker(data_source)
strat = MyStrategy(
    broker=broker,
)
trader.add_strategy(strat)
trader.run_all()

which also results in similar error shown below

(trader) (base) someuser@trading_bot  % /opt/homebrew/Caskroom/miniconda/base/envs/trader/bin/python /Users
/ahmedalhendi/Dropbox/Mac/Desktop/trading_bot/test.py
Failed to get ticker '^IRX' reason: HTTPSConnectionPool(host='fc.yahoo.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x16d3e4fd0>: Failed to establish a new connection: [Errno 61] Connection refused'))
^IRX: No price data found, symbol may be delisted (period=7d)
ERROR:root:Error getting the risk free rate: unsupported operand type(s) for /: 'NoneType' and 'int'
Progress |โ–ˆ----------------------------------------------------------------------------|   2.39%  [Elapsed: 0:00:00 ETA: 0:00:21] 2024-01-30 22:55:17,435: yfinance: ERROR: Failed to get ticker 'AAPL' reason: HTTPSConnectionPool(host='fc.yahoo.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x16f871e70>: Failed to establish a new connection: [Errno 61] Connection refused'))
2024-01-30 22:55:17,435: yfinance: ERROR: AAPL: No timezone found, symbol may be delisted
2024-01-30 22:55:17,439: root: ERROR: YAHOO did not return data for symbol AAPL. Make sure this symbol is valid.
2024-01-30 22:55:17,440: root: ERROR: unsupported operand type(s) for //: 'float' and 'NoneType'
2024-01-30 22:55:17,440: root: ERROR: Traceback (most recent call last):
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 831, in run
    self._run_trading_session()
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 782, in _run_trading_session
    self._on_trading_iteration()
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 274, in func_output
    result = func_input(self, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 298, in func_output
    result = func_input(self, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 87, in func_output
    return func_input(self, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 378, in _on_trading_iteration
    on_trading_iteration()
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/tools/decorators.py", line 62, in func_output
    frame, result = call_function_get_frame(func_input, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/tools/decorators.py", line 30, in call_function_get_frame
    result = func(*args, **kwargs)
  File "/Users/ahmedalhendi/Dropbox/Mac/Desktop/trading_bot/test.py", line 13, in on_trading_iteration
    quantity = self.portfolio_value // aapl_price
TypeError: unsupported operand type(s) for //: 'float' and 'NoneType'

Exception in thread MyStrategy:
Traceback (most recent call last):
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 831, in run
    self._run_trading_session()
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 782, in _run_trading_session
    self._on_trading_iteration()
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 274, in func_output
    result = func_input(self, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 298, in func_output
    result = func_input(self, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 87, in func_output
    return func_input(self, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 378, in _on_trading_iteration
    on_trading_iteration()
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/tools/decorators.py", line 62, in func_output
    frame, result = call_function_get_frame(func_input, *args, **kwargs)
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/tools/decorators.py", line 30, in call_function_get_frame
    result = func(*args, **kwargs)
  File "/Users/ahmedalhendi/Dropbox/Mac/Desktop/trading_bot/test.py", line 13, in on_trading_iteration
    quantity = self.portfolio_value // aapl_price
TypeError: unsupported operand type(s) for //: 'float' and 'NoneType'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "/opt/homebrew/Caskroom/miniconda/base/envs/trader/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 844, in run
    raise RuntimeError("Exception encountered, stopping BackTest.") from e
RuntimeError: Exception encountered, stopping BackTest.

Creating indicators plot...

So I think it is the issue with lumibot version I would suggest that update the installation section with requirements.txt so that we can that we can replicate your work.. e.g.

# from nicknochnack pc
pip freeze > requirements.txt

then on our to replicate your work we can run

# using pip
pip install -r requirements.txt

# using Conda
conda create --name trader --file requirements.txt

Looking forward to your reply.. thank you

Paper Trader didn't place a trade.

Monitoring the bot, however it has yet to place a paper trade. This is all it does below:
0|tradingb | 2024-01-30 17:55:46,774: root: INFO: mlstrat : Executing the initialize lifecycle method
0|tradingb | 2024-01-30 17:55:58,085: root: INFO: mlstrat : Executing the before_starting_trading lifecycle method
0|tradingb | 2024-01-30 17:55:58,224: root: INFO: mlstrat : Strategy will check in again at: 2024-01-30 18:00:00
0|tradingb | 2024-01-30 17:58:49,988: root: INFO: Untracked order 211b4005-1fc2-45be-a5a6-8bb9b752ecac was logged by broker alpaca
0|tradingb | 2024-01-30 17:58:49,999: root: INFO: Untracked order 211b4005-1fc2-45be-a5a6-8bb9b752ecac was logged by broker alpaca
0|tradingb | 2024-01-30 17:58:50,611: root: INFO: Untracked order 211b4005-1fc2-45be-a5a6-8bb9b752ecac was logged by broker alpaca

0|tradingbot | 2024-01-30 18:00:02,463: root: INFO: mlstrat : Executing the on_trading_iteration lifecycle method at 2024-01-30 18:00:00
0|tradingbot | 2024-01-30 18:00:09,850: root: INFO: mlstrat : Trading iteration ended at 2024-01-30 18:00:09, next check in time is 2024-01-30 19:00:00
0|tradingbot | 2024-01-30 18:00:28,894: root: INFO: Untracked order aac780c5-b378-4c91-a8cd-b348c3cd7f21 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:00:28,901: root: INFO: Untracked order aac780c5-b378-4c91-a8cd-b348c3cd7f21 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:00:29,199: root: INFO: Untracked order aac780c5-b378-4c91-a8cd-b348c3cd7f21 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:00:56,551: root: INFO: Untracked order c373fc64-7561-433f-81c2-2a829a93f903 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:00:56,566: root: INFO: Untracked order c373fc64-7561-433f-81c2-2a829a93f903 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:00:57,197: root: INFO: Untracked order c373fc64-7561-433f-81c2-2a829a93f903 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:01:24,988: root: INFO: Untracked order e591619d-1511-4024-b2aa-d20d094461d8 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:01:24,996: root: INFO: Untracked order e591619d-1511-4024-b2aa-d20d094461d8 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:01:25,505: root: INFO: Untracked order e591619d-1511-4024-b2aa-d20d094461d8 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:01:32,146: root: INFO: Untracked order d564aeb1-2d8e-4142-b1c7-688c93741af0 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:01:32,154: root: INFO: Untracked order d564aeb1-2d8e-4142-b1c7-688c93741af0 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:01:32,578: root: INFO: Untracked order d564aeb1-2d8e-4142-b1c7-688c93741af0 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:01:39,279: root: INFO: Untracked order 6e3b7600-53d9-401c-a853-2e95caf22b4b was logged by broker alpaca
0|tradingbot | 2024-01-30 18:01:39,287: root: INFO: Untracked order 6e3b7600-53d9-401c-a853-2e95caf22b4b was logged by broker alpaca
0|tradingbot | 2024-01-30 18:01:39,762: root: INFO: Untracked order 6e3b7600-53d9-401c-a853-2e95caf22b4b was logged by broker alpaca
0|tradingbot | 2024-01-30 18:02:00,070: root: INFO: Untracked order 7a02326a-5b71-4559-9a41-0817bc19743f was logged by broker alpaca
0|tradingbot | 2024-01-30 18:02:00,084: root: INFO: Untracked order 7a02326a-5b71-4559-9a41-0817bc19743f was logged by broker alpaca
0|tradingbot | 2024-01-30 18:02:00,521: root: INFO: Untracked order 7a02326a-5b71-4559-9a41-0817bc19743f was logged by broker alpaca
0|tradingbot | 2024-01-30 18:05:45,112: root: INFO: Untracked order ead92392-c849-4b2e-af58-343678100566 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:05:45,131: root: INFO: Untracked order ead92392-c849-4b2e-af58-343678100566 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:05:45,676: root: INFO: Untracked order ead92392-c849-4b2e-af58-343678100566 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:09:54,951: root: INFO: Untracked order 593bc5fa-2e8f-4b30-bf16-7539be40d700 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:09:54,974: root: INFO: Untracked order 593bc5fa-2e8f-4b30-bf16-7539be40d700 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:09:55,465: root: INFO: Untracked order 593bc5fa-2e8f-4b30-bf16-7539be40d700 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:10:11,882: root: INFO: Untracked order fa5bcc44-797a-427d-9572-35bcf39a1cc2 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:10:11,891: root: INFO: Untracked order fa5bcc44-797a-427d-9572-35bcf39a1cc2 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:10:12,164: root: INFO: Untracked order fa5bcc44-797a-427d-9572-35bcf39a1cc2 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:10:42,036: root: INFO: Untracked order d71aa6fc-d2fd-4b0a-a575-9c8305b20bdc was logged by broker alpaca
0|tradingbot | 2024-01-30 18:10:42,052: root: INFO: Untracked order d71aa6fc-d2fd-4b0a-a575-9c8305b20bdc was logged by broker alpaca
0|tradingbot | 2024-01-30 18:10:42,459: root: INFO: Untracked order d71aa6fc-d2fd-4b0a-a575-9c8305b20bdc was logged by broker alpaca
0|tradingbot | 2024-01-30 18:10:48,389: root: INFO: Untracked order 1037325a-4044-4294-8f3f-1308c758eeb1 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:10:48,397: root: INFO: Untracked order 1037325a-4044-4294-8f3f-1308c758eeb1 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:10:48,606: root: INFO: Untracked order 1037325a-4044-4294-8f3f-1308c758eeb1 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:11:46,978: root: INFO: Untracked order 781c8314-39bd-4c40-b6c1-3cc8e2557429 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:11:46,990: root: INFO: Untracked order 781c8314-39bd-4c40-b6c1-3cc8e2557429 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:11:47,137: root: INFO: Untracked order 781c8314-39bd-4c40-b6c1-3cc8e2557429 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:13:14,847: root: INFO: Untracked order cc01b60f-5a7f-45e4-80a9-e8d2921ccfe8 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:13:14,854: root: INFO: Untracked order cc01b60f-5a7f-45e4-80a9-e8d2921ccfe8 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:13:15,392: root: INFO: Untracked order cc01b60f-5a7f-45e4-80a9-e8d2921ccfe8 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:17:05,043: root: INFO: Untracked order 12f8ed3d-96d6-4238-a46f-be2e1d1c61c5 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:17:05,049: root: INFO: Untracked order 12f8ed3d-96d6-4238-a46f-be2e1d1c61c5 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:17:05,216: root: INFO: Untracked order 12f8ed3d-96d6-4238-a46f-be2e1d1c61c5 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:17:48,565: root: INFO: Untracked order 645f82a8-30cf-4534-8e08-b7aa024fd248 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:17:48,574: root: INFO: Untracked order 645f82a8-30cf-4534-8e08-b7aa024fd248 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:17:48,905: root: INFO: Untracked order 645f82a8-30cf-4534-8e08-b7aa024fd248 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:17:52,527: root: INFO: Untracked order dab9ae3d-9357-404b-ada6-2fb965d96a62 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:17:52,537: root: INFO: Untracked order dab9ae3d-9357-404b-ada6-2fb965d96a62 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:17:53,062: root: INFO: Untracked order dab9ae3d-9357-404b-ada6-2fb965d96a62 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:19:41,944: root: INFO: Untracked order e94821a5-858a-4dd7-a452-60b004c711ef was logged by broker alpaca
0|tradingbot | 2024-01-30 18:19:41,969: root: INFO: Untracked order e94821a5-858a-4dd7-a452-60b004c711ef was logged by broker alpaca
0|tradingbot | 2024-01-30 18:19:42,456: root: INFO: Untracked order e94821a5-858a-4dd7-a452-60b004c711ef was logged by broker alpaca
0|tradingbot | 2024-01-30 18:21:33,256: root: INFO: Untracked order 9c15fcc3-bdba-413b-ada0-92870d041915 was logged by broker alpaca
0|tradingbot | 2024-01-30 18:21:33,265: root: INFO: Untracked order 9c15fcc3-bdba-413b-ada0-92870d041915 was logged by broker alpaca

Compatible versions of alpaca-py, alpaca-trade-api and lumibot

What recent versions of alpaca-py, alpaca-trade-api and lumibot are comaptible?
I've tried multiple combinations but it always comes down to a ResolutionImpossible due to websockets
image
If I lower the version of alpaca-py, then lumibot will not be compatible with it anymore.

AttributeError: 'REST' object has no attribute 'get_news'

Using your instructions from the ReadMe leads to a attribution error:
AttributeError: 'REST' object has no attribute 'get_news'. The full traceback:

(venv) MLTradingBot % python tradingbot.py
Starting backtest for MLTrader...
INFO:backtest_stats:Starting backtest...
Progress |--------------------------------------------------------------------------------------------------------| 0.10% [Elapsed: 0:00:02 ETA: 0:38:27] 2024-01-20 14:56:56,805: root: ERROR: 'REST' object has no attribute 'get_news'
2024-01-20 14:56:56,809: root: ERROR: Traceback (most recent call last):
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 831, in run
self._run_trading_session()
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 782, in _run_trading_session
self._on_trading_iteration()
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 274, in func_output
result = func_input(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 298, in func_output
result = func_input(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 87, in func_output
return func_input(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 378, in _on_trading_iteration
on_trading_iteration()
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/tools/decorators.py", line 62, in func_output
frame, result = call_function_get_frame(func_input, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/tools/decorators.py", line 30, in call_function_get_frame
result = func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/tradingbot.py", line 50, in on_trading_iteration
probability, sentiment = self.get_sentiment()
^^^^^^^^^^^^^^^^^^^^
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/tradingbot.py", line 41, in get_sentiment
news = self.api.get_news(symbol=self.symbol,
^^^^^^^^^^^^^^^^^
AttributeError: 'REST' object has no attribute 'get_news'

Exception in thread MLTrader:
Traceback (most recent call last):
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 831, in run
self._run_trading_session()
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 782, in _run_trading_session
self._on_trading_iteration()
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 274, in func_output
result = func_input(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 298, in func_output
result = func_input(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 87, in func_output
return func_input(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 378, in _on_trading_iteration
on_trading_iteration()
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/tools/decorators.py", line 62, in func_output
frame, result = call_function_get_frame(func_input, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/tools/decorators.py", line 30, in call_function_get_frame
result = func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/tradingbot.py", line 50, in on_trading_iteration
probability, sentiment = self.get_sentiment()
^^^^^^^^^^^^^^^^^^^^
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/tradingbot.py", line 41, in get_sentiment
news = self.api.get_news(symbol=self.symbol,
^^^^^^^^^^^^^^^^^
AttributeError: 'REST' object has no attribute 'get_news'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 1045, in _bootstrap_inner
self.run()
File "/Users/herzphi/Library/Mobile Documents/comappleCloudDocs/Programming/MLTradingBot/venv/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 844, in run
raise RuntimeError("Exception encountered, stopping BackTest.") from e
RuntimeError: Exception encountered, stopping BackTest.

Creating indicators plot...
(venv) herzphi@MacBook-Pro-von-Philipp MLTradingBot %

SSL Certificate Issue on Windows 10 with Anaconda (with solution)

I followed the guide in Readme file to try and fix the SSL issue. It didn't work. What worked is the following...
Run in pyhton:
print(ssl.get_default_verify_paths().openssl_cafile)
It will show you the directory where you should have your root certs for python. In my case that directory didn't exist. I created it. Copied isrg-root-x1-cross-signed.pem file into that directory and renamed it to "cert.pem". Works like a charm now. If you already have "cert.pem" - then you would need to use openssl to merge isrg-root-x1 with your existing certs.

pip websocket errors

Backtesting works, but that's as far as i've gotten into testing when i noticed this error.
pip install alpaca-trade-api==3.1.1
however this error shows up:
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
alpaca-py 0.14.0 requires websockets<12.0.0,>=11.0.3, but you have websockets 10.4 which is incompatible.
So I ran:
pip install "websockets>=11.0.3,<12.0"

ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
alpaca-trade-api 3.1.1 requires websockets<11,>=9.0, but you have websockets 11.0.3 which is incompatible.
Successfully installed websockets-11.0.3

What is the best way to deal with this?

ERROR: Strategy.create_order() got an unexpected keyword argument 'type'

Running on MacOS Silicon. Prep my system exactly to your README.

python tradingbot.py
Starting backtest for MLTrader...
INFO:backtest_stats:Starting backtest...
Progress |โ–ˆโ–ˆ---------------------------------------------------------------------------------------------------| 2.29% [Elapsed: 0:00:05 ETA: 0:03:38]2024-03-04 19:31:31,208: root: ERROR: Strategy.create_order() got an unexpected keyword argument 'type'
2024-03-04 19:31:31,209: root: ERROR: Traceback (most recent call last):
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 822, in run
self._run_trading_session()
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 773, in _run_trading_session
self._on_trading_iteration()
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 286, in func_output
result = func_input(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 310, in func_output
result = func_input(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 86, in func_output
return func_input(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 388, in _on_trading_iteration
on_trading_iteration()
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/tools/decorators.py", line 62, in func_output
frame, result = call_function_get_frame(func_input, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/tools/decorators.py", line 30, in call_function_get_frame
result = func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/peterboivin/Documents/VisualStudioProjects/MLTradingBot/tradingbot.py", line 69, in on_trading_iteration
order = self.create_order(
^^^^^^^^^^^^^^^^^^
TypeError: Strategy.create_order() got an unexpected keyword argument 'type'

Exception in thread MLTrader:
Traceback (most recent call last):
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 822, in run
self._run_trading_session()
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 773, in _run_trading_session
self._on_trading_iteration()
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 286, in func_output
result = func_input(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 310, in func_output
result = func_input(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 86, in func_output
return func_input(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 388, in _on_trading_iteration
on_trading_iteration()
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/tools/decorators.py", line 62, in func_output
frame, result = call_function_get_frame(func_input, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/tools/decorators.py", line 30, in call_function_get_frame
result = func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/peterboivin/Documents/VisualStudioProjects/MLTradingBot/tradingbot.py", line 69, in on_trading_iteration
order = self.create_order(
^^^^^^^^^^^^^^^^^^
TypeError: Strategy.create_order() got an unexpected keyword argument 'type'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/opt/anaconda3/lib/python3.11/threading.py", line 1045, in _bootstrap_inner
self.run()
File "/opt/anaconda3/lib/python3.11/site-packages/lumibot/strategies/strategy_executor.py", line 835, in run
raise RuntimeError("Exception encountered, stopping BackTest.") from e
RuntimeError: Exception encountered, stopping BackTest.

Creating trades plot...

Creating indicators plot...

Creating tearsheet...
2024-03-04 19:31:31,328: root: ERROR: Not enough data to create a tearsheet, at least 2 days of data are required. Skipping

Backtesting Error

I am getting an error while performing backtesting

Creating tearsheet...
2024-06-27 02:07:09,561: root: ERROR: Not enough data to create a tearsheet, at least 2 days of data are required. Skipping

image

I am passing the same dates as the start and end dates and tried with other date combinations as well but somehow this still is not working

The following is my code for backtesting
image

Any help will be appreciated. Thanks

Changing the symbol does not change the graph output

When I change the input parameters to AMD for example it does find AMD news. However, it does not create a comparison graph with AMD. The comparison graphs only work with SPY.

I changed the code like this:
start_date = datetime(2023,6,30)
end_date = datetime(2024,1,29)
inputParameters = {"symbol":"AMD",
"cash_at_risk":.5}
broker = Alpaca(ALPACA_CREDS)
strategy = MLTrader(name='mlstrat', broker=broker,
parameters=inputParameters)
strategy.backtest(
YahooDataBacktesting,
start_date,
end_date,
parameters=inputParameters
)

And in the class like this:
class MLTrader(Strategy):
def initialize(self, symbol:str="AMD", cash_at_risk:float=.5):
self.symbol = symbol
self.sleeptime = "24H"
self.last_trade = None
self.cash_at_risk = cash_at_risk
self.api = REST(base_url=BASE_URL, key_id=API_KEY, secret_key=API_SECRET)

Error when runing the python script.

Hi,
I ran the script and then get the following error. I follow the suggestion to set the environment variable "export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True" at the terminal session, but it got the same error.


return self.df["dividend"][-1]
Progress |โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ------------------------------------------------| 13.04% [Elapsed: 0:00:21 ETA: 0:02:24] Portfolio Val: 169,231.522024-02-25 19:00:23,447: root: ERROR: CUDA out of memory. Tried to allocate 20.00 MiB. GPU 0 has a total capacity of 3.94 GiB of which 21.06 MiB is free. Including non-PyTorch memory, this process has 3.88 GiB memory in use. Of the allocated memory 3.41 GiB is allocated by PyTorch, and 13.19 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)
2024-02-25 19:00:23,451: root: ERROR: Traceback (most recent call last):
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 856, in run
self._run_trading_session()
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 807, in _run_trading_session
self._on_trading_iteration()
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 276, in func_output
result = func_input(self, *args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 300, in func_output
result = func_input(self, *args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 87, in func_output
return func_input(self, *args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 378, in _on_trading_iteration
on_trading_iteration()
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/tools/decorators.py", line 62, in func_output
frame, result = call_function_get_frame(func_input, *args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/tools/decorators.py", line 30, in call_function_get_frame
result = func(*args, **kwargs)
File "/home/kenlao/python/Code Trading/tradingbot.py", line 50, in on_trading_iteration
probability, sentiment = self.get_sentiment()
File "/home/kenlao/python/Code Trading/tradingbot.py", line 45, in get_sentiment
probability, sentiment = estimate_sentiment(news)
File "/home/kenlao/python/Code Trading/finbert_utils.py", line 14, in estimate_sentiment
result = model(tokens["input_ids"], attention_mask=tokens["attention_mask"])[
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
return forward_call(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py", line 1564, in forward
outputs = self.bert(
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
return forward_call(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py", line 1013, in forward
encoder_outputs = self.encoder(
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
return forward_call(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py", line 607, in forward
layer_outputs = layer_module(
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
return forward_call(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py", line 497, in forward
self_attention_outputs = self.attention(
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
return forward_call(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py", line 427, in forward
self_outputs = self.self(
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
return forward_call(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py", line 325, in forward
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 20.00 MiB. GPU 0 has a total capacity of 3.94 GiB of which 21.06 MiB is free. Including non-PyTorch memory, this process has 3.88 GiB memory in use. Of the allocated memory 3.41 GiB is allocated by PyTorch, and 13.19 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)

Exception in thread MLTrader:
Traceback (most recent call last):
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 856, in run
self._run_trading_session()
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 807, in _run_trading_session
self._on_trading_iteration()
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 276, in func_output
result = func_input(self, *args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 300, in func_output
result = func_input(self, *args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 87, in func_output
return func_input(self, *args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 378, in _on_trading_iteration
on_trading_iteration()
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/tools/decorators.py", line 62, in func_output
frame, result = call_function_get_frame(func_input, *args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/tools/decorators.py", line 30, in call_function_get_frame
result = func(*args, **kwargs)
File "/home/kenlao/python/Code Trading/tradingbot.py", line 50, in on_trading_iteration
probability, sentiment = self.get_sentiment()
File "/home/kenlao/python/Code Trading/tradingbot.py", line 45, in get_sentiment
probability, sentiment = estimate_sentiment(news)
File "/home/kenlao/python/Code Trading/finbert_utils.py", line 14, in estimate_sentiment
result = model(tokens["input_ids"], attention_mask=tokens["attention_mask"])[
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
return forward_call(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py", line 1564, in forward
outputs = self.bert(
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
return forward_call(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py", line 1013, in forward
encoder_outputs = self.encoder(
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
return forward_call(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py", line 607, in forward
layer_outputs = layer_module(
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
return forward_call(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py", line 497, in forward
self_attention_outputs = self.attention(
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
return forward_call(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py", line 427, in forward
self_outputs = self.self(
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1511, in _wrapped_call_impl
return self._call_impl(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1520, in _call_impl
return forward_call(*args, **kwargs)
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py", line 325, in forward
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 20.00 MiB. GPU 0 has a total capacity of 3.94 GiB of which 21.06 MiB is free. Including non-PyTorch memory, this process has 3.88 GiB memory in use. Of the allocated memory 3.41 GiB is allocated by PyTorch, and 13.19 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://pytorch.org/docs/stable/notes/cuda.html#environment-variables)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/threading.py", line 1016, in _bootstrap_inner
self.run()
File "/home/kenlao/miniconda3/envs/py310/lib/python3.10/site-packages/lumibot/strategies/strategy_executor.py", line 869, in run
raise RuntimeError("Exception encountered, stopping BackTest.") from e
RuntimeError: Exception encountered, stopping BackTest.

Creating trades plot...

Creating indicators plot...

Creating tearsheet...
(py310) (base) kenlao@ken

A couple Mods Not Exactly working that Im able to tell

I am new to this and coding. I made a couple mods to the file so I would like someone to review it and help me where it needs help please and please adapt if you think its a good idea....

your patience is appreciated

Danny

from lumibot.brokers import Alpaca
from lumibot.backtesting import YahooDataBacktesting
from lumibot.strategies.strategy import Strategy
from lumibot.traders import Trader
from datetime import datetime
from alpaca_trade_api import REST
from timedelta import Timedelta
from finbert_utils import estimate_sentiment

import numpy as np #added to get pythons math functions

API_KEY = "YOUR API KEY"
API_SECRET = "YOUR API SECRET"
BASE_URL = "https://paper-api.alpaca.markets"

ALPACA_CREDS = {
"API_KEY":API_KEY,
"API_SECRET": API_SECRET,
"PAPER": True
}

class MLTrader(Strategy):
def initialize(self, symbol:str="SPY", cash_at_risk:float=.5):
self.symbol = symbol
self.sleeptime = "24H"
self.last_trade = None
self.cash_at_risk = cash_at_risk
self.api = REST(base_url=BASE_URL, key_id=API_KEY, secret_key=API_SECRET)

# def position_sizing(self): 
#     cash = self.get_cash() 
#     last_price = self.get_last_price(self.symbol)
#     quantity = round(cash * self.cash_at_risk / last_price,0)
#     return cash, last_price, quantity

def position_sizing(self):
    cash = self.get_cash()
    last_price = self.get_last_price(self.symbol)
    atr = self.calculate_atr(self.symbol)
    take_profit, stop_loss = self.set_take_profit_stop_loss(last_price, atr)
    quantity = round(cash * self.cash_at_risk / last_price, 0)
    return cash, last_price, quantity, take_profit, stop_loss

def calculate_atr(self, symbol, period=14):
    # Fetch historical data for ATR calculation, implement accordingly
    pass

def set_take_profit_stop_loss(self, last_price, atr, multiplier=2):
    take_profit = last_price + atr * multiplier
    stop_loss = last_price - atr * multiplier
    return take_profit, stop_loss


def get_dates(self): 
    today = self.get_datetime()
    three_days_prior = today - Timedelta(days=3)
    return today.strftime('%Y-%m-%d'), three_days_prior.strftime('%Y-%m-%d')

def get_sentiment(self): 
    today, three_days_prior = self.get_dates()
    news = self.api.get_news(symbol=self.symbol, 
                             start=three_days_prior, 
                             end=today) 
    news = [ev.__dict__["_raw"]["headline"] for ev in news]
    probability, sentiment = estimate_sentiment(news)
    return probability, sentiment 

def on_trading_iteration(self):
    cash, last_price, quantity = self.position_sizing() 
    probability, sentiment = self.get_sentiment()

    # if cash > last_price: 
    #     if sentiment == "positive" and probability > .999: 
    #         if self.last_trade == "sell": 
    #             self.sell_all() 
    #         order = self.create_order(
    #             self.symbol, 
    #             quantity, 
    #             "buy", 
    #             type="bracket", 
    #             take_profit_price=last_price*1.20, 
    #             stop_loss_price=last_price*.95
    #         )
    #         self.submit_order(order) 
    #         self.last_trade = "buy"
    #     elif sentiment == "negative" and probability > .999: 
    #         if self.last_trade == "buy": 
    #             self.sell_all() 
    #         order = self.create_order(
    #             self.symbol, 
    #             quantity, 
    #             "sell", 
    #             type="bracket", 
    #             take_profit_price=last_price*.8, 
    #             stop_loss_price=last_price*1.05
    #         )
    #         self.submit_order(order) 
    #         self.last_trade = "sell"


    if cash > last_price:
        if sentiment == "positive" and probability > .999:
            if self.last_trade == "sell":
                self.sell_all()
            order = self.create_order(
                self.symbol,
                quantity,
                "buy",
                type="bracket",
                take_profit_price=take_profit,
                stop_loss_price=stop_loss
            )
            self.submit_order(order)
            self.last_trade = "buy"
        elif sentiment == "negative" and probability > .999:
            if self.last_trade == "buy":
                self.sell_all()
            order = self.create_order(
                self.symbol,
                quantity,
                "sell",
                type="bracket",
                take_profit_price=take_profit,
                stop_loss_price=stop_loss
            )
            self.submit_order(order)
            self.last_trade = "sell"

start_date = datetime(2020,1,1)
end_date = datetime(2023,12,31)
broker = Alpaca(ALPACA_CREDS)
strategy = MLTrader(name='mlstrat', broker=broker,
parameters={"symbol":"SPY",
"cash_at_risk":.5})
strategy.backtest(
YahooDataBacktesting,
start_date,
end_date,
parameters={"symbol":"SPY", "cash_at_risk":.5}
)

trader = Trader()

trader.add_strategy(strategy)

trader.run_all()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.