Enable full mypy (#985)

* Add mypy types to dev requirements

* Add optional discord dependencies and generate requirements.txt for DiscordBot

* Add a full run of MyPy

* Fixing mypy errors and ignoring where unclear to establish a baseline

* Don't run mypy on Windows
This commit is contained in:
Artem Veremey
2021-11-25 08:56:14 -08:00
committed by GitHub
parent 8234ecbe27
commit a1cba7378a
12 changed files with 42 additions and 32 deletions

View File

@@ -252,6 +252,11 @@ jobs:
pip install pylint==2.11.1
pylint terminal.py gamestonk_terminal discordbot tests
- name: Run MyPy (Bash)
if: runner.os != 'Windows'
shell: bash -l {0}
run: mypy --ignore-missing-imports --exclude '/setup\.py$' .
- name: Run tests (Bash)
shell: bash -l {0}
run: pytest tests/

View File

@@ -20,7 +20,7 @@ def get_knn_model_data(
test_size: float,
end_date: str,
no_shuffle: bool,
) -> Tuple[pd.DataFrame, np.array, np.array, np.array, Any]:
) -> Tuple[pd.DataFrame, np.ndarray, np.ndarray, np.ndarray, Any]:
"""Perform knn model fitting and predicting on data
Parameters

View File

@@ -8,13 +8,13 @@ from scipy.stats import norm
def get_mc_brownian(
data: Union[pd.Series, np.array], n_future: int, n_sims: int, use_log=True
) -> np.array:
data: Union[pd.Series, np.ndarray], n_future: int, n_sims: int, use_log=True
) -> np.ndarray:
"""Performs monte carlo forecasting for brownian motion with drift
Parameters
----------
data : Union[pd.Series, np.array]
data : Union[pd.Series, np.ndarray]
Input data.
n_future : int
Number of future steps
@@ -25,10 +25,12 @@ def get_mc_brownian(
Returns
-------
np.array
np.ndarray
Array of predictions. Has shape (n_future, n_sims)
"""
changes = data.pct_change().dropna()
changes = data.pct_change().dropna() # type: ignore
if use_log:
changes = np.log(1 + changes)
@@ -40,8 +42,9 @@ def get_mc_brownian(
random_steps = norm.ppf(np.random.rand(n_future, n_sims))
predicted_change = np.exp(dist_drift + dist_std * random_steps)
possible_paths = np.zeros_like(predicted_change)
possible_paths[0] = data.values[-1]
possible_paths[0] = data.values[-1] # type: ignore
for t in range(1, n_future):
possible_paths[t] = possible_paths[t - 1] * predicted_change[t]
return possible_paths

View File

@@ -21,7 +21,7 @@ from gamestonk_terminal import feature_flags as gtff
def display_mc_forecast(
data: Union[pd.Series, np.array],
data: Union[pd.Series, np.ndarray],
n_future: int,
n_sims: int,
use_log=True,
@@ -43,7 +43,7 @@ def display_mc_forecast(
Format to export data
"""
predicted_values = mc_model.get_mc_brownian(data, n_future, n_sims, use_log)
future_index = get_next_stock_market_days(data.index[-1], n_next_days=n_future)
future_index = get_next_stock_market_days(data.index[-1], n_next_days=n_future) # type: ignore
dateFmt = mdates.DateFormatter("%m/%d/%Y")
fig, ax = plt.subplots(1, 2, figsize=plot_autoscale(), dpi=PLOT_DPI)

View File

@@ -145,7 +145,7 @@ def mlp_model(
test_size: float,
n_loops: int,
no_shuffle: bool,
) -> Tuple[pd.DataFrame, np.array, np.array, np.array, Any]:
) -> Tuple[pd.DataFrame, np.ndarray, np.ndarray, np.ndarray, Any]:
"""Train MLP model on data based on config params
Parameters
@@ -265,7 +265,7 @@ def rnn_model(
test_size: float,
n_loops: int,
no_shuffle: bool,
) -> Tuple[pd.DataFrame, np.array, np.array, np.array, Any]:
) -> Tuple[pd.DataFrame, np.ndarray, np.ndarray, np.ndarray, Any]:
"""Train RNN model on data based on config params
Parameters
@@ -378,7 +378,7 @@ def lstm_model(
test_size: float,
n_loops: int,
no_shuffle: bool,
) -> Tuple[pd.DataFrame, np.array, np.array, np.array, Any]:
) -> Tuple[pd.DataFrame, np.ndarray, np.ndarray, np.ndarray, Any]:
"""Train LSTM model on data based on config params
Parameters
@@ -491,7 +491,7 @@ def conv1d_model(
test_size: float,
n_loops: int,
no_shuffle: bool,
) -> Tuple[pd.DataFrame, np.array, np.array, np.array, Any]:
) -> Tuple[pd.DataFrame, np.ndarray, np.ndarray, np.ndarray, Any]:
"""Train Conv1D model on data based on config params
Parameters

