Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added flake8-simplify #4227

Merged
merged 9 commits into from
Feb 21, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/linting.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ jobs:
restore-keys: ${{ runner.os }}-linting-${{ hashFiles('**/poetry.lock') }}

- run: |
pip install bandit black codespell mypy==0.982 safety pylint==2.15.2 packaging==22 ruff==0.0.243
pip install bandit black codespell mypy==0.982 pylint==2.15.2 ruff==0.0.246
pip install types-pytz types-requests types-termcolor types-tabulate types-PyYAML types-python-dateutil types-setuptools types-six
- run: bandit -x ./tests -r . || true
- run: black --diff --check .
Expand Down
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ repos:
hooks:
- id: black
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: 'v0.0.243'
rev: 'v0.0.246'
hooks:
- id: ruff
- repo: https://github.com/codespell-project/codespell
Expand Down
10 changes: 2 additions & 8 deletions custom_pre_commit/check_doc.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,8 @@ def main(ignore_files: Optional[str], ignore_commands: Optional[str]):
Commands that should not be checked
"""

if ignore_files:
ignore_file_list = ignore_files.split(",")
else:
ignore_file_list = []
if ignore_commands:
ignore_cmds_list = ignore_commands.split(",")
else:
ignore_cmds_list = []
ignore_file_list = ignore_files.split(",") if ignore_files else []
ignore_cmds_list = ignore_commands.split(",") if ignore_commands else []
path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
gst_path = os.path.join(path, "openbb_terminal/")
main_yaml_filename = os.path.join(path, "website/data/menu/main.yml")
Expand Down
7 changes: 2 additions & 5 deletions generate_sdk.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,7 @@ def get_subcat_fullname(self, cat: str) -> str:

def check_submodules(self, category: str) -> bool:
"""Checks if a category has submodules."""
for d in self.categories[category].values():
if isinstance(d, dict):
return True
return False
return any(isinstance(d, dict) for d in self.categories[category].values())

def write_init_imports(self, importstr: str, filestr: str) -> None:
"""Checks if a category has submodules and adds the imports to the init file."""
Expand Down Expand Up @@ -172,7 +169,7 @@ def write_class_property(
subcat : Optional[str], optional
The subcategory name, by default None
"""
def_name = category if not subcat else subcat
def_name = subcat if subcat else category
if subcat:
subcat = f" {self.get_subcat_fullname(subcat)}"

Expand Down
25 changes: 12 additions & 13 deletions openbb_terminal/account/account_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,16 +143,12 @@ def call_sync(self, other_args: List[str]):
FeatureFlagsController.set_feature_flag(
"OPENBB_SYNC_ENABLED", True, force=True
)
elif ns_parser.off:
if obbff.SYNC_ENABLED:
FeatureFlagsController.set_feature_flag(
"OPENBB_SYNC_ENABLED", False, force=True
)
elif ns_parser.off and obbff.SYNC_ENABLED:
FeatureFlagsController.set_feature_flag(
"OPENBB_SYNC_ENABLED", False, force=True
)

if obbff.SYNC_ENABLED:
sync = "ON"
else:
sync = "OFF"
sync = "ON" if obbff.SYNC_ENABLED else "OFF"

if ns_parser.on or ns_parser.off:
console.print(f"[info]sync:[/info] {sync}")
Expand Down Expand Up @@ -420,9 +416,12 @@ def call_delete(self, other_args: List[str]):
auth_header=User.get_auth_header(),
name=name,
)
if response and response.status_code == 200:
if name in self.REMOTE_CHOICES:
self.REMOTE_CHOICES.remove(name)
self.update_runtime_choices()
if (
response
and response.status_code == 200
and name in self.REMOTE_CHOICES
):
self.REMOTE_CHOICES.remove(name)
self.update_runtime_choices()
else:
console.print("[info]Aborted.[/info]")
4 changes: 1 addition & 3 deletions openbb_terminal/alternative/oss/github_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,7 @@ def get_stars_history(repo: str) -> pd.DataFrame:
stars[sorted_keys[i]] += stars[sorted_keys[i - 1]]
df = pd.DataFrame(
{
"Date": [
datetime.strptime(date, "%Y-%m-%d").date() for date in stars.keys()
],
"Date": [datetime.strptime(date, "%Y-%m-%d").date() for date in stars],
"Stars": stars.values(),
}
)
Expand Down
26 changes: 12 additions & 14 deletions openbb_terminal/alternative/oss/oss_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,10 @@ def call_sh(self, other_args: List[str]):
export_allowed=EXPORT_BOTH_RAW_DATA_AND_FIGURES,
raw=True,
)
if ns_parser:
if valid_repo(ns_parser.repo):
github_view.display_star_history(
repo=ns_parser.repo, export=ns_parser.export
)
if ns_parser and valid_repo(ns_parser.repo):
github_view.display_star_history(
repo=ns_parser.repo, export=ns_parser.export
)

