====== Generating Pagano Dollar Value Visualization ======
**Objective:** The purpose of this script is to fetch the latest average value of the "dólar blue" (unofficial dollar exchange rate in Argentina) from an API and visualize its historical trend in a transparent PNG image.
Lo de Pagano es por Marcela:
{{ :574818.jpg?nolink&400 |}}
===== Code =====
import time
import requests
import json
import csv
import matplotlib.pyplot as plt
import pandas as pd
from PIL import Image, ImageFont, ImageDraw
from datetime import datetime
def main():
headers = {'content-type': "application/json"}
url = "https://api.bluelytics.com.ar/v2/latest"
response = requests.request("GET", url, params="", headers=headers, timeout=20)
imgfont = ImageFont.truetype("DejaVuSans-Bold.ttf", 72)
today = time.strftime("%Y-%m-%d")
resultFilePath = "/home/facundo/generadorDolarPagano/latest.jpg"
# limpio el csv, para tener 90 dias hacia atras...
# Read the CSV file into a DataFrame
df = pd.read_csv('historial.csv')
# Remove duplicate rows
df = df.drop_duplicates()
# Get the last 180 rows
df = df.tail(180)
# Save the modified DataFrame back to a CSV file
df.to_csv('historial.csv', index=False)
if response.status_code == requests.codes.ok:
# acomoda los datos del json
data = json.loads(response.text)
blue = data.get("blue")
# guarda el punto obtenido para valor blue promedio en un csv. Abre el archivo, anexa, guarda y cierra.
today = datetime.now().strftime('%Y-%m-%d') # Obtener la fecha de hoy
csvData = [today,blue.get("value_avg")]
with open('historial.csv','a', newline='') as f:
out = csv.writer(f)
out.writerow(csvData)
# Lee los datos del archivo CSV y establece las fechas como índice del DataFrame
df_train = pd.read_csv('historial.csv', parse_dates=['date'], index_col='date')
# Plotea los datos
fig, ax = plt.subplots(figsize=(12, 4.9))
ax.plot(df_train.index, df_train['rate'], color='w')
# especifica el tamanio del plot en pulgadas para que coincida con el fondo
# en este caso ta duro el valor, 12 x 4.9
# temp.png es un archivito temporal, se reescribe cada vez que se ejecuta
# Cambia el color de los ejes a verde
ax.tick_params(axis='x', colors='yellow') # Ejes x
ax.tick_params(axis='y', colors='yellow') # Ejes y
plt.savefig("temp.png", transparent=True)
# Compone las imagenes, template.png como template y plot.png con la serie time-value del csv
background = Image.open("template.png")
foreground = Image.open("temp.png")
background.paste(foreground, (0, 0), foreground)
# Escribe literalmente el valor de blue_avg sobre la imagen final y guarda el archivo resultante en la carpeta de trabajo
mensaje = "$ " + str(round(blue.get("value_avg")))
image_editable = ImageDraw.Draw(background)
image_editable.text((550,15), mensaje, (255, 170, 0), font=imgfont)
background.save(resultFilePath, quality=35)
else:
print("falla la consulta a la api")
if __name__ == '__main__':
main()
===== Code Explanation: =====
1. **API Request:** The script sends a GET request to the Blue Lytics API to retrieve the latest dollar exchange rate data. It handles potential errors with a timeout of 20 seconds.
2. **CSV Data Handling:** The script reads a CSV file containing historical exchange rate data. It removes duplicate rows and keeps only the last 180 days of data.
3. **Data Processing and Storage:** If the API request is successful, the script processes the JSON response, extracting the average blue dollar value. It then appends the current date and the average value to the CSV file for historical tracking.
4. **Plotting Data:** The script reads the updated CSV file, sets the dates as the index of the DataFrame, and plots the historical exchange rate data. The resulting plot is saved as a transparent PNG file named "temp.png".
5. **Image Composition:** The script opens a template image ("template.png") and overlays the generated plot ("temp.png") onto it. It then adds the current average blue dollar value as text to the composed image.
6. **Result Saving:** The final composed image is saved as "latest.jpg" in the specified directory ("/home/facundo/generadorDolarPagano/").
**Note:** This script requires the following dependencies: requests, json, csv, matplotlib, pandas, Pillow.
==== Results ====
https://repo.facundoitest.space/usdPagano/latest.jpg
{{:latest.jpg?nolink&500|}}
The script provides a convenient way to visualize the recent trend of the blue dollar exchange rate, aiding in financial analysis and decision-making.
==== Sending the results... ====
def dolarpagano(update: Update, context: CallbackContext) -> None:
now = datetime.now()
version = now.strftime('%d%m%Y_%H%M') # Get the current date and time in the specified format
url = f"https://repo.facundoitest.space/usdPagano/latest.jpg?v={version}"
update.message.reply_text(url)
This snippet defines a function called `dolarpagano` that accepts two arguments: `update` and `context`, which are provided by the `python-telegram-bot` library to handle updates and message context in Telegram.
Within the function:
- It gets the current date and time using `datetime.now()`.
- The date and time are formatted as a string in the 'ddmmYYYY_HHMM' format using the `strftime()` method, where 'dd' represents the day, 'mm' the month, 'YYYY' the year, 'HH' the hour, and 'MM' the minutes.
- A URL is constructed using this formatted string to include the updated version of the image resource. This is achieved by concatenating the base URL string with a query parameter `v` carrying the updated timestamp.
- Finally, it responds to the Telegram message with the generated URL using the `reply_text()` method of the `update.message` object.
In summary, this function generates a URL pointing to the latest image of a dollar meme and sends it as a reply to a message in Telegram with the 'v' parameter to bypass Telegram's thumbnail cache.