View File

@@ -240,7 +240,7 @@ def prepare_scale_train_valid_test(
X_train: np.ndarray
Array of training data. Shape (# samples, n_inputs, 1)
X_test: np.ndarray
Array of validation data. Shape (totoal sequences - #samples, n_inputs, 1)
Array of validation data. Shape (total sequences - #samples, n_inputs, 1)
y_train: np.ndarray
Array of training outputs. Shape (#samples, n_days)
y_test: np.ndarray
@@ -324,10 +324,10 @@ def prepare_scale_train_valid_test(
dates[idx + n_input_days : idx + n_input_days + n_predict_days]
)
input_dates = np.asarray(input_dates)
input_prices = np.array(input_prices)
next_n_day_prices = np.array(next_n_day_prices)
next_n_day_dates = np.asarray(next_n_day_dates)
input_dates = np.asarray(input_dates) # type: ignore
input_prices = np.array(input_prices) # type: ignore
next_n_day_prices = np.array(next_n_day_prices) # type: ignore
next_n_day_dates = np.asarray(next_n_day_dates) # type: ignore
(
X_train,

View File

@@ -768,7 +768,7 @@ def plot_chart(
print("")
def plot_order_book(bids: np.array, asks: np.array, coin: str) -> None:
def plot_order_book(bids: np.ndarray, asks: np.ndarray, coin: str) -> None:
"""
Plots Bid/Ask. Can be used for Coinbase and Binance

View File

@@ -46,7 +46,7 @@ def get_trading_pair_info(product_id: str) -> pd.DataFrame:
return df
def get_order_book(product_id: str) -> Tuple[np.array, np.array, str, dict]:
def get_order_book(product_id: str) -> Tuple[np.ndarray, np.ndarray, str, dict]:
"""Get orders book for chosen trading pair. [Source: Coinbase]
Parameters

View File

@@ -92,14 +92,15 @@ def get_historical(interval: str = "day", span: str = "3month") -> pd.DataFrame:
close_eq.append(float(h["adjusted_close_equity"]))
open_eq.append(float(h["adjusted_open_equity"]))
close_eq = np.asarray(close_eq)
open_eq = np.asarray(open_eq)
high = np.maximum(open_eq, close_eq)
low = np.minimum(open_eq, close_eq)
close_eq_array = np.asarray(close_eq)
open_eq_array = np.asarray(open_eq)
high = np.maximum(open_eq_array, close_eq_array)
low = np.minimum(open_eq_array, close_eq_array)
df = pd.DataFrame(index=time)
df["High"] = high
df["Low"] = low
df["Open"] = open_eq
df["Close"] = close_eq
df["Open"] = open_eq_array
df["Close"] = close_eq_array
return df

View File

@@ -82,7 +82,7 @@ def get_management(ticker: str) -> pd.DataFrame:
"a", {"onclick": "silentTrackPI()"}
):
for s_name in df_management.index:
if fuzz.token_set_ratio(s_name, insider.text.strip()) > 70:
if fuzz.token_set_ratio(s_name, insider.text.strip()) > 70: # type: ignore
df_management.loc[s_name]["Insider Activity"] = (
s_url_base + insider.attrs["href"]
)

View File

@@ -8,7 +8,7 @@ import numpy as np
def pnl_calculator(
strike: float, premium: float, put: bool, sell: bool, **kwargs: Dict[str, int]
) -> Tuple[np.array, np.array, float]:
) -> Tuple[np.ndarray, np.ndarray, float]:
"""Calculate profit/loss for different option variables
Parameters
@@ -25,20 +25,21 @@ def pnl_calculator(
Returns
-------
price_at_expiry : np.array
price_at_expiry : np.ndarray
Array of prices
pnl: np.array
pnl: np.ndarray
Array of calculated profit/loss
break_even: float
Breakeven point
"""
if "x_min" in kwargs and "x_max" in kwargs:
price_at_expiry = np.linspace(kwargs["x_min"], kwargs["x_max"], 301)
price_at_expiry = np.linspace(kwargs["x_min"], kwargs["x_max"], 301) # type: ignore
else:
price_at_expiry = np.linspace(strike / 2, 1.5 * strike, 301)
sell_factor = [1, -1][sell]
if put:
break_even = strike - sell_factor * premium
pnl = strike - premium - price_at_expiry

View File

@@ -756,7 +756,7 @@ def quote(other_args: List[str], s_ticker: str):
print(
tabulate(
quote_data,
headers=quote_data.columns,
headers=quote_data.columns, # type: ignore
tablefmt="fancy_grid",
stralign="right",
)