Spaces:
Sleeping
Sleeping
artbreguez
commited on
Commit
•
5e0745f
1
Parent(s):
f684503
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import random
|
2 |
+
from pricegenerator.PriceGenerator import PriceGenerator, uLogger
|
3 |
+
from datetime import datetime, timedelta
|
4 |
+
import gradio as gr
|
5 |
+
import pandas as pd
|
6 |
+
import pickle
|
7 |
+
import matplotlib.pyplot as plt
|
8 |
+
import mplfinance as mpf
|
9 |
+
import numpy as np
|
10 |
+
from PIL import Image
|
11 |
+
import io
|
12 |
+
from sklearn.preprocessing import StandardScaler
|
13 |
+
import requests
|
14 |
+
import time
|
15 |
+
|
16 |
+
def download_model():
|
17 |
+
# URL do arquivo do modelo
|
18 |
+
model_url = "https://huggingface.co/artbreguez/BinaryOptionsXGB/resolve/main/eurusd.pkl?download=true"
|
19 |
+
|
20 |
+
# Baixar o arquivo do modelo
|
21 |
+
response = requests.get(model_url, stream=True)
|
22 |
+
|
23 |
+
# Verificar se o download foi bem-sucedido
|
24 |
+
if response.status_code == 200:
|
25 |
+
# Salvar o arquivo
|
26 |
+
with open('eurusd.pkl', 'wb') as f:
|
27 |
+
for chunk in response.iter_content(1024):
|
28 |
+
f.write(chunk)
|
29 |
+
print("Modelo baixado com sucesso!")
|
30 |
+
return True
|
31 |
+
else:
|
32 |
+
print("Erro ao baixar o modelo:", response.status_code)
|
33 |
+
return False
|
34 |
+
|
35 |
+
# Realizar o download do modelo
|
36 |
+
download_success = download_model()
|
37 |
+
|
38 |
+
if download_success:
|
39 |
+
with open('eurusd.pkl', 'rb') as f:
|
40 |
+
content = f.read()
|
41 |
+
with open('eurusd.pkl', 'rb') as f:
|
42 |
+
model = pickle.load(f)
|
43 |
+
else:
|
44 |
+
print("Download do modelo falhou.")
|
45 |
+
|
46 |
+
|
47 |
+
# model = load_model()
|
48 |
+
|
49 |
+
|
50 |
+
def generate_candle_image(df, predicao):
|
51 |
+
df['DateTime'] = pd.to_datetime(df['DateTime'])
|
52 |
+
df.set_index('DateTime', inplace=True)
|
53 |
+
|
54 |
+
prox_candle = pd.DataFrame(index=[df.index[-1] + pd.Timedelta(hours=1)])
|
55 |
+
prox_candle['Open'] = df['Close'].iloc[-1]
|
56 |
+
|
57 |
+
if predicao[0] == 1: # Predição positiva
|
58 |
+
prox_candle['Close'] = prox_candle['Open'] + 0.01
|
59 |
+
prox_candle['High'] = prox_candle['Open'] + 0.01
|
60 |
+
prox_candle['Low'] = prox_candle['Open']
|
61 |
+
else: # Predição negativa
|
62 |
+
prox_candle['Close'] = prox_candle['Open'] - 0.01
|
63 |
+
prox_candle['High'] = prox_candle['Open']
|
64 |
+
prox_candle['Low'] = prox_candle['Open'] - 0.01
|
65 |
+
|
66 |
+
prox_candle['Volume'] = 0
|
67 |
+
|
68 |
+
df_combined = pd.concat([df, prox_candle])
|
69 |
+
|
70 |
+
nans = [float('nan')]*len(df_combined)
|
71 |
+
cdf = pd.DataFrame(dict(Open=nans, High=nans, Low=nans, Close=nans), index=df_combined.index)
|
72 |
+
cdf.loc[df_combined.index[-1]] = df_combined.loc[df_combined.index[-1]]
|
73 |
+
|
74 |
+
mc = mpf.make_marketcolors(up='green', down='red')
|
75 |
+
s = mpf.make_mpf_style(marketcolors=mc)
|
76 |
+
|
77 |
+
fig, axlist = mpf.plot(df_combined, type='candle', volume=True, returnfig=True, ylabel_lower='Volume', title='EUR/USD Price Chart')
|
78 |
+
mpf.plot(cdf, type='candle', style=s, ax=axlist[0])
|
79 |
+
|
80 |
+
img_bytes = io.BytesIO()
|
81 |
+
plt.savefig(img_bytes, format='png')
|
82 |
+
img_bytes.seek(0)
|
83 |
+
|
84 |
+
img_pil = Image.open(img_bytes)
|
85 |
+
|
86 |
+
return img_pil
|
87 |
+
|
88 |
+
|
89 |
+
def predict(X_2d):
|
90 |
+
return model.predict(X_2d)
|
91 |
+
|
92 |
+
|
93 |
+
def generate_array(df):
|
94 |
+
features = df.drop(columns=['DateTime'])
|
95 |
+
scaler = StandardScaler()
|
96 |
+
normalized_features = scaler.fit_transform(features)
|
97 |
+
df_normalized = pd.DataFrame(normalized_features, columns=features.columns, index=df.index)
|
98 |
+
X = df_normalized.iloc[-1].values # Obtém apenas os valores dos recursos normalizados
|
99 |
+
X_2d = np.array(X).reshape(1, -1)
|
100 |
+
return X_2d
|
101 |
+
|
102 |
+
|
103 |
+
def calculate_bollinger_bands(df, period=20):
|
104 |
+
df['SMA'] = df['Close'].rolling(window=period).mean()
|
105 |
+
df['STD'] = df['Close'].rolling(window=period).std()
|
106 |
+
df['Upper'] = df['SMA'] + (2 * df['STD'])
|
107 |
+
df['Lower'] = df['SMA'] - (2 * df['STD'])
|
108 |
+
return df
|
109 |
+
|
110 |
+
def calculate_stochastic_oscillator(df, period=14):
|
111 |
+
low_min = df['Low'].rolling(window=period).min()
|
112 |
+
high_max = df['High'].rolling(window=period).max()
|
113 |
+
close_diff = df['Close'] - low_min
|
114 |
+
high_diff = high_max - low_min
|
115 |
+
stoch = close_diff / high_diff * 100
|
116 |
+
df['Stochastic'] = stoch
|
117 |
+
return df
|
118 |
+
|
119 |
+
def calculate_rsi(df, period=14):
|
120 |
+
diff = df['Close'].diff()
|
121 |
+
gain = diff.where(diff > 0, 0)
|
122 |
+
loss = -diff.where(diff < 0, 0)
|
123 |
+
ema_gain = gain.ewm(alpha=1/period, min_periods=period, adjust=False).mean()
|
124 |
+
ema_loss = loss.ewm(alpha=1/period, min_periods=period, adjust=False).mean()
|
125 |
+
rs = ema_gain / ema_loss
|
126 |
+
rsi = 100 - (100 / (1 + rs))
|
127 |
+
df['RSI'] = rsi
|
128 |
+
return df
|
129 |
+
|
130 |
+
def process_data(file_path):
|
131 |
+
with open(file_path, 'r') as f:
|
132 |
+
data = f.readlines()
|
133 |
+
|
134 |
+
data = [line.strip().split(',') for line in data]
|
135 |
+
|
136 |
+
df = pd.DataFrame(data, columns=['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume'])
|
137 |
+
|
138 |
+
numeric_columns = ['Open', 'High', 'Low', 'Close', 'Volume']
|
139 |
+
df[numeric_columns] = df[numeric_columns].astype(float)
|
140 |
+
|
141 |
+
df['DateTime'] = pd.to_datetime(df['Date'] + ' ' + df['Time'])
|
142 |
+
df.set_index('DateTime', inplace=True)
|
143 |
+
|
144 |
+
df = calculate_bollinger_bands(df)
|
145 |
+
df = calculate_stochastic_oscillator(df)
|
146 |
+
df = calculate_rsi(df)
|
147 |
+
df.drop(['Date', 'Time', 'STD'], axis=1, inplace=True)
|
148 |
+
processed_file_path = file_path.replace('.csv', '_processed.csv')
|
149 |
+
df.to_csv(processed_file_path)
|
150 |
+
|
151 |
+
return df
|
152 |
+
|
153 |
+
def generate_graph_data():
|
154 |
+
uLogger.setLevel(0)
|
155 |
+
|
156 |
+
priceModel = PriceGenerator()
|
157 |
+
priceModel.precision = 5 # 5 casas decimais para maior precisão
|
158 |
+
priceModel.ticker = "EURUSD" # par de moedas EUR/USD
|
159 |
+
priceModel.timeframe = timedelta(hours=1) # intervalo de tempo entre os candles, 1 dia
|
160 |
+
priceModel.timeStart = datetime.today() - timedelta(days=1) # dados do último ano
|
161 |
+
priceModel.horizon = 24 # 24 candles, correspondendo a um dia de dados
|
162 |
+
priceModel.maxClose = 1.25 # Maior preço de fechamento, similar aos preços do EUR/USD
|
163 |
+
priceModel.minClose = 1.05 # Menor preço de fechamento, similar aos preços do EUR/USD
|
164 |
+
priceModel.initClose = None # Preço inicial aleatório dentro do intervalo (minClose, maxClose)
|
165 |
+
priceModel.maxOutlier = 0.01 # Máximo desvio para outliers, similar aos preços do EUR/USD
|
166 |
+
priceModel.maxCandleBody = None # Sem limite para o tamanho do corpo dos candles
|
167 |
+
priceModel.maxVolume = 500000 # Volume máximo, valor arbitrário
|
168 |
+
priceModel.upCandlesProb = 0.5 # Probabilidade de candle de alta de 50%
|
169 |
+
priceModel.outliersProb = 0.03 # Probabilidade de outliers de 3%
|
170 |
+
priceModel.trendDeviation = 0.0005 # Desvio para definir tendência, valor pequeno
|
171 |
+
priceModel.zigzag = 0.01 # Diferença entre pontos do indicador ZigZag
|
172 |
+
priceModel._chartTitle = "EUR/USD Price Chart" # Título do gráfico
|
173 |
+
|
174 |
+
priceModel.Generate()
|
175 |
+
|
176 |
+
priceModel.SaveToFile(fileName="eur_usd_prices.csv")
|
177 |
+
|
178 |
+
def generate_predictions():
|
179 |
+
generate_graph_data()
|
180 |
+
df = process_data('eur_usd_prices.csv')
|
181 |
+
df = pd.read_csv('eur_usd_prices_processed.csv')
|
182 |
+
x_d2 = generate_array(df)
|
183 |
+
prediction = predict(x_d2)
|
184 |
+
image = generate_candle_image(df, prediction)
|
185 |
+
return image
|
186 |
+
|
187 |
+
outputs = gr.Image(type='pil', label='label')
|
188 |
+
inputs = None
|
189 |
+
title = "Binary Options Predictor"
|
190 |
+
description = "This tool generates a simulated candlestick chart for EUR/USD. If the last candlestick is green, it indicates an upward trend, while a red candlestick suggests a downward trend."
|
191 |
+
gr.Interface(generate_predictions, inputs, outputs, title=title, description=description).launch(debug=True)
|