-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathactive_crudeoil.yaml
More file actions
189 lines (145 loc) · 7.33 KB
/
active_crudeoil.yaml
File metadata and controls
189 lines (145 loc) · 7.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
pip install yfinance pandas numpy xgboost scikit-learn
import yfinance as yf
import pandas as pd
import numpy as np
from xgboost import XGBClassifier
from sklearn.model_selection import train_test_split
class OilPriceDropperAI:
def __init__(self, ticker="CL=F"):
self.ticker = ticker
self.model = XGBClassifier(n_estimators=100, learning_rate=0.05, max_depth=5)
def fetch_data(self, period="2y", interval="1h"):
"""Fetches historical data to train the AI."""
data = yf.download(self.ticker, period=period, interval=interval)
return data
def prepare_features(self, df):
"""Creates technical indicators to detect price drops."""
df = df.copy()
# Features: RSI, Moving Average Crossovers, Momentum
df['MA5'] = df['Close'].rolling(window=5).mean()
df['MA20'] = df['Close'].rolling(window=20).mean()
df['Momentum'] = df['Close'] - df['Close'].shift(4)
# Target: 1 if price drops by > 0.5% in the next 3 intervals, else 0
df['Target'] = (df['Close'].shift(-3) < df['Close'] * 0.995).astype(int)
return df.dropna()
def train_logic(self):
"""Trains the AI to recognize patterns before a price drop."""
raw_data = self.fetch_data()
processed = self.prepare_features(raw_data)
X = processed[['MA5', 'MA20', 'Momentum']]
y = processed['Target']
self.model.fit(X, y)
print(f"AI Model trained on {self.ticker} data.")
def monitor_live(self):
"""Checks the current market for 'Drop' signals."""
live_data = yf.download(self.ticker, period="1d", interval="1h").tail(20)
processed = self.prepare_features(live_data)
if not processed.empty:
current_features = processed[['MA5', 'MA20', 'Momentum']].tail(1)
prediction = self.model.predict(current_features)
probability = self.model.predict_proba(current_features)[0][1]
if prediction[0] == 1:
print(f"⚠️ ALERT: High probability of price drop detected ({probability:.2%})")
else:
print(f"✅ Market Stable. Drop probability: {probability:.2%}")
# --- Execution ---
if __name__ == "__main__":
ai_dropper = OilPriceDropperAI()
ai_dropper.train_logic()
print("\n--- Starting Active Monitoring ---")
ai_dropper.monitor_live()
import numpy as np
import pandas as pd
import yfinance as yf
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout, Bidirectional
import matplotlib.pyplot as plt
class CrudeOilAdvancedAI:
def __init__(self, symbol="CL=F"):
self.symbol = symbol
self.scaler = MinMaxScaler(feature_range=(0, 1))
self.model = None
def get_data(self, period="5y"):
df = yf.download(self.symbol, period=period, interval="1d")
# Advanced Feature Engineering
df['Log_Ret'] = np.log(df['Close'] / df['Close'].shift(1))
df['Vol_Shock'] = df['Volume'] / df['Volume'].rolling(20).mean()
# Bollinger Bands for drop detection
sma = df['Close'].rolling(window=20).mean()
std = df['Close'].rolling(window=20).std()
df['B_Upper'] = sma + (std * 2)
df['B_Lower'] = sma - (std * 2)
df['B_Perc'] = (df['Close'] - df['B_Lower']) / (df['B_Upper'] - df['B_Lower'])
return df.dropna()
def create_sequences(self, data, window=60):
X, y = [], []
for i in range(window, len(data)):
X.append(data[i-window:i])
# Target is the next day's 'Close'
y.append(data[i, 0])
return np.array(X), np.array(y)
def build_lstm(self, input_shape):
model = Sequential([
Bidirectional(LSTM(units=100, return_sequences=True), input_shape=input_shape),
Dropout(0.2),
LSTM(units=50, return_sequences=False),
Dropout(0.2),
Dense(units=25),
Dense(units=1)
])
model.compile(optimizer='adam', loss='mean_squared_error')
self.model = model
return model
def train_engine(self):
data = self.get_data()
# Using Close, Log_Ret, and B_Perc as inputs
features = data[['Close', 'Log_Ret', 'B_Perc']].values
scaled_data = self.scaler.fit_transform(features)
X, y = self.create_sequences(scaled_data)
# Training (80/20 split)
split = int(len(X) * 0.8)
self.model = self.build_lstm((X.shape[1], X.shape[2]))
self.model.fit(X[:split], y[:split], epochs=25, batch_size=32, verbose=1)
print("Model specialized for Crude Index Drops.")
def predict_drop_signal(self):
"""Analyzes the last 60 days to predict if a drop is coming."""
recent_data = yf.download(self.symbol, period="90d", interval="1d")
# Apply the same transformations
recent_data['Log_Ret'] = np.log(recent_data['Close'] / recent_data['Close'].shift(1))
sma = recent_data['Close'].rolling(20).mean()
std = recent_data['Close'].rolling(20).std()
recent_data['B_Perc'] = (recent_data['Close'] - (sma-2*std)) / ((sma+2*std)-(sma-2*std))
inputs = self.scaler.transform(recent_data[['Close', 'Log_Ret', 'B_Perc']].tail(60).values)
inputs = np.expand_dims(inputs, axis=0)
prediction_scaled = self.model.predict(inputs)
# Inverse transform logic (Simplified for visualization)
current_price = recent_data['Close'].iloc[-1]
# Logic: If predicted price is >1.5% below current price, trigger DROP ALERT
print(f"Current Index Price: ${current_price:.2f}")
# (Note: In production, use full inverse_transform on a feature-matched array)
# --- Deployment Execution ---
if __name__ == "__main__":
ai_system = CrudeOilAdvancedAI()
ai_system.train_engine()
ai_system.predict_drop_signal()
<svg width="100" height="100" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 2C8.686 2 6 3.791 6 6V18C6 20.209 8.686 22 12 22C15.314 22 18 20.209 18 18V6C18 3.791 15.314 2 12 2Z" stroke="#2C3E50" stroke-width="1.5"/>
<path d="M6 10C6 12.209 8.686 14 12 14C15.314 14 18 12.209 18 10" stroke="#2C3E50" stroke-width="1.5"/>
<path d="M22 6L16 12L12 8L6 14M6 14L6 10M6 14L10 14" stroke="#E74C3C" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<svg width="100" height="100" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="7" y="7" width="10" height="10" rx="2" stroke="#3498DB" stroke-width="2"/>
<circle cx="12" cy="12" r="2" fill="#3498DB"/>
<path d="M12 7V4M12 20V17M7 12H4M20 12H17" stroke="#3498DB" stroke-width="2" stroke-linecap="round"/>
<path d="M12 9C12 9 10 11.5 10 13C10 14.1046 10.8954 15 12 15C13.1046 15 14 14.1046 14 13C14 11.5 12 9 12 9Z" fill="#2C3E50"/>
</svg>
/* Apply this class to the SVG when AI detects a signal */
.signal-active {
animation: pulse-red 1.5s infinite;
}
@keyframes pulse-red {
0% { filter: drop-shadow(0 0 2px rgba(231, 76, 60, 0.5)); transform: scale(1); }
50% { filter: drop-shadow(0 0 15px rgba(231, 76, 60, 1)); transform: scale(1.05); }
100% { filter: drop-shadow(0 0 2px rgba(231, 76, 60, 0.5)); transform: scale(1); }
}