This is an old revision of the document!
Table of Contents
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.
Code
- main.py
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.
The script provides a convenient way to visualize the recent trend of the blue dollar exchange rate, aiding in financial analysis and decision-making.
