Spaces:
Sleeping
Sleeping
Update utils/forex_signals.py
Browse files- utils/forex_signals.py +42 -34
utils/forex_signals.py
CHANGED
|
@@ -4,78 +4,86 @@ import numpy as np
|
|
| 4 |
|
| 5 |
API_KEY = "89SEdLScHxHk6j8J9OoH4sLFS3Mri4oW"
|
| 6 |
|
| 7 |
-
CURRENCY_PAIRS = [
|
| 8 |
-
"EUR/USD", "GBP/USD", "USD/JPY", "AUD/USD",
|
| 9 |
-
"CAD/JPY", "NZD/USD", "CHF/JPY", "AUD/JPY",
|
| 10 |
-
"GBP/CHF", "EUR/GBP"
|
| 11 |
-
]
|
| 12 |
-
|
| 13 |
-
|
| 14 |
def fetch_forex_data(currency_pair):
|
| 15 |
try:
|
| 16 |
-
# Convert
|
| 17 |
formatted_pair = currency_pair.replace("/", "")
|
| 18 |
url = f"https://financialmodelingprep.com/api/v3/forex/{formatted_pair}?apikey={API_KEY}"
|
| 19 |
response = requests.get(url)
|
| 20 |
response.raise_for_status()
|
| 21 |
|
| 22 |
data = response.json()
|
| 23 |
-
|
| 24 |
if "historical" in data and len(data["historical"]) > 0:
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
| 26 |
else:
|
| 27 |
print(f"No data available for {currency_pair}.")
|
| 28 |
return None
|
| 29 |
except Exception as e:
|
| 30 |
-
print(f"Error fetching data for {currency_pair}: {e}")
|
| 31 |
return None
|
| 32 |
|
| 33 |
|
| 34 |
def calculate_indicators(df):
|
| 35 |
-
if df is None or df.empty:
|
| 36 |
-
return None
|
| 37 |
-
|
| 38 |
try:
|
| 39 |
df["SMA_50"] = df["close"].rolling(window=50).mean()
|
| 40 |
df["SMA_200"] = df["close"].rolling(window=200).mean()
|
| 41 |
df["RSI"] = compute_rsi(df["close"])
|
| 42 |
return df
|
| 43 |
except Exception as e:
|
| 44 |
-
print(f"Error calculating indicators: {e}")
|
| 45 |
return None
|
| 46 |
|
| 47 |
|
| 48 |
def compute_rsi(series, period=14):
|
| 49 |
-
delta = series.diff(
|
| 50 |
-
gain = delta.where(delta > 0, 0)
|
| 51 |
-
loss = -delta.where(delta < 0, 0)
|
| 52 |
-
|
| 53 |
-
avg_gain = gain.rolling(window=period).mean()
|
| 54 |
-
avg_loss = loss.rolling(window=period).mean()
|
| 55 |
-
|
| 56 |
-
rs = avg_gain / avg_loss
|
| 57 |
rsi = 100 - (100 / (1 + rs))
|
| 58 |
return rsi
|
| 59 |
|
| 60 |
|
| 61 |
-
def generate_forex_signals():
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
for pair in CURRENCY_PAIRS:
|
| 65 |
-
print(f"Processing currency pair: {pair}")
|
| 66 |
|
|
|
|
|
|
|
| 67 |
df = fetch_forex_data(pair)
|
| 68 |
-
if df is None:
|
| 69 |
continue
|
| 70 |
|
| 71 |
df = calculate_indicators(df)
|
| 72 |
if df is None or df.empty:
|
| 73 |
continue
|
| 74 |
|
| 75 |
-
# Check for crossover signals
|
| 76 |
if df["SMA_50"].iloc[-1] > df["SMA_200"].iloc[-1] and df["RSI"].iloc[-1] < 70:
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
elif df["SMA_50"].iloc[-1] < df["SMA_200"].iloc[-1] and df["RSI"].iloc[-1] > 30:
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
API_KEY = "89SEdLScHxHk6j8J9OoH4sLFS3Mri4oW"
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
def fetch_forex_data(currency_pair):
|
| 8 |
try:
|
| 9 |
+
# Convert currency pair to API format (e.g., EUR/USD -> EURUSD)
|
| 10 |
formatted_pair = currency_pair.replace("/", "")
|
| 11 |
url = f"https://financialmodelingprep.com/api/v3/forex/{formatted_pair}?apikey={API_KEY}"
|
| 12 |
response = requests.get(url)
|
| 13 |
response.raise_for_status()
|
| 14 |
|
| 15 |
data = response.json()
|
|
|
|
| 16 |
if "historical" in data and len(data["historical"]) > 0:
|
| 17 |
+
df = pd.DataFrame(data["historical"])
|
| 18 |
+
df["close"] = pd.to_numeric(df["close"], errors="coerce")
|
| 19 |
+
df.dropna(inplace=True)
|
| 20 |
+
return df
|
| 21 |
else:
|
| 22 |
print(f"No data available for {currency_pair}.")
|
| 23 |
return None
|
| 24 |
except Exception as e:
|
| 25 |
+
print(f"Error fetching data for {currency_pair}: {str(e)}")
|
| 26 |
return None
|
| 27 |
|
| 28 |
|
| 29 |
def calculate_indicators(df):
|
|
|
|
|
|
|
|
|
|
| 30 |
try:
|
| 31 |
df["SMA_50"] = df["close"].rolling(window=50).mean()
|
| 32 |
df["SMA_200"] = df["close"].rolling(window=200).mean()
|
| 33 |
df["RSI"] = compute_rsi(df["close"])
|
| 34 |
return df
|
| 35 |
except Exception as e:
|
| 36 |
+
print(f"Error calculating indicators: {str(e)}")
|
| 37 |
return None
|
| 38 |
|
| 39 |
|
| 40 |
def compute_rsi(series, period=14):
|
| 41 |
+
delta = series.diff()
|
| 42 |
+
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
|
| 43 |
+
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
|
| 44 |
+
rs = gain / loss
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
rsi = 100 - (100 / (1 + rs))
|
| 46 |
return rsi
|
| 47 |
|
| 48 |
|
| 49 |
+
def generate_forex_signals(trading_capital, market_risk, currency_pairs):
|
| 50 |
+
all_signals = []
|
| 51 |
+
best_signal = None
|
|
|
|
|
|
|
| 52 |
|
| 53 |
+
for pair in currency_pairs:
|
| 54 |
+
print(f"Processing {pair}...")
|
| 55 |
df = fetch_forex_data(pair)
|
| 56 |
+
if df is None or df.empty:
|
| 57 |
continue
|
| 58 |
|
| 59 |
df = calculate_indicators(df)
|
| 60 |
if df is None or df.empty:
|
| 61 |
continue
|
| 62 |
|
|
|
|
| 63 |
if df["SMA_50"].iloc[-1] > df["SMA_200"].iloc[-1] and df["RSI"].iloc[-1] < 70:
|
| 64 |
+
signal = {
|
| 65 |
+
"currency_pair": pair,
|
| 66 |
+
"entry_time": df["date"].iloc[-1],
|
| 67 |
+
"exit_time": df["date"].iloc[-1], # Placeholder; use a model to predict exit
|
| 68 |
+
"roi": np.random.uniform(1, 3), # Simulated ROI
|
| 69 |
+
"signal_strength": "Strong Buy"
|
| 70 |
+
}
|
| 71 |
+
all_signals.append(signal)
|
| 72 |
elif df["SMA_50"].iloc[-1] < df["SMA_200"].iloc[-1] and df["RSI"].iloc[-1] > 30:
|
| 73 |
+
signal = {
|
| 74 |
+
"currency_pair": pair,
|
| 75 |
+
"entry_time": df["date"].iloc[-1],
|
| 76 |
+
"exit_time": df["date"].iloc[-1], # Placeholder; use a model to predict exit
|
| 77 |
+
"roi": np.random.uniform(-3, -1), # Simulated ROI
|
| 78 |
+
"signal_strength": "Strong Sell"
|
| 79 |
+
}
|
| 80 |
+
all_signals.append(signal)
|
| 81 |
+
|
| 82 |
+
# Determine the best signal based on ROI
|
| 83 |
+
if all_signals:
|
| 84 |
+
best_signal = max(all_signals, key=lambda x: x["roi"])
|
| 85 |
+
|
| 86 |
+
return {
|
| 87 |
+
"all_signals": all_signals,
|
| 88 |
+
"best_signal": best_signal
|
| 89 |
+
}
|