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

Requests using style fix #1691

Merged
merged 6 commits into from
Apr 17, 2022
Merged
Show file tree
Hide file tree
Changes from 5 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
5 changes: 3 additions & 2 deletions openbb_terminal/common/behavioural_analysis/finbrain_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,10 @@ def get_sentiment(ticker: str) -> pd.DataFrame:
result = requests.get(f"https://api.finbrain.tech/v0/sentiments/{ticker}")
sentiment = pd.DataFrame()
if result.status_code == 200:
if "sentimentAnalysis" in result.json():
result_json = result.json()
if "sentimentAnalysis" in result_json:
sentiment = pd.DataFrame.from_dict(
result.json()["sentimentAnalysis"], orient="index"
result_json["sentimentAnalysis"], orient="index"
)
sentiment.index = pd.to_datetime(sentiment.index).to_pydatetime()
sentiment.index.name = "date"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,22 +50,23 @@ def get_historical(ticker: str, start: str, end: str, number: int) -> pd.DataFra
response = requests.get(
"https://api.sentimentinvestor.com/v1/historical", params=payload
)
response_json = response.json()

df = pd.DataFrame()

if "results" in response.json():
if response.json()["results"]:
df = pd.DataFrame(response.json()["results"])
if "results" in response_json:
if response_json["results"]:
df = pd.DataFrame(response_json["results"])
df = df.set_index("timestamp_date")
df.index = pd.to_datetime(df.index)
else:
console.print("No data found.\n")

elif "error" in response.json():
if "Authorization error" in response.json()["error"]:
elif "error" in response_json:
if "Authorization error" in response_json["error"]:
console.print("[red]Invalid API Key[/red]\n")
else:
console.print({response.json()["error"]})
console.print({response_json["error"]})

return df

Expand Down Expand Up @@ -94,23 +95,24 @@ def check_supported_ticker(ticker: str) -> bool:
response = requests.get(
"https://api.sentimentinvestor.com/v1/supported", params=payload
)
response_json = response.json()

result = False

if "result" in response.json():
if "result" in response_json:
# if ticker is valid, payload has result key
if response.json()["result"]:
result = response.json()["result"]
if response_json["result"]:
result = response_json["result"]
else:
console.print(
f"[red]Ticker {ticker} not supported. Please try another one![/red]\n"
)

elif "error" in response.json():
if "Authorization error" in response.json()["error"]:
elif "error" in response_json:
if "Authorization error" in response_json["error"]:
console.print("[red]Invalid API Key[/red]\n")
else:
console.print({response.json()["error"]})
console.print({response_json["error"]})

return result

Expand Down Expand Up @@ -150,19 +152,20 @@ def get_trending(start: datetime, hour: int, number: int) -> pd.DataFrame:
response = requests.get(
"https://api.sentimentinvestor.com/v1/trending", params=payload
)
response_json = response.json()

df = pd.DataFrame()

if "results" in response.json():
if response.json()["results"]:
df = pd.DataFrame(response.json()["results"])
if "results" in response_json:
if response_json["results"]:
df = pd.DataFrame(response_json["results"])
else:
console.print(f"No data found for start date of {str(start_timestamp)}.\n")

elif "error" in response.json():
if "Authorization error" in response.json()["error"]:
elif "error" in response_json:
if "Authorization error" in response_json["error"]:
console.print("[red]Invalid API Key[/red]\n")
else:
console.print({response.json()["error"]})
console.print({response_json["error"]})

return df
21 changes: 7 additions & 14 deletions openbb_terminal/common/behavioural_analysis/stocktwits_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,12 @@ def get_bullbear(ticker: str) -> Tuple[int, int, int, int]:
f"https://api.stocktwits.com/api/2/streams/symbol/{ticker}.json"
)
if result.status_code == 200:
watchlist_count = result.json()["symbol"]["watchlist_count"]
result_json = result.json()
watchlist_count = result_json["symbol"]["watchlist_count"]
n_cases = 0
n_bull = 0
n_bear = 0
for message in result.json()["messages"]:
for message in result_json["messages"]:
if message["entities"]["sentiment"]:
n_cases += 1
n_bull += message["entities"]["sentiment"]["basic"] == "Bullish"
Expand Down Expand Up @@ -69,13 +70,10 @@ def get_messages(ticker: str, limit: int = 30) -> List[str]:
result = requests.get(
f"https://api.stocktwits.com/api/2/streams/symbol/{ticker}.json"
)
messages = []
if result.status_code == 200:
for idx, message in enumerate(result.json()["messages"]):
messages.append(message["body"])
if idx > limit - 1:
break
return messages
return [message["body"] for message in result.json()["messages"][:limit]]

return []


@log_start_end(log=logger)
Expand Down Expand Up @@ -116,11 +114,6 @@ def get_stalker(user: str, limit: int = 30) -> List[Dict]:
"""
result = requests.get(f"https://api.stocktwits.com/api/2/streams/user/{user}.json")
if result.status_code == 200:
messages = []
for idx, message in enumerate(result.json()["messages"]):
messages.append(message)
if idx > limit - 1:
break
return messages
return list(result.json()["messages"][:limit])

return []
7 changes: 4 additions & 3 deletions openbb_terminal/common/newsapi_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,16 @@ def get_news(

# Check that the API response was successful
if response.status_code == 200:
response_json = response.json()
console.print(
f"{response.json()['totalResults']} news articles for {term} were found since {s_from}\n"
f"{response_json['totalResults']} news articles for {term} were found since {s_from}\n"
)

if show_newest:
articles = response.json()["articles"]
articles = response_json["articles"]

else:
articles = response.json()["articles"][::-1]
articles = response_json["articles"][::-1]

elif response.status_code == 426:
console.print(f"Error in request: {response.json()['message']}", "\n")
Expand Down
9 changes: 5 additions & 4 deletions openbb_terminal/cryptocurrency/defi/smartstake_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,18 @@ def get_luna_supply_stats(supply_type: str, days: int) -> pd.DataFrame:
"https://prod.smartstakeapi.com/listData?app=TERRA",
params=payload,
)
response_json = response.json()

df = pd.DataFrame()

if "errors" in response.json():
if "DENIED" in response.json()["errors"]:
if "errors" in response_json:
if "DENIED" in response_json["errors"]:
console.print("[red]Invalid API Key[/red]\n")
else:
console.print(response.json()["errors"])
console.print(response_json["errors"])

else:
result = response.json()[supply_type]
result = response_json[supply_type]

# check if result is not empty
if result:
Expand Down
7 changes: 4 additions & 3 deletions openbb_terminal/cryptocurrency/overview/cryptopanic_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,15 +93,16 @@ def make_request(**kwargs: Any) -> Optional[dict]:
url += f"&regions={region}"

response = requests.get(url)
response_json = response.json()
result = None

if response.status_code == 200:
result = response.json()
result = response_json
else:
if "Token not found" in response.json()["info"]:
if "Token not found" in response_json["info"]:
console.print("[red]Invalid API Key[/red]\n")
else:
console.print(response.json()["info"])
console.print(response_json["info"])

logger.warning("Invalid authentication: %s", response.text)

Expand Down
24 changes: 12 additions & 12 deletions openbb_terminal/economy/alphavantage_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ def get_real_gdp(interval: str = "a") -> pd.DataFrame:

# Successful requests
if "data" in payload:
if r.json()["data"]:
data = pd.DataFrame(r.json()["data"])
if payload["data"]:
data = pd.DataFrame(payload["data"])
data["date"] = pd.to_datetime(data["date"])
data["GDP"] = data["value"].astype(float)
data = data.drop(columns=["value"])
Expand Down Expand Up @@ -93,8 +93,8 @@ def get_gdp_capita() -> pd.DataFrame:
data = pd.DataFrame()
# Successful requests
if "data" in payload:
if r.json()["data"]:
data = pd.DataFrame(r.json()["data"])
if payload["data"]:
data = pd.DataFrame(payload["data"])
data["date"] = pd.to_datetime(data["date"])
data["GDP"] = data["value"].astype(float)
data = data.drop(columns=["value"])
Expand Down Expand Up @@ -128,8 +128,8 @@ def get_inflation() -> pd.DataFrame:
data = pd.DataFrame()
# Successful requests
if "data" in payload:
if r.json()["data"]:
data = pd.DataFrame(r.json()["data"])
if payload["data"]:
data = pd.DataFrame(payload["data"])
data["date"] = pd.to_datetime(data["date"])
data["Inflation"] = data["value"].astype(float)
data = data.drop(columns=["value"])
Expand Down Expand Up @@ -171,8 +171,8 @@ def get_cpi(interval: str) -> pd.DataFrame:

# Successful requests
if "data" in payload:
if r.json()["data"]:
data = pd.DataFrame(r.json()["data"])
if payload["data"]:
data = pd.DataFrame(payload["data"])
data["date"] = pd.to_datetime(data["date"])
data["CPI"] = data["value"].astype(float)
data = data.drop(columns=["value"])
Expand Down Expand Up @@ -218,8 +218,8 @@ def get_treasury_yield(interval: str, maturity: str) -> pd.DataFrame:

# Successful requests
if "data" in payload:
if r.json()["data"]:
data = pd.DataFrame(r.json()["data"])
if payload["data"]:
data = pd.DataFrame(payload["data"])
data["date"] = pd.to_datetime(data["date"])
data["Yield"] = data["value"].astype(float)
data = data.drop(columns=["value"])
Expand Down Expand Up @@ -255,8 +255,8 @@ def get_unemployment() -> pd.DataFrame:

# Successful requests
if "data" in payload:
if r.json()["data"]:
data = pd.DataFrame(r.json()["data"])
if payload["data"]:
data = pd.DataFrame(payload["data"])
data["date"] = pd.to_datetime(data["date"])
data["unemp"] = data["value"].astype(float)
data = data.drop(columns=["value"])
Expand Down
5 changes: 3 additions & 2 deletions openbb_terminal/economy/nasdaq_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,9 @@ def get_big_mac_index(country_code: str) -> pd.DataFrame:
df = pd.DataFrame()

if r.status_code == 200:
df = pd.DataFrame(r.json()["dataset"]["data"])
df.columns = r.json()["dataset"]["column_names"]
response_json = r.json()
df = pd.DataFrame(response_json["dataset"]["data"])
df.columns = response_json["dataset"]["column_names"]
df["Date"] = pd.to_datetime(df["Date"])

# Wrong API Key
Expand Down
26 changes: 14 additions & 12 deletions openbb_terminal/forex/av_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,18 +76,19 @@ def get_quote(to_symbol: str, from_symbol: str) -> Dict:
)

response = requests.get(url)
response_json = response.json()
result = {}

# If the returned data was unsuccessful
if "Error Message" in response.json():
console.print(response.json()["Error Message"])
logger.error(response.json()["Error Message"])
if "Error Message" in response_json:
console.print(response_json["Error Message"])
logger.error(response_json["Error Message"])
else:
# check if json is empty
if not response.json():
if not response_json:
console.print("No data found.\n")
else:
result = response.json()
result = response_json

return result

Expand Down Expand Up @@ -128,25 +129,26 @@ def get_historical(
url += f"&interval={interval}min"

r = requests.get(url)
response_json = r.json()

if r.status_code != 200:
return pd.DataFrame()

df = pd.DataFrame()

# If the returned data was unsuccessful
if "Error Message" in r.json():
console.print(r.json()["Error Message"])
elif "Note" in r.json():
console.print(r.json()["Note"])
if "Error Message" in response_json:
console.print(response_json["Error Message"])
elif "Note" in response_json:
console.print(response_json["Note"])
else:
# check if json is empty
if not r.json():
if not response_json:
console.print("No data found.\n")
else:
key = list(r.json().keys())[1]
key = list(response_json.keys())[1]

df = pd.DataFrame.from_dict(r.json()[key], orient="index")
df = pd.DataFrame.from_dict(response_json[key], orient="index")

if start_date and resolution != "i":
df = df[df.index > start_date]
Expand Down
7 changes: 4 additions & 3 deletions openbb_terminal/stocks/comparison_analysis/finbrain_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,13 @@ def get_sentiments(tickers: List[str]) -> pd.DataFrame:
for ticker in tickers:
result = requests.get(f"https://api.finbrain.tech/v0/sentiments/{ticker}")
if result.status_code == 200:
if "ticker" in result.json() and "sentimentAnalysis" in result.json():
result_json = result.json()
if "ticker" in result_json and "sentimentAnalysis" in result_json:
df_sentiment[ticker] = [
float(val)
for val in list(result.json()["sentimentAnalysis"].values())
for val in list(result_json["sentimentAnalysis"].values())
]
dates_sentiment = list(result.json()["sentimentAnalysis"].keys())
dates_sentiment = list(result_json["sentimentAnalysis"].keys())
else:
console.print(f"Unexpected data format from FinBrain API for {ticker}")
tickers_to_remove.append(ticker)
Expand Down
5 changes: 3 additions & 2 deletions openbb_terminal/stocks/dark_pool_shorts/stockgrid_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,12 @@ def get_short_interest_volume(ticker: str) -> Tuple[pd.DataFrame, List]:
"""
link = f"https://stockgridapp.herokuapp.com/get_dark_pool_individual_data?ticker={ticker}"
response = requests.get(link)
response_json = response.json()

df = pd.DataFrame(response.json()["individual_short_volume_table"]["data"])
df = pd.DataFrame(response_json["individual_short_volume_table"]["data"])
df["date"] = pd.to_datetime(df["date"])

return df, response.json()["prices"]["prices"]
return df, response_json["prices"]["prices"]


@log_start_end(log=logger)
Expand Down
Loading