Devendra21 commited on
Commit
9f2fedd
·
verified ·
1 Parent(s): 4b691a4

Update utils/forex_signals.py

Browse files
Files changed (1) hide show
  1. utils/forex_signals.py +61 -80
utils/forex_signals.py CHANGED
@@ -1,82 +1,63 @@
1
  import requests
2
- import pandas as pd
3
- import numpy as np
4
-
5
- # Function to calculate Simple Moving Average (SMA)
6
- def calculate_sma(data, window=14):
7
- return data['close'].rolling(window=window).mean()
8
-
9
- # Function to calculate Relative Strength Index (RSI)
10
- def calculate_rsi(data, window=14):
11
- delta = data['close'].diff()
12
- gain = (delta.where(delta > 0, 0)).rolling(window=window).mean()
13
- loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean()
14
- rs = gain / loss
15
- rsi = 100 - (100 / (1 + rs))
16
- return rsi
17
-
18
- # Function to calculate Bollinger Bands
19
- def calculate_bollinger_bands(data, window=20, num_std_dev=2):
20
- sma = calculate_sma(data)
21
- rolling_std = data['close'].rolling(window=window).std()
22
- upper_band = sma + (rolling_std * num_std_dev)
23
- lower_band = sma - (rolling_std * num_std_dev)
24
- return upper_band, lower_band
25
-
26
- # Function to fetch Forex data from Financial Modeling Prep API
27
- def fetch_forex_data(pair, start_date='2020-01-01', end_date='2025-01-01', api_key='89SEdLScHxHk6j8J9OoH4sLFS3Mri4oW'):
28
- url = f'https://financialmodelingprep.com/api/v3/historical-price-full/{pair}?from={start_date}&to={end_date}&apikey={api_key}'
29
- response = requests.get(url)
30
- data = response.json()
31
-
32
- if 'historical' in data:
33
- df = pd.DataFrame(data['historical'])
34
- df['date'] = pd.to_datetime(df['date'])
35
- df.set_index('date', inplace=True)
36
- return df
37
- else:
38
- print(f"Error: No data available for {pair}.")
39
- return pd.DataFrame()
40
-
41
- # Function to generate Forex signals
42
- def generate_forex_signals(trading_capital, market_risk, user_timezone, additional_pairs=None, api_key='your_api_key'):
43
  signals = []
44
-
45
- # List of currency pairs to generate signals for
46
- currency_pairs = additional_pairs if additional_pairs else ['EURUSD', 'GBPUSD', 'USDJPY', 'AUDUSD']
47
-
48
- # Loop through each currency pair
49
- for pair in currency_pairs:
50
- pair_data = fetch_forex_data(pair, api_key=api_key)
51
-
52
- if pair_data.empty:
53
- continue # Skip if no data is available
54
-
55
- # Calculate technical indicators
56
- sma = calculate_sma(pair_data)
57
- rsi = calculate_rsi(pair_data)
58
- upper_band, lower_band = calculate_bollinger_bands(pair_data)
59
-
60
- # Example signal generation logic (buy/sell based on RSI and Bollinger Bands)
61
- for i in range(len(pair_data)):
62
- if rsi[i] < 30 and pair_data['close'][i] < lower_band[i]: # Buy signal
63
- signals.append({
64
- 'currency_pair': pair,
65
- 'entry_time': pair_data.index[i],
66
- 'exit_time': pair_data.index[i] + pd.Timedelta(hours=2), # Example exit time
67
- 'roi': np.random.uniform(0.1, 1), # Simulated ROI, adjust accordingly
68
- 'signal_strength': np.random.uniform(50, 100) # Simulated signal strength
69
- })
70
- elif rsi[i] > 70 and pair_data['close'][i] > upper_band[i]: # Sell signal
71
- signals.append({
72
- 'currency_pair': pair,
73
- 'entry_time': pair_data.index[i],
74
- 'exit_time': pair_data.index[i] + pd.Timedelta(hours=2), # Example exit time
75
- 'roi': np.random.uniform(0.1, 1), # Simulated ROI, adjust accordingly
76
- 'signal_strength': np.random.uniform(50, 100) # Simulated signal strength
77
- })
78
-
79
- # Find the best signal based on highest ROI
80
- best_signal = max(signals, key=lambda x: x['roi']) if signals else {}
81
-
82
- return {"best_signal": best_signal, "all_signals": signals}
 
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
+ }