* Added model fix

* Fixed nasdaq view issue

* Fixed fred_view bug

* Fixed screener view bug

* Improved oanda_model excption handling

* Fixed scripts

* Improved run_scripts
This commit is contained in:
Colin Delahunty
2022-02-04 09:15:38 -05:00
committed by GitHub
parent d8279adcbf
commit b189ffa45d
9 changed files with 154 additions and 88 deletions

View File

@@ -546,7 +546,7 @@ Loaded {self.current_coin} against {self.current_currency} from {CRYPTO_SOURCES[
self.queue,
)
except ImportError:
console.print("[red]Run pip install tensorflow to continue[/red]")
console.print("[red]Run pip install tensorflow to continue[/red]\n")
else:
console.print(

View File

@@ -144,9 +144,11 @@ SORT_VALUES = [
def coin_formatter(n):
# TODO: can be improved
coins = []
re_str = "small/(.*)(.jpg|.png|.JPG|.PNG)"
for coin in n:
coin_stripped = re.search("small/(.*)(.jpg|.png|.JPG|.PNG)", coin).group(1)
coins.append(coin_stripped)
if re.search(re_str, coin):
coin_stripped = re.search(re_str, coin).group(1)
coins.append(coin_stripped)
return ",".join(coins)

View File

@@ -112,50 +112,53 @@ def display_fred_series(
data = data.dropna()
# Try to get everything onto the same 0-10 scale.
# To do so, think in scientific notation. Divide the data by whatever the E would be
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
if len(series_ids) == 1:
s_id = series_ids[0]
sub_dict: Dict = d_series[s_id]
title = f"{sub_dict['title']} ({sub_dict['units']})"
ax.plot(data.index, data, label="\n".join(textwrap.wrap(title, 80)))
else:
for s_id, sub_dict in d_series.items():
data_to_plot = data[s_id].dropna()
exponent = int(np.log10(data_to_plot.max()))
data_to_plot /= 10**exponent
multiplier = f"x {format_units(10**exponent)}" if exponent > 0 else ""
title = f"{sub_dict['title']} ({sub_dict['units']}) {'['+multiplier+']' if multiplier else ''}"
ax.plot(
data_to_plot.index,
data_to_plot,
label="\n".join(textwrap.wrap(title, 80))
if len(series_ids) < 5
else title,
if not data.empty:
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
if len(series_ids) == 1:
s_id = series_ids[0]
sub_dict: Dict = d_series[s_id]
title = f"{sub_dict['title']} ({sub_dict['units']})"
ax.plot(data.index, data, label="\n".join(textwrap.wrap(title, 80)))
else:
for s_id, sub_dict in d_series.items():
data_to_plot = data[s_id].dropna()
exponent = int(np.log10(data_to_plot.max()))
data_to_plot /= 10**exponent
multiplier = f"x {format_units(10**exponent)}" if exponent > 0 else ""
title = f"{sub_dict['title']} ({sub_dict['units']}) {'['+multiplier+']' if multiplier else ''}"
ax.plot(
data_to_plot.index,
data_to_plot,
label="\n".join(textwrap.wrap(title, 80))
if len(series_ids) < 5
else title,
)
ax.legend(prop={"size": 10}, bbox_to_anchor=(0, 1), loc="lower left")
ax.grid()
ax.set_xlim(data.index[0], data.index[-1])
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.gcf().autofmt_xdate()
fig.tight_layout()
if gtff.USE_ION:
plt.ion()
plt.show()
data.index = [x.strftime("%Y-%m-%d") for x in data.index]
if raw:
print_rich_table(
data.tail(limit),
headers=list(data.columns),
show_index=True,
index_name="Date",
)
ax.legend(prop={"size": 10}, bbox_to_anchor=(0, 1), loc="lower left")
ax.grid()
ax.set_xlim(data.index[0], data.index[-1])
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.gcf().autofmt_xdate()
fig.tight_layout()
if gtff.USE_ION:
plt.ion()
plt.show()
data.index = [x.strftime("%Y-%m-%d") for x in data.index]
if raw:
print_rich_table(
data.tail(limit),
headers=list(data.columns),
show_index=True,
index_name="Date",
export_data(
export,
os.path.dirname(os.path.abspath(__file__)),
"plot",
data,
)
export_data(
export,
os.path.dirname(os.path.abspath(__file__)),
"plot",
data,
)
console.print("")
console.print("")
else:
console.print("[red]Unable to get data for the fred series [/red]\n")

View File

@@ -42,22 +42,31 @@ def display_big_mac_index(
big_mac = pd.DataFrame(columns=df_cols)
for country in country_codes:
df1 = nasdaq_model.get_big_mac_index(country)
big_mac[country] = df1["dollar_price"]
big_mac["Date"] = df1["Date"]
if not df1.empty:
big_mac[country] = df1["dollar_price"]
big_mac["Date"] = df1["Date"]
big_mac.set_index("Date", inplace=True)
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
big_mac.plot(ax=ax, marker="o")
ax.legend(bbox_to_anchor=(1, 1))
ax.set_title("Big Mac Index (USD)")
ax.set_ylabel("Price of Big Mac in USD")
ax.grid("on")
if gtff.USE_ION:
plt.ion()
fig.tight_layout()
plt.show()
if raw:
print_rich_table(big_mac, headers=list(big_mac.columns), title="Big Mac Index")
if not big_mac.empty:
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
big_mac.plot(ax=ax, marker="o")
ax.legend(bbox_to_anchor=(1, 1))
ax.set_title("Big Mac Index (USD)")
ax.set_ylabel("Price of Big Mac in USD")
ax.grid("on")
if gtff.USE_ION:
plt.ion()
fig.tight_layout()
plt.show()
export_data(export, os.path.dirname(os.path.abspath(__file__)), "bigmac", big_mac)
console.print("")
if raw:
print_rich_table(
big_mac, headers=list(big_mac.columns), title="Big Mac Index"
)
export_data(
export, os.path.dirname(os.path.abspath(__file__)), "bigmac", big_mac
)
console.print("")
else:
console.print("[red]Unable to get big mac data[/red]\n")

View File

@@ -41,7 +41,7 @@ def view_screener(
print_rich_table(
screened_data.head(num_to_show).fillna(""),
headers=screened_data.columns,
headers=list(screened_data.columns),
show_index=True,
title="Display Screener Output",
)

View File

@@ -27,6 +27,8 @@ logger = logging.getLogger(__name__)
if cfg.OANDA_ACCOUNT_TYPE != "REPLACE_ME":
client = API(access_token=cfg.OANDA_TOKEN, environment=cfg.OANDA_ACCOUNT_TYPE)
else:
client = None
account = cfg.OANDA_ACCOUNT
@@ -84,6 +86,9 @@ def account_summary_request(accountID: str = account) -> Union[pd.DataFrame, boo
if accountID == "REPLACE_ME":
console.print("Error: Oanda account credentials are required.")
return False
if client is None:
return False
try:
request = accounts.AccountSummary(accountID=accountID)
response = client.request(request)
@@ -153,6 +158,10 @@ def orderbook_plot_data_request(
)
return False
parameters = {"bucketWidth": "1"}
if client is None:
return False
try:
request = instruments.InstrumentsOrderBook(
instrument=instrument, params=parameters
@@ -192,6 +201,9 @@ def positionbook_plot_data_request(
"Error: An instrument should be loaded before running this command."
)
return False
if client is None:
return False
try:
request = instruments.InstrumentsPositionBook(instrument=instrument)
response = client.request(request)
@@ -227,6 +239,9 @@ def order_history_request(
parameters["state"] = order_state
parameters["count"] = order_count
if client is None:
return False
try:
request = orders.OrderList(accountID, parameters)
response = client.request(request)
@@ -292,6 +307,10 @@ def create_order_request(
"positionFill": "DEFAULT",
}
}
if client is None:
return False
try:
request = orders.OrderCreate(accountID, data)
response = client.request(request)
@@ -331,6 +350,10 @@ def cancel_pending_order_request(
if accountID == "REPLACE_ME":
console.print("Error: Oanda account credentials are required.")
return False
if client is None:
return False
try:
request = orders.OrderCancel(accountID, orderID)
response = client.request(request)
@@ -354,6 +377,10 @@ def open_positions_request(accountID: str = account) -> Union[pd.DataFrame, bool
if accountID == "REPLACE_ME":
console.print("Error: Oanda account credentials are required.")
return False
if client is None:
return False
try:
request = positions.OpenPositions(accountID)
response = client.request(request)
@@ -399,6 +426,10 @@ def pending_orders_request(accountID: str = account) -> Union[pd.DataFrame, bool
if accountID == "REPLACE_ME":
console.print("Error: Oanda account credentials are required.")
return False
if client is None:
return False
try:
request = orders.OrdersPending(accountID)
response = client.request(request)
@@ -443,6 +474,10 @@ def open_trades_request(accountID: str = account) -> Union[pd.DataFrame, bool]:
if accountID == "REPLACE_ME":
console.print("Error: Oanda account credentials are required.")
return False
if client is None:
return False
try:
request = trades.OpenTrades(accountID)
response = client.request(request)
@@ -503,6 +538,10 @@ def close_trades_request(
data = {}
if units is not None:
data["units"] = units
if client is None:
return False
try:
request = trades.TradeClose(accountID, orderID, data)
response = client.request(request)
@@ -556,6 +595,10 @@ def get_candles_dataframe(
"granularity": granularity,
"count": candlecount,
}
if client is None:
return False
try:
request = instruments.InstrumentsCandles(instrument, params=parameters)
response = client.request(request)
@@ -610,6 +653,10 @@ def get_calendar_request(
)
return False
parameters = {"instrument": instrument, "period": str(days * 86400 * -1)}
if client is None:
return False
try:
request = forexlabs.Calendar(params=parameters)
response = client.request(request)

View File

@@ -300,27 +300,29 @@ def show_candles(
df_candles, additional_charts
)
if gtff.USE_ION:
plt.ion()
if gtff.USE_ION:
plt.ion()
_, ax = mpf.plot(
df_candles,
type="candle",
style="charles",
volume=True,
scale_padding={"left": 0.3, "right": 1, "top": 0.8, "bottom": 0.8},
returnfig=True,
addplot=plots_to_add,
)
_, ax = mpf.plot(
df_candles,
type="candle",
style="charles",
volume=True,
scale_padding={"left": 0.3, "right": 1, "top": 0.8, "bottom": 0.8},
returnfig=True,
addplot=plots_to_add,
)
ax[0].set_title(f"{instrument} {granularity}")
if len(legends) > 0:
ax[0].legend(legends)
# pylint: disable=C0200
for i in range(0, len(subplot_legends), 2):
ax[subplot_legends[i]].legend(subplot_legends[i + 1])
ax[0].set_title(f"{instrument} {granularity}")
if len(legends) > 0:
ax[0].legend(legends)
# pylint: disable=C0200
for i in range(0, len(subplot_legends), 2):
ax[subplot_legends[i]].legend(subplot_legends[i + 1])
console.print("")
console.print("")
else:
console.print("[red]Could not retrieve the data[/red]\n")
@log_start_end(log=logger)

10
run_scripts.sh vendored
View File

@@ -1,5 +1,7 @@
for f in scripts/*.gst; do
python terminal.py "$f" || break # execute successfully or break
# Or more explicitly: if this execution fails, then stop the `for`:
# if ! bash "$f"; then break; fi
done
if [[ "$f" == *"$1"* ]] || [ -z "$1" ]; then
python terminal.py "$f" || break # execute successfully or break
# Or more explicitly: if this execution fails, then stop the `for`:
# if ! bash "$f"; then break; fi
fi
done

View File

@@ -1,3 +1,4 @@
jupyter
reports
h
help
@@ -14,4 +15,4 @@ r
reset
home
jupyter
exit
exit