Skip to content

Instantly share code, notes, and snippets.

@mhackersu
Created March 27, 2025 20:27
Show Gist options
  • Save mhackersu/4bceddc2939ed7da5e9ba4cb47200101 to your computer and use it in GitHub Desktop.
Save mhackersu/4bceddc2939ed7da5e9ba4cb47200101 to your computer and use it in GitHub Desktop.
Standard Deviation Function
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