FireTax/price.py

53 lines
1.5 KiB
Python
Raw Permalink Normal View History

2024-11-28 17:13:39 +11:00
from pycoingecko import CoinGeckoAPI
import json
import os
import dotenv
dotenv.load_dotenv()
fiat = os.getenv("fiat")
usd_to_fiat = float(os.getenv("usd_to_fiat"))
stablecoins = ["usdc", "usdt", "dai"]
# Get api key
if os.path.exists("api_keys/coingecko.txt"):
with open("api_keys/coingecko.txt", "r") as f:
apiKey = f.read()
else:
apiKey = None
def get_historical_fiat_price(coin_id, date):
"""
Fetches the historical price of a cryptocurrency in fiat on a specific date.
Args:
coin_id (str): The CoinGecko ID of the cryptocurrency (e.g., 'bitcoin', 'ethereum').
date (str): The date in YYYY-MM-DD format.
Returns:
float: The historical price of the cryptocurrency in specified fiat currency.
"""
if coin_id in stablecoins:
return 1 * usd_to_fiat
historical_prices = {}
if os.path.exists(f"chain_data/{coin_id}_price.json"):
with open(f"chain_data/{coin_id}_price.json", "r") as f:
historical_prices = json.load(f)
if date in historical_prices:
return historical_prices[date]
cg = CoinGeckoAPI()
historical_data = cg.get_coin_history_by_id(id=coin_id, date=date, localization='false', demo_api_key=apiKey)
price_data = historical_data['market_data']['current_price']
fiat_price = price_data[fiat]
historical_prices[date] = fiat_price
with open(f"chain_data/{coin_id}_price.json", "w") as f:
json.dump(historical_prices, f)
return fiat_price