Skip to content

Commit

Permalink
refactor: convert for loops into list and dict comprehensions (OpenBB…
Browse files Browse the repository at this point in the history
  • Loading branch information
Uzaaft authored Sep 23, 2022
1 parent 593bcf8 commit 35b21ce
Show file tree
Hide file tree
Showing 28 changed files with 186 additions and 227 deletions.
6 changes: 1 addition & 5 deletions custom_pre_commit/check_doc.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,7 @@ def main(ignore_files: Optional[str], ignore_commands: Optional[str]):
with open(main_yaml_filename) as yaml:
lines = yaml.read()

undocumented = []
for command in clean_commands:
if command not in lines:
undocumented.append(command)

undocumented = [command for command in clean_commands if command not in lines]
if not undocumented:
sys.exit(0)
else:
Expand Down
4 changes: 1 addition & 3 deletions custom_pre_commit/check_reserved_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ def process_file(file_path: str, exp: str):

# pylint:disable=anomalous-backslash-in-string
def main():
expressions = []
for sa in RESERVED_ARGS:
expressions.append(rf'("-{sa}(.|\n)*?\--.*?\S*)') # noqa: W605
expressions = [f'("-{sa}(.|\n)*?\\--.*?\\S*)' for sa in RESERVED_ARGS]
exp = f"""({"|".join(expressions)})"""

base = os.path.abspath(os.path.dirname(__file__))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,10 @@ def get_trending() -> pd.DataFrame:
"""
result = requests.get("https://api.stocktwits.com/api/2/trending/symbols.json")
if result.status_code == 200:
l_symbols = []
for symbol in result.json()["symbols"]:
l_symbols.append(
[symbol["symbol"], symbol["watchlist_count"], symbol["title"]]
)
l_symbols = [
[symbol["symbol"], symbol["watchlist_count"], symbol["title"]]
for symbol in result.json()["symbols"]
]

df_trending = pd.DataFrame(
l_symbols, columns=["Ticker", "Watchlist Count", "Name"]
Expand Down
5 changes: 1 addition & 4 deletions openbb_terminal/common/quantitative_analysis/qa_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -635,10 +635,7 @@ def get_omega(
threshold = np.linspace(threshold_start, threshold_end, 50)
df = pd.DataFrame(threshold, columns=["threshold"])

omega_list = []
for i in threshold:
omega_list.append(get_omega_ratio(data, i))

omega_list = [get_omega_ratio(data, i) for i in threshold]
df["omega"] = omega_list

return df
1 change: 0 additions & 1 deletion openbb_terminal/common/quantitative_analysis/qa_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -1175,7 +1175,6 @@ def display_omega(
threshold_end: float
annualized target return threshold end of plotted threshold range
"""

df = qa_model.get_omega(data, threshold_start, threshold_end)

# Plotting
Expand Down
33 changes: 16 additions & 17 deletions openbb_terminal/cryptocurrency/defi/terramoney_fcd_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,23 +162,22 @@ def get_validators(sortby: str = "votingPower", ascend: bool = True) -> pd.DataF
"""

response = _make_request("staking")["validators"]
results = []
for validator in response:
results.append(
{
"accountAddress": validator["accountAddress"],
"validatorName": validator["description"].get("moniker"),
"tokensAmount": denominate_number(validator["tokens"]),
"votingPower": round(
(float(validator["votingPower"].get("weight")) * 100), 2
),
"commissionRate": round(
(float(validator["commissionInfo"].get("rate", 0)) * 100), 2
),
"status": validator["status"],
"uptime": round((float(validator.get("upTime", 0)) * 100), 2),
}
)
results = [
{
"accountAddress": validator["accountAddress"],
"validatorName": validator["description"].get("moniker"),
"tokensAmount": denominate_number(validator["tokens"]),
"votingPower": round(
(float(validator["votingPower"].get("weight")) * 100), 2
),
"commissionRate": round(
(float(validator["commissionInfo"].get("rate", 0)) * 100), 2
),
"status": validator["status"],
"uptime": round((float(validator.get("upTime", 0)) * 100), 2),
}
for validator in response
]

df = pd.DataFrame(results)
if not df.empty:
Expand Down
62 changes: 31 additions & 31 deletions openbb_terminal/cryptocurrency/discovery/dappradar_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,16 +135,16 @@ def get_top_dexes(sortby: str = "", limit: int = 10) -> pd.DataFrame:
"oaGJtZGxjeVp6YjNKMFBYUnZkR0ZzVm05c2RXMWxTVzVHYVdGMEptOXlaR1Z5UFdSbGMyTW1iR2x0YVhROU1qWT0="
)
if data:
arr = []
for dex in data["dapps"]:
arr.append(
[
dex["name"],
dex["category"],
dex["statistic"]["userActivity"],
dex["statistic"]["totalVolumeInFiat"],
]
)
arr = [
[
dex["name"],
dex["category"],
dex["statistic"]["userActivity"],
dex["statistic"]["totalVolumeInFiat"],
]
for dex in data["dapps"]
]

df = pd.DataFrame(arr, columns=DEX_COLUMNS)
if sortby in DEX_COLUMNS:
df = df.sort_values(by=sortby, ascending=False)
Expand Down Expand Up @@ -177,16 +177,16 @@ def get_top_games(sortby: str = "", limit: int = 10) -> pd.DataFrame:
"oYldWekpuTnZjblE5ZFhObGNpWnZjbVJsY2oxa1pYTmpKbXhwYldsMFBUSTI="
)
if data:
arr = []
for dex in data["dapps"]:
arr.append(
[
dex["name"],
dex["category"],
dex["statistic"]["userActivity"],
dex["statistic"]["totalVolumeInFiat"],
]
)
arr = [
[
dex["name"],
dex["category"],
dex["statistic"]["userActivity"],
dex["statistic"]["totalVolumeInFiat"],
]
for dex in data["dapps"]
]

df = pd.DataFrame(
arr,
columns=DEX_COLUMNS,
Expand Down Expand Up @@ -220,17 +220,17 @@ def get_top_dapps(sortby: str = "", limit: int = 10) -> pd.DataFrame:
"2Y21SbGNqMWtaWE5qSm14cGJXbDBQVEky"
)
if data:
arr = []
for dex in data["dapps"]:
arr.append(
[
dex["name"],
dex["category"],
dex["activeProtocols"],
dex["statistic"]["userActivity"],
dex["statistic"]["totalVolumeInFiat"],
]
)
arr = [
[
dex["name"],
dex["category"],
dex["activeProtocols"],
dex["statistic"]["userActivity"],
dex["statistic"]["totalVolumeInFiat"],
]
for dex in data["dapps"]
]

df = pd.DataFrame(
arr,
columns=DAPPS_COLUMNS,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -432,10 +432,7 @@ def basic_coin_info(symbol: str = "btc-bitcoin") -> pd.DataFrame:
"proof_type",
"contract",
]
results = {}
for key in keys:
results[key] = coin.get(key)

results = {key: coin.get(key) for key in keys}
try:
tags = ", ".join(t.get("name") for t in tags)
parent = coin.get("parent") or {}
Expand Down
14 changes: 3 additions & 11 deletions openbb_terminal/cryptocurrency/due_diligence/pycoingecko_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -599,9 +599,7 @@ def get_market_data(self) -> pd.DataFrame:
"price_change_percentage_1y",
"market_cap_change_24h",
]
single_stats = {}
for col in market_single_columns:
single_stats[col] = market_data.get(col)
single_stats = {col: market_data.get(col) for col in market_single_columns}
single_stats.update(denominated_data)

if (
Expand Down Expand Up @@ -644,10 +642,7 @@ def get_all_time_high(self, currency: str = "usd") -> pd.DataFrame:
"ath_change_percentage",
]

results = {}
for column in ath_columns:
results[column] = market_data[column].get(currency)

results = {column: market_data[column].get(currency) for column in ath_columns}
df = pd.Series(results).to_frame().reset_index()
df.columns = ["Metric", "Value"]
df["Metric"] = df["Metric"].apply(
Expand Down Expand Up @@ -680,10 +675,7 @@ def get_all_time_low(self, currency: str = "usd") -> pd.DataFrame:
"atl_date",
"atl_change_percentage",
]
results = {}
for column in ath_columns:
results[column] = market_data[column].get(currency)

results = {column: market_data[column].get(currency) for column in ath_columns}
df = pd.Series(results).to_frame().reset_index()
df.columns = ["Metric", "Value"]
df["Metric"] = df["Metric"].apply(
Expand Down
5 changes: 0 additions & 5 deletions openbb_terminal/econometrics/econometrics_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,11 +367,6 @@ def display_cointegration_test(
External axes to plot on
"""

if isinstance(datasets, pd.DataFrame):
new_datasets = {}
for column in datasets.columns:
new_datasets[column] = datasets[column]

pairs = list(combinations(datasets.keys(), 2))
result: Dict[str, list] = {}
z_values: Dict[str, pd.Series] = {}
Expand Down
10 changes: 6 additions & 4 deletions openbb_terminal/economy/nasdaq_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ def check_country_code_type(list_of_codes: str) -> List[str]:
"Code"
]
)
valid_codes = []
for code in list_of_codes.split(","):
if code.upper() in nasdaq_codes:
valid_codes.append(code.upper())
valid_codes = [
code.upper()
for code in list_of_codes.split(",")
if code.upper() in nasdaq_codes
]

