Skip to content

Commit 67f0eed

Browse files
committed
fix: resolve all 39 ruff linting errors
1 parent 096b505 commit 67f0eed

134 files changed

Lines changed: 3185 additions & 2778 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

backtrader/analyzer.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
from collections import OrderedDict
3636

3737
from .dataseries import TimeFrame
38-
from .metabase import findowner, OwnerContext
38+
from .metabase import findowner
3939
from .observer import Observer
4040
from .parameters import ParameterizedBase
4141
from .strategy import Strategy
@@ -108,12 +108,12 @@ class Analyzer(ParameterizedBase):
108108
def __init__(self, *args, **kwargs):
109109
"""
110110
Initialize Analyzer with basic functionality.
111-
111+
112112
Note: __new__ removed - _children initialization moved here.
113113
"""
114114
# Initialize children list (moved from __new__)
115115
self._children = list()
116-
116+
117117
# Initialize parent first
118118
super().__init__(*args, **kwargs)
119119

@@ -572,7 +572,8 @@ def _get_subday_cmpkey(self, dt):
572572
tadjust = datetime.timedelta(
573573
minutes=self.timeframe == TimeFrame.Minutes,
574574
seconds=self.timeframe == TimeFrame.Seconds,
575-
microseconds=self.timeframe == TimeFrame.MicroSeconds)
575+
microseconds=self.timeframe == TimeFrame.MicroSeconds,
576+
)
576577

577578
# Add extra day if present
578579
# If next day is True, adjust time to next day

backtrader/analyzers/logreturnsrolling.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -118,9 +118,7 @@ def start(self):
118118
self._fundmode = self.p.fund
119119
# The special part is that self._values is set as a queue, where self.compression parameter controls how many elements the queue saves
120120
# Note: use self.compression (set in _start from data) not self.p.compression (which may be None)
121-
self._values = collections.deque(
122-
[float("Nan")] * self.compression, maxlen=self.compression
123-
)
121+
self._values = collections.deque([float("Nan")] * self.compression, maxlen=self.compression)
124122

125123
if self.p.data is None:
126124
# keep the initial portfolio value if not tracing data

backtrader/analyzers/sharpe_ratio_stats.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
min_track_record_length: Minimum track record for significance.
1313
sharpe_ratio_defacto: Defacto Sharpe ratio calculation.
1414
"""
15+
1516
import numpy as np
1617
import pandas as pd
1718
from scipy import stats as scipy_stats

backtrader/analyzers/total_value.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
>>> results = cerebro.run()
1313
>>> print(results[0].analyzers.val.get_analysis())
1414
"""
15+
1516
from collections import OrderedDict
1617

1718
from ..analyzer import Analyzer

backtrader/bokeh/__init__.py

Lines changed: 32 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8; py-indent-offset:4 -*-
32
"""
43
Backtrader Bokeh Module
54
@@ -13,22 +12,22 @@
1312
Example:
1413
import backtrader as bt
1514
from backtrader.bokeh import LivePlotAnalyzer, Blackly
16-
15+
1716
cerebro = bt.Cerebro()
1817
cerebro.adddata(data)
1918
cerebro.addstrategy(MyStrategy)
20-
19+
2120
# Add live plot analyzer
2221
cerebro.addanalyzer(LivePlotAnalyzer,
2322
scheme=Blackly(),
2423
lookback=100)
25-
24+
2625
cerebro.run()
2726
"""
2827

29-
from .schemes import Scheme, Blackly, Tradimo
30-
from .tab import BokehTab
3128
from . import tabs
29+
from .schemes import Blackly, Scheme, Tradimo
30+
from .tab import BokehTab
3231
from .utils import get_datanames, get_strategy_label, sanitize_source_name
3332

3433
# Custom tab registry
@@ -37,7 +36,7 @@
3736

