Created
March 27, 2025 20:27
-
-
Save mhackersu/4bceddc2939ed7da5e9ba4cb47200101 to your computer and use it in GitHub Desktop.
Standard Deviation Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import requests | |
import statistics | |
def get_exchange_rate(base_currency, target_currency, api_url): | |
response = requests.get(api_url) | |
data = response.json() | |
if 'rates' in data and target_currency in data['rates']: | |
return data['rates'][target_currency] | |
else: | |
raise ValueError("Invalid API response or currency not found") | |
def calculate_standard_deviation(base_currency, target_currency, api_url, duration=600, interval=60): | |
price_diffs = [] | |
end_time = time.time() + duration | |
while time.time() < end_time: | |
try: | |
rate1 = get_exchange_rate(base_currency, target_currency, api_url) | |
rate2 = get_exchange_rate(target_currency, base_currency, api_url) | |
price_diffs.append(abs(rate1 - rate2)) | |
except Exception as e: | |
print(f"Error fetching data: {e}") | |
time.sleep(interval) | |
if len(price_diffs) > 1: | |
return statistics.stdev(price_diffs) | |
else: | |
return "Not enough data to calculate standard deviation." | |
# Example usage (replace 'API_URL' with a valid API endpoint): | |
API_URL = "https://api.exchangerate-api.com/v4/latest/USD" | |
base_currency = "USD" | |
target_currency = "EUR" | |
dev = calculate_standard_deviation(base_currency, target_currency, API_URL) | |
print(f"Standard Deviation: {dev}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment