Spaces:
Runtime error
Runtime error
Create signals/strategy.py
Browse files- signals/strategy.py +44 -0
signals/strategy.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
from indicators.sma import calculate_sma
|
3 |
+
from indicators.bollinger_bands import calculate_bollinger_bands
|
4 |
+
|
5 |
+
def generate_signals(data):
|
6 |
+
"""
|
7 |
+
Analyzes technical indicators to generate buy and sell signals.
|
8 |
+
|
9 |
+
Args:
|
10 |
+
data (pd.DataFrame): DataFrame containing the historical price data and indicators.
|
11 |
+
|
12 |
+
Returns:
|
13 |
+
pd.DataFrame: The input DataFrame augmented with buy and sell signals.
|
14 |
+
"""
|
15 |
+
# Ensure the necessary indicators are calculated and present in the DataFrame
|
16 |
+
if 'SMA_21' not in data.columns or 'SMA_50' not in data.columns:
|
17 |
+
data['SMA_21'] = calculate_sma(data, period=21)
|
18 |
+
data['SMA_50'] = calculate_sma(data, period=50)
|
19 |
+
|
20 |
+
if 'BB_Upper' not in data.columns:
|
21 |
+
data = calculate_bollinger_bands(data)
|
22 |
+
|
23 |
+
# Initialize columns for signals
|
24 |
+
data['Buy_Signal'] = False
|
25 |
+
data['Sell_Signal'] = False
|
26 |
+
|
27 |
+
# Loop through the DataFrame to find buy and sell conditions
|
28 |
+
for i in range(2, len(data)):
|
29 |
+
# Buy condition: SMA_21 crosses above SMA_50, and has been below SMA_50 for at least 10 periods
|
30 |
+
if data['SMA_21'].iloc[i] > data['SMA_50'].iloc[i] and data['SMA_21'].iloc[i-1] <= data['SMA_50'].iloc[i-1]:
|
31 |
+
if data['SMA_50'].iloc[i-10:i-1].isnull().sum() < 1: # Ensure there's enough data
|
32 |
+
if (data['SMA_21'].iloc[i-10:i-1] < data['SMA_50'].iloc[i-10:i-1]).all():
|
33 |
+
data.at[data.index[i], 'Buy_Signal'] = True
|
34 |
+
|
35 |
+
# Sell condition: Price reaches or exceeds the upper Bollinger band for at least 3 periods after being below it for 5 or more periods
|
36 |
+
if data['close'].iloc[i] >= data['BB_Upper'].iloc[i] and data['close'].iloc[i-1] < data['BB_Upper'].iloc[i-1] and data['close'].iloc[i-2] < data['BB_Upper'].iloc[i-2]:
|
37 |
+
if (data['close'].iloc[i-5:i-1] < data['BB_Upper'].iloc[i-5:i-1]).all():
|
38 |
+
data.at[data.index[i], 'Sell_Signal'] = True
|
39 |
+
|
40 |
+
return data
|
41 |
+
|
42 |
+
# Example usage:
|
43 |
+
# Assuming `price_data` is a pandas DataFrame with columns including 'date', 'open', 'high', 'low', 'close', and 'volume':
|
44 |
+
# signals_data = generate_signals(price_data)
|