Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

в чем ошибка C:\Users\user\PycharmProjects\pythonProject1\venv\Scripts\python.exe…

  1. 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

  2. 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:

    1. Naming Conflict with backtesting.py:

      • You have a local file named backtesting.py in your src directory.
      • In simulation.py, you're trying to import Backtest and Strategy using:
        from backtesting import Backtest, Strategy
        
      • Python looks for a module named backtesting in 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 external backtesting package you might have installed via pip.
      • Your local backtesting.py does not contain Backtest or Strategy classes, leading to the ImportError.
    2. 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()
          
    3. Using backtrader Instead of backtesting:

      • It seems you're using the backtrader library (imported as import backtrader as bt) in your backtesting.py.
      • However, in simulation.py, you're importing Backtest and Strategy from backtesting, which is a different library (backtesting.py package).
      • This inconsistency can lead to confusion and errors.

    Solution:

    • Rename Your Local backtesting.py File:

      • Rename backtesting.py to something else, like backtester.py or my_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.
    • Correct the Typos in Special Methods and Variables:

      • Update the __init__ method in your TestStrategy class:
        def __init__(self):
        
      • Update the conditional statement at the end of your script:
        if __name__ == "__main__":
            run_backtest()
        
    • Ensure Consistent Use of Libraries:

      • Decide whether you're using backtesting or backtrader and stick with one for consistency.
      • If you intend to use backtrader, adjust your imports in simulation.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.

    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 from backtrader:

      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 backtrader or backtesting prevents confusion and potential errors in your code.

    Summary: The error occurs because your local backtesting.py file shadows the external backtesting package 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.