@log_start_end(log=logger)
def call_rs(self, other_args: List[str]):
Expand All @@ -116,15 +115,14 @@ def call_rs(self, other_args: List[str]):
ns_parser = self.parse_known_args_and_warn(
parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED, raw=True
)
if ns_parser:
if valid_repo(ns_parser.repo):
github_view.display_repo_summary(
repo=ns_parser.repo,
export=ns_parser.export,
sheet_name=" ".join(ns_parser.sheet_name)
if ns_parser.sheet_name
else None,
)
if ns_parser and valid_repo(ns_parser.repo):
github_view.display_repo_summary(
repo=ns_parser.repo,
export=ns_parser.export,
sheet_name=" ".join(ns_parser.sheet_name)
if ns_parser.sheet_name
else None,
)

@log_start_end(log=logger)
def call_rossidx(self, other_args: List[str]):
Expand Down
117 changes: 59 additions & 58 deletions openbb_terminal/common/behavioural_analysis/reddit_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,10 +170,11 @@ def get_popular_tickers(
pd.DataFrame
DataFrame of top tickers from supplied subreddits
"""
if subreddits:
sub_reddit_list = subreddits.split(",") if "," in subreddits else [subreddits]
else:
sub_reddit_list = l_sub_reddits
sub_reddit_list = (
(subreddits.split(",") if "," in subreddits else [subreddits])
if subreddits
else l_sub_reddits
)
d_watchlist_tickers: dict = {}
l_watchlist_author = []

Expand Down Expand Up @@ -223,31 +224,31 @@ def get_popular_tickers(
# Get more information about post using PRAW api
submission = praw_api.submission(id=submission.id)

if submission is not None:
# Ensure that the post hasn't been removed by moderator in the meanwhile,
# that there is a description and it's not just an image, that the flair is
# meaningful, and that we aren't re-considering same author's content
if (
not submission.removed_by_category
and (submission.selftext or submission.title)
and submission.author.name not in l_watchlist_author
):
l_tickers_found = find_tickers(submission)

if l_tickers_found:
n_tickers += len(l_tickers_found)

# Add another author's name to the parsed watchlists
l_watchlist_author.append(submission.author.name)

# Lookup stock tickers within a watchlist
for key in l_tickers_found:
if key in d_watchlist_tickers:
# Increment stock ticker found
d_watchlist_tickers[key] += 1
else:
# Initialize stock ticker found
d_watchlist_tickers[key] = 1
# Ensure that the post hasn't been removed by moderator in the meanwhile,
# that there is a description and it's not just an image, that the flair is
# meaningful, and that we aren't re-considering same author's content
if (
submission is not None
and not submission.removed_by_category
and (submission.selftext or submission.title)
and submission.author.name not in l_watchlist_author
):
l_tickers_found = find_tickers(submission)

if l_tickers_found:
n_tickers += len(l_tickers_found)

# Add another author's name to the parsed watchlists
l_watchlist_author.append(submission.author.name)

# Lookup stock tickers within a watchlist
for key in l_tickers_found:
if key in d_watchlist_tickers:
# Increment stock ticker found
d_watchlist_tickers[key] += 1
else:
# Initialize stock ticker found
d_watchlist_tickers[key] = 1

except ResponseException as e:
logger.exception("Invalid response: %s", str(e))
Expand Down Expand Up @@ -812,37 +813,37 @@ def get_due_dilligence(
submission = praw_api.submission(id=submission.id)

# Ensure that the post hasn't been removed in the meanwhile
if not submission.removed_by_category:
# Either just filter out Yolo, and Meme flairs, or focus on DD, based on b_DD flag
if (
submission.link_flair_text in l_flair_text,
submission.link_flair_text not in ["Yolo", "Meme"],
)[show_all_flairs]:
s_datetime = datetime.utcfromtimestamp(
submission.created_utc
).strftime("%Y-%m-%d %H:%M:%S")
s_link = f"https://old.reddit.com{submission.permalink}"
s_all_awards = "".join(
f"{award['count']} {award['name']}\n"
for award in submission.all_awardings
)
# Either just filter out Yolo, and Meme flairs, or focus on DD, based on b_DD flag
if (
not submission.removed_by_category
and submission.link_flair_text in l_flair_text,
submission.link_flair_text not in ["Yolo", "Meme"],
)[show_all_flairs]:
s_datetime = datetime.utcfromtimestamp(submission.created_utc).strftime(
"%Y-%m-%d %H:%M:%S"
)
s_link = f"https://old.reddit.com{submission.permalink}"
s_all_awards = "".join(
f"{award['count']} {award['name']}\n"
for award in submission.all_awardings
)

s_all_awards = s_all_awards[:-2]
s_all_awards = s_all_awards[:-2]

data = [
s_datetime,
submission.subreddit,
submission.link_flair_text,
submission.title,
submission.score,
submission.num_comments,
f"{round(100 * submission.upvote_ratio)}%",
s_all_awards,
s_link,
]
subs.loc[len(subs)] = data
# Increment count of valid posts found
n_flair_posts_found += 1
data = [
s_datetime,
submission.subreddit,
submission.link_flair_text,
submission.title,
submission.score,
submission.num_comments,
f"{round(100 * submission.upvote_ratio)}%",
s_all_awards,
s_link,
]
subs.loc[len(subs)] = data
# Increment count of valid posts found
n_flair_posts_found += 1

# Check if number of wanted posts found has been reached
if n_flair_posts_found > limit - 1:
Expand Down
5 changes: 1 addition & 4 deletions openbb_terminal/common/common_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,7 @@ def load(
return wage_panel.load()
return getattr(sm.datasets, file).load_pandas().data

if file in data_files:
full_file = data_files[file]
else:
full_file = file
full_file = data_files[file] if file in data_files else file

if not Path(full_file).exists():
console.print(f"[red]Cannot find the file {full_file}[/red]\n")
Expand Down
10 changes: 5 additions & 5 deletions openbb_terminal/common/newsapi_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,11 @@ def get_news(
f" {query} were found since {start_date}\n",
)

if show_newest:
articles = response_json["articles"]

else:
articles = response_json["articles"][::-1]
articles = (
response_json["articles"]
if show_newest
else response_json["articles"][::-1]
)

elif response.status_code == 426:
console.print(f"Error in request: {response.json()['message']}", "\n")
Expand Down
19 changes: 7 additions & 12 deletions openbb_terminal/common/quantitative_analysis/qa_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,10 +269,7 @@ def get_var(
percentile_custom = stats.norm.ppf(1 - percentile)

# Mean
if use_mean:
mean = data_return.mean()
else:
mean = 0
mean = data_return.mean() if use_mean else 0

# Standard Deviation
std = data_return.std(axis=0)
Expand Down Expand Up @@ -396,10 +393,7 @@ def get_es(
percentile_custom = stats.norm.ppf(1 - percentile)

# Mean
if use_mean:
mean = data_return.mean()
else:
mean = 0
mean = data_return.mean() if use_mean else 0

# Standard Deviation
std = data_return.std(axis=0)
Expand All @@ -418,10 +412,11 @@ def get_es(
es_95 = -b * (1 - np.log(2 * 0.05)) + mean
es_99 = -b * (1 - np.log(2 * 0.01)) + mean

if (1 - percentile) < 0.5:
es_custom = -b * (1 - np.log(2 * (1 - percentile))) + mean
else:
es_custom = 0
es_custom = (
-b * (1 - np.log(2 * (1 - percentile))) + mean
if 1 - percentile < 0.5
else 0
)

elif distribution == "student_t":
# Calculating ES based on the Student-t distribution
Expand Down
15 changes: 3 additions & 12 deletions openbb_terminal/common/quantitative_analysis/qa_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,10 +316,7 @@ def display_bw(

theme.style_primary_axis(ax)
color = theme.get_colors()[0]
if yearly:
x_data = data.index.year
else:
x_data = data.index.month
x_data = data.index.year if yearly else data.index.month
box_plot = sns.boxplot(
x=x_data,
y=data,
Expand Down Expand Up @@ -913,10 +910,7 @@ def display_raw(
Export data as CSV, JSON, XLSX
"""

if isinstance(data, pd.Series):
df1 = pd.DataFrame(data)
else:
df1 = data.copy()
df1 = pd.DataFrame(data) if isinstance(data, pd.Series) else data.copy()

if sortby:
try:
Expand Down Expand Up @@ -1213,10 +1207,7 @@ def display_sortino(
adjust the sortino ratio
"""
sortino_ratio = qa_model.get_sortino(data, target_return, window, adjusted)
if adjusted:
str_adjusted = "Adjusted "
else:
str_adjusted = ""
str_adjusted = "Adjusted " if adjusted else ""

fig, ax = plt.subplots()
ax.plot(sortino_ratio[int(window - 1) :])
Expand Down
Loading