3837
def register_tab(tab_class):
3938
"""Register a custom tab.
40-
39+
4140
Args:
4241
tab_class: Tab class that inherits from BokehTab
4342
"""
@@ -54,39 +53,44 @@ def get_registered_tabs():
5453
# Lazy import to avoid circular dependencies
5554
def __getattr__(name):
5655
"""Lazy load module attributes."""
57-
if name == 'BacktraderBokeh':
56+
if name == "BacktraderBokeh":
5857
from .app import BacktraderBokeh
58+
5959
return BacktraderBokeh
60-
elif name == 'LivePlotAnalyzer':
60+
elif name == "LivePlotAnalyzer":
6161
from .analyzers import LivePlotAnalyzer
62+
6263
return LivePlotAnalyzer
63-
elif name == 'RecorderAnalyzer':
64+
elif name == "RecorderAnalyzer":
6465
from .analyzers import RecorderAnalyzer
66+
6567
return RecorderAnalyzer
66-
elif name == 'LiveClient':
68+
elif name == "LiveClient":
6769
from .live import LiveClient
70+
6871
return LiveClient
69-
elif name == 'LiveDataHandler':
72+
elif name == "LiveDataHandler":
7073
from .live import LiveDataHandler
74+
7175
return LiveDataHandler
72-
76+
7377
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
7478

7579

7680
__all__ = [
77-
'BacktraderBokeh',
78-
'Scheme',
79-
'Blackly',
80-
'Tradimo',
81-
'BokehTab',
82-
'LivePlotAnalyzer',
83-
'RecorderAnalyzer',
84-
'LiveClient',
85-
'LiveDataHandler',
86-
'tabs',
87-
'register_tab',
88-
'get_registered_tabs',
89-
'get_datanames',
90-
'get_strategy_label',
91-
'sanitize_source_name',
81+
"BacktraderBokeh",
82+
"Scheme",
83+
"Blackly",
84+
"Tradimo",
85+
"BokehTab",
86+
"LivePlotAnalyzer",
87+
"RecorderAnalyzer",
88+
"LiveClient",
89+
"LiveDataHandler",
90+
"tabs",
91+
"register_tab",
92+
"get_registered_tabs",
93+
"get_datanames",
94+
"get_strategy_label",
95+
"sanitize_source_name",
9296
]

backtrader/bokeh/analyzers/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8; py-indent-offset:4 -*-
32
"""
43
Bokeh analyzers module.
54
@@ -11,4 +10,4 @@
1110
from .plot import LivePlotAnalyzer
1211
from .recorder import RecorderAnalyzer
1312

14-
__all__ = ['LivePlotAnalyzer', 'RecorderAnalyzer']
13+
__all__ = ["LivePlotAnalyzer", "RecorderAnalyzer"]

backtrader/bokeh/analyzers/plot.py

Lines changed: 38 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/env python
2-
# -*- coding: utf-8; py-indent-offset:4 -*-
32
"""
43
Live plotting analyzer.
54
@@ -13,16 +12,17 @@
1312

1413
try:
1514
import tornado.ioloop
15+
1616
TORNADO_AVAILABLE = True
1717
except ImportError:
1818
TORNADO_AVAILABLE = False
1919

2020
import backtrader as bt
2121

2222
from ..app import BacktraderBokeh
23-
from ..webapp import Webapp
24-
from ..schemes import Tradimo, Blackly
2523
from ..live.client import LiveClient
24+
from ..schemes import Tradimo
25+
from ..webapp import Webapp
2626

2727
_logger = logging.getLogger(__name__)
2828

