Skip to content

Commit

Permalink
Fixed images
Browse files Browse the repository at this point in the history
close #498
  • Loading branch information
StephanAkkerman committed Feb 22, 2024
1 parent fdf076e commit d0868cb
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 52 deletions.
2 changes: 1 addition & 1 deletion src/cogs/loops/assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ async def format_exchange(
new_df = await self.update_prices_and_changes(new_df)

# Remove everything after % in change
new_df["change"] = new_df["change"].str.split("%").str[0]
#new_df["change"] = new_df["change"].str.split("%").str[0]

# Set the types (again)
new_df = new_df.astype(
Expand Down
11 changes: 6 additions & 5 deletions src/cogs/loops/liquidations.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,9 @@ async def post_liquidations(self):
fig.set_size_inches(15, 6)

# Convert to plot to a temporary image
filename = "temp/liquidations.png"
plt.savefig(filename, bbox_inches="tight", dpi=300)
file_name = "liquidations.png"
file_path = os.path.join("temp", file_name)
plt.savefig(file_path, bbox_inches="tight", dpi=300)
plt.cla()
plt.close()

Expand All @@ -172,8 +173,8 @@ async def post_liquidations(self):
timestamp=datetime.datetime.now(datetime.timezone.utc),
url="https://www.coinglass.com/LiquidationData",
)
file = discord.File(filename)
e.set_image(url=f"attachment://{filename}")
file = discord.File(file_path, filename=file_name)
e.set_image(url=f"attachment://{file_name}")
e.set_footer(
text="\u200b",
icon_url=data_sources["coinglass"]["icon"],
Expand All @@ -183,7 +184,7 @@ async def post_liquidations(self):
await self.channel.send(file=file, embed=e)

# Delete yield.png
os.remove(filename)
os.remove(file_path)


def setup(bot: commands.Bot) -> None:
Expand Down
11 changes: 6 additions & 5 deletions src/cogs/loops/rsi_heatmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,9 @@ async def post_rsi_heatmap(self):
# Display the plot
plt.tight_layout()

filename = "temp/rsi_heatmap.png"
plt.savefig(filename, bbox_inches="tight", dpi=300)
file_name = "rsi_heatmap.png"
file_path = os.path.join("temp", file_name)
plt.savefig(file_path, bbox_inches="tight", dpi=300)
plt.cla()
plt.close()

Expand All @@ -155,8 +156,8 @@ async def post_rsi_heatmap(self):
timestamp=datetime.datetime.now(datetime.timezone.utc),
url="https://www.coinglass.com/pro/i/RsiHeatMap",
)
file = discord.File(filename)
e.set_image(url=f"attachment://{filename}")
file = discord.File(file_path, filename=file_name)
e.set_image(url=f"attachment://{file_name}")
e.set_footer(
text="\u200b",
icon_url=data_sources["coinglass"]["icon"],
Expand All @@ -166,7 +167,7 @@ async def post_rsi_heatmap(self):
await self.channel.send(file=file, embed=e)

# Delete yield.png
os.remove(filename)
os.remove(file_path)


def setup(bot: commands.Bot) -> None:
Expand Down
9 changes: 5 additions & 4 deletions src/cogs/loops/yield.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,9 @@ async def post_curve(self) -> None:
plt.xlabel("Residual Maturity")

# Convert to plot to a temporary image
file_name = "temp/yield.png"
plt.savefig(file_name, bbox_inches="tight", dpi=300)
file_name = "yield.png"
file_path = os.path.join("temp", file_name)
plt.savefig(file_path, bbox_inches="tight", dpi=300)
plt.cla()
plt.close()

Expand All @@ -85,14 +86,14 @@ async def post_curve(self) -> None:
color=0x000000,
timestamp=datetime.datetime.now(datetime.timezone.utc),
)
file = discord.File(file_name)
file = discord.File(file_path, filename=file_name)
e.set_image(url=f"attachment://{file_name}")

await self.channel.purge(limit=1)
await self.channel.send(file=file, embed=e)

# Delete yield.png
os.remove(file_name)
os.remove(file_path)

async def plot_US_yield(self) -> None:
"""
Expand Down
75 changes: 38 additions & 37 deletions src/util/yf_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,43 +13,44 @@


async def yf_info(ticker: str, do_format_change: bool = True):
try:
stock_info = await Ticker(ticker, asynchronous=True).price

# Test if the ticker is valid
if not isinstance(stock_info.get(ticker), dict):
return None

stock_info = stock_info[ticker]
prices = []
changes = []

# Helper function to format and append price data
def append_price_data(price_key, change_key):
price = stock_info.get(price_key)
change = stock_info.get(change_key, 0)
if do_format_change:
change = format_change(change)
if price and price != 0:
prices.append(price)
changes.append(change or "N/A") # Handle None or missing change

# Determine which price to report based on market hours
if afterHours():
append_price_data("preMarketPrice", "preMarketChangePercent")
append_price_data("regularMarketPrice", "regularMarketChangePercent")

# Calculate volume
volume = stock_info.get("regularMarketVolume", 0) * prices[-1] if prices else 0

# Prepare return values
url = f"https://finance.yahoo.com/quote/{ticker}"
exchange = stock_info.get("exchange", "N/A")

return volume, url, exchange, prices, changes if changes else ["N/A"], ticker

except Exception as e:
print(f"Error in getting Yahoo Finance data for {ticker}: {e}")
# try:
stock_info = await Ticker(ticker, asynchronous=True).price

# Test if the ticker is valid
if not isinstance(stock_info.get(ticker), dict):
return None

stock_info = stock_info[ticker]
prices = []
changes = []

# Helper function to format and append price data
def append_price_data(price_key, change_key):
price = stock_info.get(price_key)
change = stock_info.get(change_key, 0)
if do_format_change:
change = format_change(change)
if price and price != 0:
prices.append(price)
changes.append(change or "N/A") # Handle None or missing change

# Determine which price to report based on market hours
if afterHours():
append_price_data("preMarketPrice", "preMarketChangePercent")
append_price_data("regularMarketPrice", "regularMarketChangePercent")

# Calculate volume
volume = stock_info.get("regularMarketVolume", 0) * prices[-1] if prices else 0

# Prepare return values
url = f"https://finance.yahoo.com/quote/{ticker}"
exchange = stock_info.get("exchange", "N/A")

return volume, url, exchange, prices, changes if changes else ["N/A"], ticker

# TODO: ratelimit exception
# except Exception as e:
# print(f"Error in getting Yahoo Finance data for {ticker}: {e}")

return None

Expand Down

0 comments on commit d0868cb

Please sign in to comment.