Devendra21 commited on
Commit
2882e78
·
verified ·
1 Parent(s): 8e6eedf

Update utils/forex_signals.py

Browse files
Files changed (1) hide show
  1. utils/forex_signals.py +55 -61
utils/forex_signals.py CHANGED
@@ -1,71 +1,65 @@
1
  import pandas as pd
2
  import numpy as np
3
- import talib
4
- from datetime import datetime, timedelta
5
 
6
- def generate_forex_signals(trading_capital, market_risk, user_timezone, additional_pairs=None):
7
- # Placeholder: Retrieve historical data for each currency pair (e.g., from an API like Yahoo Finance or a local dataset)
8
- # In practice, you'll fetch this data dynamically or from a database.
9
- currency_pairs = additional_pairs if additional_pairs else ["EUR/USD", "GBP/USD", "AUD/USD"] # Example pairs
10
- signals = []
11
 
12
- for pair in currency_pairs:
13
- # Fetch historical data for the currency pair
14
- # Placeholder: Load data from a file, API, or a database.
15
- data = fetch_historical_data(pair) # Replace with real function to fetch data
16
 
17
- # Calculate technical indicators for entry/exit points
18
- data['SMA_50'] = talib.SMA(data['close'], timeperiod=50) # Simple Moving Average
19
- data['SMA_200'] = talib.SMA(data['close'], timeperiod=200)
20
- data['RSI'] = talib.RSI(data['close'], timeperiod=14) # Relative Strength Index
21
- data['BB_upper'], data['BB_middle'], data['BB_lower'] = talib.BBANDS(data['close'], timeperiod=20)
 
 
 
22
 
23
- # Define strategy for entry and exit (example strategy)
24
- entry_signal = None
25
- exit_signal = None
26
- entry_time = None
27
- exit_time = None
28
- max_roi = -float('inf')
29
- signal_strength = 0
30
 
31
- for i in range(200, len(data)): # Skip first few rows due to moving average window
32
- # Check if we should enter the market based on SMA crossover
33
- if data['SMA_50'][i] > data['SMA_200'][i] and data['RSI'][i] < 30: # Buy signal (bullish crossover)
34
- entry_signal = "Buy"
35
- entry_time = data.index[i]
36
- entry_price = data['close'][i]
 
 
 
 
37
 
38
- # Look ahead for the best exit signal within the next 2 hours (adjustable window)
39
- for j in range(i+1, min(i+12, len(data))): # Look 2 hours ahead (12 data points for 15-min intervals)
40
- if data['close'][j] > entry_price: # Check if price has gone up
41
- roi = (data['close'][j] - entry_price) / entry_price * 100
42
- if roi > max_roi:
43
- max_roi = roi
44
- exit_signal = "Sell"
45
- exit_time = data.index[j]
46
- signal_strength = 100 # Simplified for now (could be refined further)
47
-
48
- # Append to the list of signals
49
- if entry_signal and exit_signal:
50
- signals.append({
51
- 'currency_pair': pair,
52
- 'entry_time': entry_time,
53
- 'exit_time': exit_time,
54
- 'roi': max_roi,
55
- 'signal_strength': signal_strength
56
- })
57
 
58
- return {
59
- 'best_signal': max(signals, key=lambda x: x['roi'], default={}),
60
- 'all_signals': signals
61
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- def fetch_historical_data(currency_pair):
64
- # Placeholder function to fetch historical price data for a given currency pair
65
- # Ideally, replace this with actual API calls to get real-time data
66
- data = pd.DataFrame({
67
- 'date': pd.date_range(start="2025-01-01", periods=100, freq='15T'),
68
- 'close': np.random.rand(100) * 1.5 + 1.1 # Random price data (replace with actual data)
69
- })
70
- data.set_index('date', inplace=True)
71
- return data
 
1
  import pandas as pd
2
  import numpy as np
 
 
3
 
4
+ # Define the function to calculate technical indicators
 
 
 
 
5
 
6
+ def calculate_sma(data, window=14):
7
+ """Calculate Simple Moving Average (SMA)"""
8
+ return data['Close'].rolling(window=window).mean()
 
9
 
10
+ def calculate_rsi(data, window=14):
11
+ """Calculate Relative Strength Index (RSI)"""
12
+ delta = data['Close'].diff()
13
+ gain = (delta.where(delta > 0, 0)).rolling(window=window).mean()
14
+ loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean()
15
+ rs = gain / loss
16
+ rsi = 100 - (100 / (1 + rs))
17
+ return rsi
18
 
19
+ def calculate_bollinger_bands(data, window=20, num_std_dev=2):
20
+ """Calculate Bollinger Bands"""
21
+ sma = calculate_sma(data, window)
22
+ rolling_std = data['Close'].rolling(window=window).std()
23
+ upper_band = sma + (rolling_std * num_std_dev)
24
+ lower_band = sma - (rolling_std * num_std_dev)
25
+ return upper_band, lower_band
26
 
27
+ def generate_forex_signals(trading_capital, market_risk, user_timezone, additional_pairs=None):
28
+ """Generate trading signals for the Forex market"""
29
+ # Example: Fetch historical data for currency pairs (use your data source here)
30
+ data = pd.read_csv('historical_forex_data.csv') # Replace with real data source
31
+ signals = []
32
+
33
+ # Generate signals for multiple pairs (additional_pairs can be used to loop through them)
34
+ currency_pairs = additional_pairs if additional_pairs else ['EUR/USD', 'GBP/USD', 'USD/JPY', 'AUD/USD']
35
+ for pair in currency_pairs:
36
+ pair_data = data[data['Currency Pair'] == pair]
37
 
38
+ # Calculate technical indicators
39
+ sma = calculate_sma(pair_data)
40
+ rsi = calculate_rsi(pair_data)
41
+ upper_band, lower_band = calculate_bollinger_bands(pair_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ # Example signal generation logic (this can be customized)
44
+ for i in range(len(pair_data)):
45
+ if rsi[i] < 30 and pair_data['Close'][i] < lower_band[i]: # Buy signal
46
+ signals.append({
47
+ 'currency_pair': pair,
48
+ 'entry_time': pair_data['Date'][i],
49
+ 'exit_time': pair_data['Date'][i] + pd.Timedelta(hours=2), # Example exit time
50
+ 'roi': np.random.uniform(0.1, 1), # Simulated ROI, adjust accordingly
51
+ 'signal_strength': np.random.uniform(50, 100) # Simulated signal strength
52
+ })
53
+ elif rsi[i] > 70 and pair_data['Close'][i] > upper_band[i]: # Sell signal
54
+ signals.append({
55
+ 'currency_pair': pair,
56
+ 'entry_time': pair_data['Date'][i],
57
+ 'exit_time': pair_data['Date'][i] + pd.Timedelta(hours=2), # Example exit time
58
+ 'roi': np.random.uniform(0.1, 1), # Simulated ROI, adjust accordingly
59
+ 'signal_strength': np.random.uniform(50, 100) # Simulated signal strength
60
+ })
61
+
62
+ # Choose the best signal
63
+ best_signal = max(signals, key=lambda x: x['roi']) if signals else {}
64
 
65
+ return {"best_signal": best_signal, "all_signals": signals}