if valid_codes:
return valid_codes
raise argparse.ArgumentTypeError("No valid codes provided.")
Expand Down
9 changes: 5 additions & 4 deletions openbb_terminal/etf/etf_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,10 +277,11 @@ def call_load(self, other_args: List[str]):
self.etf_holdings = holdings.index[: ns_parser.limit].tolist()

if "n/a" in self.etf_holdings:
na_tix_idx = []
for idx, item in enumerate(self.etf_holdings):
if item == "n/a":
na_tix_idx.append(str(idx))
na_tix_idx = [
str(idx)
for idx, item in enumerate(self.etf_holdings)
if item == "n/a"
]

console.print(
f"n/a tickers found at position {','.join(na_tix_idx)}. "
Expand Down
5 changes: 1 addition & 4 deletions openbb_terminal/forex/forex_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,10 +238,7 @@ def display_candle(
)
if ma:
# Manually construct the chart legend
colors = []

for i, _ in enumerate(ma):
colors.append(theme.get_colors()[i])
colors = [theme.get_colors()[i] for i, _ in enumerate(ma)]

lines = [Line2D([0], [0], color=c) for c in colors]
labels = ["MA " + str(label) for label in ma]
Expand Down
88 changes: 43 additions & 45 deletions openbb_terminal/forex/oanda/oanda_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,23 +393,21 @@ def open_positions_request(accountID: str = account) -> Union[pd.DataFrame, bool
try:
request = positions.OpenPositions(accountID)
response = client.request(request)
position_data = []
for i in range(len(response["positions"])):
position_data.append(
{
"Instrument": response["positions"][i]["instrument"],
"Long Units": response["positions"][i]["long"]["units"],
"Total Long P/L": response["positions"][i]["long"]["units"],
"Unrealized Long P/L": response["positions"][i]["long"][
"unrealizedPL"
],
"Short Units": response["positions"][i]["short"]["units"],
"Total Short P/L": response["positions"][i]["short"]["pl"],
"Short Unrealized P/L": response["positions"][i]["short"][
"unrealizedPL"
],
}
)
position_data = [
{
"Instrument": response["positions"][i]["instrument"],
"Long Units": response["positions"][i]["long"]["units"],
"Total Long P/L": response["positions"][i]["long"]["units"],
"Unrealized Long P/L": response["positions"][i]["long"]["unrealizedPL"],
"Short Units": response["positions"][i]["short"]["units"],
"Total Short P/L": response["positions"][i]["short"]["pl"],
"Short Unrealized P/L": response["positions"][i]["short"][
"unrealizedPL"
],
}
for i in range(len(response["positions"]))
]

df_positions = pd.DataFrame.from_dict(position_data)
return df_positions
except V20Error as e:
Expand Down Expand Up @@ -443,20 +441,20 @@ def pending_orders_request(accountID: str = account) -> Union[pd.DataFrame, bool
try:
request = orders.OrdersPending(accountID)
response = client.request(request)
pending_data = []
for i in range(len(response["orders"])):
pending_data.append(
{
"Order ID": response["orders"][i]["id"],
"Instrument": response["orders"][i]["instrument"],
"Price": response["orders"][i]["price"],
"Units": response["orders"][i]["units"],
"Time Created": response["orders"][i]["createTime"][:10]
+ " "
+ response["orders"][i]["createTime"][11:19],
"Time In Force": response["orders"][i]["timeInForce"],
}
)
pending_data = [
{
"Order ID": response["orders"][i]["id"],
"Instrument": response["orders"][i]["instrument"],
"Price": response["orders"][i]["price"],
"Units": response["orders"][i]["units"],
"Time Created": response["orders"][i]["createTime"][:10]
+ " "
+ response["orders"][i]["createTime"][11:19],
"Time In Force": response["orders"][i]["timeInForce"],
}
for i in range(len(response["orders"]))
]

if len(pending_data) == 0:
return pd.DataFrame()
df_pending = pd.DataFrame.from_dict(pending_data)
Expand Down Expand Up @@ -615,20 +613,20 @@ def get_candles_dataframe(
try:
request = instruments.InstrumentsCandles(instrument, params=parameters)
response = client.request(request)
candles_data = []
for i in range(len(response["candles"])):
candles_data.append(
{
"Date": response["candles"][i]["time"][:10]
+ " "
+ response["candles"][i]["time"][11:19],
"Open": float(response["candles"][i]["mid"]["o"]),
"High": float(response["candles"][i]["mid"]["h"]),
"Low": float(response["candles"][i]["mid"]["l"]),
"Close": float(response["candles"][i]["mid"]["c"]),
"Volume": response["candles"][i]["volume"],
}
)
candles_data = [
{
"Date": response["candles"][i]["time"][:10]
+ " "
+ response["candles"][i]["time"][11:19],
"Open": float(response["candles"][i]["mid"]["o"]),
"High": float(response["candles"][i]["mid"]["h"]),
"Low": float(response["candles"][i]["mid"]["l"]),
"Close": float(response["candles"][i]["mid"]["c"]),
"Volume": response["candles"][i]["volume"],
}
for i in range(len(response["candles"]))
]

if len(candles_data) == 0:
df_candles = pd.DataFrame()
else:
Expand Down
Loading

0 comments on commit 35b21ce

Please sign in to comment.