Devendra21 commited on
Commit
d334385
·
verified ·
1 Parent(s): a2a7548

Update utils/forex_signals.py

Browse files
Files changed (1) hide show
  1. utils/forex_signals.py +68 -50
utils/forex_signals.py CHANGED
@@ -1,63 +1,81 @@
1
  import requests
2
- import random
3
- from datetime import datetime, timedelta
4
 
5
  API_KEY = "89SEdLScHxHk6j8J9OoH4sLFS3Mri4oW"
6
- BASE_URL = "https://financialmodelingprep.com/api/v3/forex"
7
 
8
- def fetch_forex_data(pair):
9
- """Fetch historical forex data for a given currency pair."""
 
 
 
 
 
 
10
  try:
11
- url = f"{BASE_URL}/{pair}?apikey={API_KEY}"
 
 
12
  response = requests.get(url)
 
 
 
13
 
14
- if response.status_code == 200:
15
- data = response.json()
16
- if not data or "historical" not in data:
17
- return None # No data available for this pair
18
- return data["historical"]
19
  else:
20
- print(f"Error fetching data for {pair}: {response.status_code} - {response.text}")
21
  return None
22
  except Exception as e:
23
- print(f"Exception while fetching data for {pair}: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  return None
25
 
26
- def generate_forex_signals(trading_capital, market_risk, user_timezone, additional_pairs):
27
- """Generate forex trading signals."""
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  signals = []
29
- for pair in additional_pairs:
30
- print(f"Fetching data for {pair}...")
31
- data = fetch_forex_data(pair)
32
-
33
- if data is None:
34
- print(f"Skipping {pair} due to missing data.")
35
- continue # Skip to the next pair if data is missing
36
-
37
- # Simulate processing data for signal generation
38
- entry_time = datetime.now()
39
- exit_time = entry_time + timedelta(hours=random.randint(1, 5)) # Simulated exit time
40
- roi = round(random.uniform(0.5, 10.0), 2) # Simulated ROI
41
- signal_strength = round(random.uniform(50, 100), 2) # Simulated signal strength
42
-
43
- signals.append({
44
- "currency_pair": pair,
45
- "entry_time": entry_time.strftime("%Y-%m-%d %H:%M:%S"),
46
- "exit_time": exit_time.strftime("%Y-%m-%d %H:%M:%S"),
47
- "roi": roi,
48
- "signal_strength": signal_strength,
49
- })
50
-
51
- # Sort signals by ROI (descending) to recommend the best signal
52
- signals.sort(key=lambda x: x["roi"], reverse=True)
53
-
54
- if signals:
55
- return {
56
- "best_signal": signals[0],
57
- "all_signals": signals,
58
- }
59
- else:
60
- return {
61
- "best_signal": None,
62
- "all_signals": [],
63
- }
 
1
  import requests
2
+ import pandas as pd
3
+ 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 the pair into the format required by the API (EURUSD, GBPUSD, etc.)
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
+ return pd.DataFrame(data["historical"])
 
 
 
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(1)
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
  signals = []
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
+ signals.append({"pair": pair, "signal": "Buy"})
78
+ elif df["SMA_50"].iloc[-1] < df["SMA_200"].iloc[-1] and df["RSI"].iloc[-1] > 30:
79
+ signals.append({"pair": pair, "signal": "Sell"})
80
+
81
+ return signals