-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
214 lines (188 loc) · 7.78 KB
/
app.py
File metadata and controls
214 lines (188 loc) · 7.78 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import os
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from flask import Flask, jsonify, render_template
from io import BytesIO
import base64
from datetime import datetime, timedelta
app = Flask(__name__)
TICKER = 'GOOG'
MA1 = 10
MA2 = 21
price_image = ""
oscillator_image = ""
cumulative_profit = 0.0
rsi_cumulative_profit = 0.0
rsi_image = ""
rsi_price_image = ""
start_date = datetime(2024, 1, 1)
def macd(signals, ma1, ma2):
signals['ma1'] = signals['Close'].rolling(window=ma1, min_periods=1, center=False).mean()
signals['ma2'] = signals['Close'].rolling(window=ma2, min_periods=1, center=False).mean()
return signals
def smma(series, n):
if len(series) == 0:
raise ValueError("The input series is empty")
output = [series[0]]
for i in range(1, len(series)):
temp = output[-1] * (n - 1) + series[i]
output.append(temp / n)
return output
def rsi(data, n=14):
delta = data.diff().dropna()
up = np.where(delta > 0, delta, 0)
down = np.where(delta < 0, -delta, 0)
rs = np.divide(smma(up, n), smma(down, n))
output = 100 - 100 / (1 + rs)
return output[n-1:]
def signal_generation(df, ma1, ma2):
global cumulative_profit
signals = macd(df, ma1, ma2)
signals['positions'] = 0
signals['positions'][ma1:] = np.where(signals['ma1'][ma1:] >= signals['ma2'][ma1:], 1, 0)
signals['signals'] = signals['positions'].diff()
signals['oscillator'] = signals['ma1'] - signals['ma2']
signals['profit'] = 0.0
buy_price = 0.0
for i in range(1, len(signals)):
if signals['signals'].iloc[i] == 1:
buy_price = signals['Close'].iloc[i]
elif signals['signals'].iloc[i] == -1 and buy_price != 0.0:
sell_price = signals['Close'].iloc[i]
signals['profit'].iloc[i] = sell_price - buy_price
buy_price = 0.0
signals['cumulative_profit'] = signals['profit'].cumsum()
cumulative_profit = signals['cumulative_profit'].iloc[-1]
return signals
def rsi_signal_generation(df, method, n=14):
global rsi_cumulative_profit
if 'Close' not in df or len(df['Close']) == 0:
raise ValueError("The dataframe does not have a valid 'Close' column or it is empty")
df['rsi'] = 0.0
df['rsi'][n:] = method(df['Close'], n=14)
df['positions'] = np.select([df['rsi'] < 30, df['rsi'] > 70], [1, -1], default=0)
df['signals'] = df['positions'].diff()
df['profit'] = 0.0
buy_price = 0.0
for i in range(1, len(df)):
if df['signals'].iloc[i] == 1:
buy_price = df['Close'].iloc[i]
elif df['signals'].iloc[i] == -1 and buy_price != 0.0:
sell_price = df['Close'].iloc[i]
df['profit'].iloc[i] = sell_price - buy_price
buy_price = 0.0
df['cumulative_profit'] = df['profit'].cumsum()
rsi_cumulative_profit = df['cumulative_profit'].iloc[-1]
return df
def fetch_and_generate_chart():
global price_image, oscillator_image
try:
end_date = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
df = yf.download(TICKER, start=start_date, end=end_date)
signals = signal_generation(df, MA1, MA2)
# Generate the price image
fig, ax = plt.subplots()
df['Close'].plot(label=TICKER, ax=ax)
ax.plot(signals.loc[signals['signals'] == 1].index, signals['Close'][signals['signals'] == 1], '^', markersize=10, color='g', lw=0, label='LONG')
ax.plot(signals.loc[signals['signals'] == -1].index, signals['Close'][signals['signals'] == -1], 'v', markersize=10, color='r', lw=0, label='SHORT')
plt.legend(loc='best')
plt.grid(True)
plt.title('Positions')
figfile = BytesIO()
plt.savefig(figfile, format='jpeg')
figfile.seek(0)
price_image = base64.b64encode(figfile.getvalue()).decode()
print(f"Price image Base64 length: {len(price_image)}") # Log the length of the Base64 string
plt.close(fig)
# Generate the oscillator image
fig, (cx, bx) = plt.subplots(nrows=2, ncols=1)
signals['oscillator'].plot(kind='bar', color='r', ax=cx)
cx.legend(loc='best')
cx.grid(True)
cx.set_xticks([])
cx.set_title('MACD Oscillator')
signals['ma1'].plot(label='ma1', ax=bx)
signals['ma2'].plot(label='ma2', linestyle=':', ax=bx)
bx.legend(loc='best')
bx.grid(True)
figfile1 = BytesIO()
plt.savefig(figfile1, format='jpeg')
figfile1.seek(0)
oscillator_image = base64.b64encode(figfile1.getvalue()).decode()
print(f"Oscillator image Base64 length: {len(oscillator_image)}") # Log the length of the Base64 string
plt.close(fig)
except Exception as e:
print(f"Error fetching or generating MACD chart: {e}")
def fetch_and_generate_rsi_chart():
global rsi_price_image, rsi_image
try:
end_date = datetime.today().strftime('%Y-%m-%d')
df = yf.download(TICKER, start=start_date, end=end_date)
new = rsi_signal_generation(df, rsi, n=14)
# Generate and save the price image
fig, ax = plt.subplots()
new['Close'].plot(label=TICKER, ax=ax)
ax.plot(new.loc[new['signals'] == 1].index, new['Close'][new['signals'] == 1], '^', markersize=10, color='g', lw=0, label='LONG')
ax.plot(new.loc[new['signals'] == -1].index, new['Close'][new['signals'] == -1], 'v', markersize=10, color='r', lw=0, label='SHORT')
plt.legend(loc='best')
plt.grid(True)
plt.title('Positions')
figfile2 = BytesIO()
plt.savefig(figfile2, format='jpeg')
figfile2.seek(0)
rsi_price_image = base64.b64encode(figfile2.getvalue()).decode()
print(f"RSI price image Base64 length: {len(rsi_price_image)}") # Log the length of the Base64 string
plt.close(fig)
# Plot and save the RSI image
fig, bx = plt.subplots()
new['rsi'][14:].plot(label='relative strength index', c='#522e75', ax=bx)
bx.fill_between(new.index, 30, 70, alpha=0.5, color='#f22f08')
bx.text(new.index[-45], 75, 'overbought', color='#594346', size=12.5)
bx.text(new.index[-45], 25, 'oversold', color='#594346', size=12.5)
plt.xlabel('Date')
plt.ylabel('value')
plt.title('RSI')
plt.legend(loc='best')
plt.grid(True)
figfile3 = BytesIO()
plt.savefig(figfile3, format='jpeg')
figfile3.seek(0)
rsi_image = base64.b64encode(figfile3.getvalue()).decode()
print(f"RSI image Base64 length: {len(rsi_image)}") # Log the length of the Base64 string
plt.close(fig)
except Exception as e:
print(f"Error fetching or generating RSI chart: {e}")
@app.route('/')
def home():
return render_template('index.html')
@app.route('/generate_macd_chart', methods=['POST'])
def generate_macd_chart():
fetch_and_generate_chart()
return jsonify({'status': 'MACD chart generated'})
@app.route('/generate_rsi_chart', methods=['POST'])
def generate_rsi_chart():
fetch_and_generate_rsi_chart()
return jsonify({'status': 'RSI chart generated'})
@app.route('/get_profit')
def get_profit():
return jsonify({
'cumulative_profit': cumulative_profit,
'cumulative_rsi_profit': rsi_cumulative_profit
})
@app.route('/get_price_image')
def get_price_image_route():
return jsonify({'image': price_image})
@app.route('/get_oscillator_image')
def get_oscillator_image_route():
return jsonify({'image': oscillator_image})
@app.route('/get_rsi_price_image')
def get_rsi_price_image_route():
return jsonify({'image': rsi_price_image})
@app.route('/get_rsi_image')
def get_rsi_image_route():
return jsonify({'image': rsi_image})
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(debug=True, host='0.0.0.0', port=port)