@@ -51,15 +51,15 @@ class LivePlotAnalyzer(bt.Analyzer):
5151
lookback=100,
5252
port=8999)
5353
"""
54-
54+
5555
params = (
56-
('scheme', None), # Theme
57-
('style', 'bar'), # Chart style
58-
('lookback', 100), # Historical data retention
59-
('address', 'localhost'), # Server address
60-
('port', 8999), # Server port
61-
('title', None), # Title
62-
('autostart', True), # Auto-start
56+
("scheme", None), # Theme
57+
("style", "bar"), # Chart style
58+
("lookback", 100), # Historical data retention
59+
("address", "localhost"), # Server address
60+
("port", 8999), # Server port
61+
("title", None), # Title
62+
("autostart", True), # Auto-start
6363
)
6464

6565
def __init__(self, **kwargs):
@@ -76,48 +76,46 @@ def __init__(self, **kwargs):
7676
- autostart: Whether to auto-start server (default: True)
7777
"""
7878
super().__init__()
79-
79+
8080
# Set title
8181
title = self.p.title
8282
if title is None:
83-
title = f'Live {type(self.strategy).__name__}'
84-
83+
title = f"Live {type(self.strategy).__name__}"
84+
8585
# Set auto-start
86-
autostart = kwargs.get('autostart', self.p.autostart)
87-
86+
autostart = kwargs.get("autostart", self.p.autostart)
87+
8888
# Get theme
8989
scheme = self.p.scheme
9090
if scheme is None:
9191
scheme = Tradimo()
92-
92+
9393
# Create Webapp
9494
self._webapp = Webapp(
9595
title=title,
96-
template='basic.html.j2',
96+
template="basic.html.j2",
9797
scheme=scheme,
9898
on_root_model=self._app_cb_build_root_model,
9999
on_session_destroyed=self._on_session_destroyed,
100100
autostart=autostart,
101101
address=self.p.address,
102-
port=self.p.port
102+
port=self.p.port,
103103
)
104-
104+
105105
self._lock = Lock()
106106
self._clients = {}
107107
self._app_kwargs = kwargs
108-
108+
109109
def _create_app(self):
110110
"""Create BacktraderBokeh application instance.
111111
112112
Returns:
113113
BacktraderBokeh instance
114114
"""
115115
return BacktraderBokeh(
116-
style=self.p.style,
117-
scheme=self.p.scheme or Tradimo(),
118-
**self._app_kwargs
116+
style=self.p.style, scheme=self.p.scheme or Tradimo(), **self._app_kwargs
119117
)
120-
118+
121119
def _on_session_destroyed(self, session_context):
122120
"""Session destroyed callback.
123121
@@ -129,17 +127,17 @@ def _on_session_destroyed(self, session_context):
129127
if session_id in self._clients:
130128
self._clients[session_id].stop()
131129
del self._clients[session_id]
132-
130+
133131
def _t_server(self):
134132
"""Server thread method."""
135133
if not TORNADO_AVAILABLE:
136-
_logger.error('Tornado is not available. Cannot start Bokeh server.')
134+
_logger.error("Tornado is not available. Cannot start Bokeh server.")
137135
return
138-
136+
139137
asyncio.set_event_loop(asyncio.new_event_loop())
140138
loop = tornado.ioloop.IOLoop.current()
141139
self._webapp.start(loop)
142-
140+
143141
def _app_cb_build_root_model(self, doc):
144142
"""Build root model callback.
145143
@@ -149,37 +147,32 @@ def _app_cb_build_root_model(self, doc):
149147
Returns:
150148
Root model
151149
"""
152-
client = LiveClient(
153-
doc,
154-
self._create_app(),
155-
self.strategy,
156-
self.p.lookback
157-
)
158-
150+
client = LiveClient(doc, self._create_app(), self.strategy, self.p.lookback)
151+
159152
with self._lock:
160153
self._clients[doc.session_context.id] = client
161-
154+
162155
return client.model
163-
156+
164157
def start(self):
165158
"""Start from backtrader.
166159
167160
Starts the Bokeh Server.
168161
"""
169-
_logger.debug('Starting LivePlotAnalyzer...')
170-
162+
_logger.debug("Starting LivePlotAnalyzer...")
163+
171164
t = threading.Thread(target=self._t_server)
172165
t.daemon = True
173166
t.start()
174-
167+
175168
def stop(self):
176169
"""Stop from backtrader."""
177-
_logger.debug('Stopping LivePlotAnalyzer...')
178-
170+
_logger.debug("Stopping LivePlotAnalyzer...")
171+
179172
with self._lock:
180173
for client in self._clients.values():
181174
client.stop()
182-
175+
183176
def next(self):
184177
"""Receive new data from backtrader.
185178
@@ -188,7 +181,7 @@ def next(self):
188181
with self._lock:
189182
for client in self._clients.values():
190183
client.next()
191-
184+
192185
def get_analysis(self):
193186
"""Return analysis results.
194187

0 commit comments

Comments
 (0)