в чем ошибка C:\Users\user\PycharmProjects\pythonProject1\venv\Scripts\python.exe…
- User
в чем ошибка C:\Users\user\PycharmProjects\pythonProject1\venv\Scripts\python.exe C:\Users\user\PycharmProjects\pythonProject1\trading_system\src\main.py Traceback (most recent call last): File "C:\Users\user\PycharmProjects\pythonProject1\trading_system\src\main.py", line 9, in from simulation import run_simulation File "C:\Users\user\PycharmProjects\pythonProject1\trading_system\src\simulation.py", line 4, in from backtesting import Backtest, Strategy ImportError: cannot import name 'Backtest' from 'backtesting' (C:\Users\user\PycharmProjects\pythonProject1\trading_system\src\backtesting.py) # src/backtesting.py
import backtrader as bt import pandas as pd from data_loader import load_data
class TestStrategy(bt.Strategy): params = ( ('rsi_period', 14), ('ma_period', 50), )
def _init_(self): self.rsi = bt.indicators.RSI_Safe(self.data.close, period=self.params.rsi_period) self.ma = bt.indicators.SimpleMovingAverage(self.data.close, period=self.params.ma_period) def next(self): if not self.position: if self.rsi < 30 and self.data.close > self.ma: self.buy() elif self.rsi > 70 or self.data.close < self.ma: self.sell()def run_backtest(): cerebro = bt.Cerebro() cerebro.addstrategy(TestStrategy)
df = load_data() data = bt.feeds.PandasData(dataname=df, fromdate=pd.Timestamp('2020-01-01'), todate=pd.Timestamp('2023-12-31')) cerebro.adddata(data) cerebro.broker.set_cash(100000) cerebro.addsizer(bt.sizers.FixedSize, stake=10) cerebro.broker.setcommission(commission=0.001) print('Начальный капитал: %.2f' % cerebro.broker.getvalue()) cerebro.run() print('Конечный капитал: %.2f' % cerebro.broker.getvalue()) cerebro.plot()if name == "main": run_backtest()
Process finished with exit code 1
- Assistant
The error you're encountering is due to a combination of issues in your code related to naming conflicts and typos. Here's what's happening:
-
Naming Conflict with
backtesting.py:- You have a local file named
backtesting.pyin yoursrcdirectory. - In
simulation.py, you're trying to importBacktestandStrategyusing:from backtesting import Backtest, Strategy - Python looks for a module named
backtestingin the following order:- The current directory.
- The directories listed in
sys.path.
- Since you have a local
backtesting.py, Python imports from it instead of the externalbacktestingpackage you might have installed viapip. - Your local
backtesting.pydoes not containBacktestorStrategyclasses, leading to theImportError.
- You have a local file named
-
Typos in Special Method and Variable Names:
- In Python, special methods and variables use double underscores before and after the name, also known as "dunder" methods.
- In your
backtesting.py:- The
__init__method is incorrectly defined as_init_. It should be:def __init__(self): - The special variable
__name__is incorrectly used as_main_in the conditional statement. It should be:if __name__ == "__main__": run_backtest()
- The
-
Using
backtraderInstead ofbacktesting:- It seems you're using the
backtraderlibrary (imported asimport backtrader as bt) in yourbacktesting.py. - However, in
simulation.py, you're importingBacktestandStrategyfrombacktesting, which is a different library (backtesting.pypackage). - This inconsistency can lead to confusion and errors.
- It seems you're using the
Solution:
-
Rename Your Local
backtesting.pyFile:- Rename
backtesting.pyto something else, likebacktester.pyormy_backtesting.py, to avoid the naming conflict. - This ensures that when you import
backtesting, Python will look for the external package, not your local file.
- Rename
-
Correct the Typos in Special Methods and Variables:
- Update the
__init__method in yourTestStrategyclass:def __init__(self): - Update the conditional statement at the end of your script:
if __name__ == "__main__": run_backtest()
- Update the
-
Ensure Consistent Use of Libraries:
- Decide whether you're using
backtestingorbacktraderand stick with one for consistency. - If you intend to use
backtrader, adjust your imports insimulation.py:from backtrader import Cerebro, Strategy - If you're using
backtesting(the library), make sure it's installed:pip install backtesting - And adjust your code accordingly to use the correct classes and functions from that library.
- Decide whether you're using
Revised
backtester.py:# src/backtester.py import backtrader as bt import pandas as pd from data_loader import load_data class TestStrategy(bt.Strategy): params = ( ('rsi_period', 14), ('ma_period', 50), ) def __init__(self): self.rsi = bt.indicators.RSI_Safe(self.data0.close, period=self.params.rsi_period) self.ma = bt.indicators.SimpleMovingAverage(self.data0.close, period=self.params.ma_period) def next(self): if not self.position: if self.rsi < 30 and self.data0.close > self.ma: self.buy() elif self.rsi > 70 or self.data0.close < self.ma: self.sell() def run_backtest(): cerebro = bt.Cerebro() cerebro.addstrategy(TestStrategy) df = load_data() data = bt.feeds.PandasData( dataname=df, fromdate=pd.Timestamp('2020-01-01'), todate=pd.Timestamp('2023-12-31') ) cerebro.adddata(data) cerebro.broker.set_cash(100000) cerebro.addsizer(bt.sizers.FixedSize, stake=10) cerebro.broker.setcommission(commission=0.001) print('Начальный капитал: %.2f' % cerebro.broker.getvalue()) cerebro.run() print('Конечный капитал: %.2f' % cerebro.broker.getvalue()) cerebro.plot() if __name__ == "__main__": run_backtest()Adjust
simulation.py:-
If you're using
backtrader, import the necessary classes frombacktrader:import backtrader as bt from backtester import run_backtest -
If you're using
backtesting, make sure to correctly import from it after resolving the naming conflict.
Explanation:
- By renaming
backtesting.py, you eliminate the naming conflict that was causing Python to import from the wrong module. - Correcting the special method and variable names fixes the typos that would prevent your class and script from functioning properly.
- Ensuring consistent use of either
backtraderorbacktestingprevents confusion and potential errors in your code.
Summary: The error occurs because your local
backtesting.pyfile shadows the externalbacktestingpackage you intend to import from, and due to typos in your special method names. Renaming the local file and correcting the typos should resolve the issue. -