LeonceNsh commited on
Commit
b333b98
·
verified ·
1 Parent(s): 33b84b1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +174 -0
app.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yfinance as yf
2
+ import matplotlib.pyplot as plt
3
+ import numpy as np
4
+ from concurrent.futures import ThreadPoolExecutor, as_completed
5
+ from datetime import datetime
6
+ from PIL import Image
7
+ import io
8
+ import gradio as gr
9
+ from cachetools import cached, TTLCache
10
+ import cProfile
11
+ import pstats
12
+
13
+ # Global fontsize variable
14
+ FONT_SIZE = 32
15
+
16
+ # Company ticker mapping for US-based public finance companies
17
+ COMPANY_TICKERS_US_FINANCE = {
18
+ 'JPMorgan Chase': 'JPM',
19
+ 'Visa': 'V',
20
+ 'PNC Financial': 'PNC',
21
+ 'Goldman Sachs': 'GS',
22
+ 'Bank of America': 'BAC',
23
+ 'Wells Fargo': 'WFC',
24
+ 'Citigroup': 'C',
25
+ 'American Express': 'AXP',
26
+ 'Morgan Stanley': 'MS',
27
+ 'U.S. Bancorp': 'USB',
28
+ 'Capital One': 'COF',
29
+ 'Charles Schwab': 'SCHW',
30
+ 'BlackRock': 'BLK',
31
+ 'Mastercard': 'MA',
32
+ 'PayPal': 'PYPL',
33
+ 'Fidelity National Information Services': 'FIS',
34
+ 'S&P Global': 'SPGI',
35
+ 'Northern Trust': 'NTRS',
36
+ 'Discover': 'DFS',
37
+ 'Synchrony': 'SYF',
38
+ 'First Republic': 'FRC',
39
+ 'State Street': 'STT',
40
+ 'CME Group': 'CME'
41
+ }
42
+
43
+
44
+ # Cache with 1-day TTL
45
+ cache = TTLCache(maxsize=100, ttl=86400)
46
+
47
+ @cached(cache)
48
+ def fetch_historical_data(ticker, start_date, end_date):
49
+ """Fetch historical stock data and market cap from Yahoo Finance."""
50
+ try:
51
+ data = yf.download(ticker, start=start_date, end=end_date)
52
+ if data.empty:
53
+ raise ValueError(f"No data found for ticker {ticker}")
54
+ info = yf.Ticker(ticker).info
55
+ market_cap = info.get('marketCap', 'N/A')
56
+ if market_cap != 'N/A':
57
+ market_cap = market_cap / 1e9 # Convert to billions
58
+ return data, market_cap
59
+ except Exception as e:
60
+ print(f"Error fetching data for {ticker}: {e}")
61
+ return None, 'N/A'
62
+
63
+ def plot_to_image(plt, title, market_cap):
64
+ """Convert plot to a PIL Image object."""
65
+ plt.title(title, fontsize=FONT_SIZE + 1, pad=40)
66
+ plt.suptitle(f'Market Cap: ${market_cap:.2f} Billion', fontsize=FONT_SIZE - 5, y=0.92, weight='bold')
67
+ plt.legend(fontsize=FONT_SIZE)
68
+ plt.xlabel('Date', fontsize=FONT_SIZE)
69
+ plt.ylabel('', fontsize=FONT_SIZE)
70
+ plt.grid(True)
71
+ plt.xticks(rotation=45, ha='right', fontsize=FONT_SIZE)
72
+ plt.yticks(fontsize=FONT_SIZE)
73
+ plt.tight_layout(rect=[0, 0, 1, 0.95])
74
+
75
+ buf = io.BytesIO()
76
+ plt.savefig(buf, format='png', dpi=200)
77
+ plt.close()
78
+ buf.seek(0)
79
+ return Image.open(buf)
80
+
81
+ def plot_indicator(data, company_name, ticker, indicator, market_cap):
82
+ """Plot selected technical indicator for a single company."""
83
+ plt.figure(figsize=(16, 10))
84
+ if indicator == "SMA":
85
+ sma_55 = data['Close'].rolling(window=55).mean()
86
+ sma_200 = data['Close'].rolling(window=200).mean()
87
+ plt.plot(data.index, data['Close'], label='Close')
88
+ plt.plot(data.index, sma_55, label='55-day SMA')
89
+ plt.plot(data.index, sma_200, label='200-day SMA')
90
+ plt.ylabel('Price', fontsize=FONT_SIZE)
91
+ elif indicator == "MACD":
92
+ exp1 = data['Close'].ewm(span=12, adjust=False).mean()
93
+ exp2 = data['Close'].ewm(span=26, adjust=False).mean()
94
+ macd = exp1 - exp2
95
+ signal = macd.ewm(span=9, adjust=False).mean()
96
+ plt.plot(data.index, macd, label='MACD')
97
+ plt.plot(data.index, signal, label='Signal Line')
98
+ plt.bar(data.index, macd - signal, label='MACD Histogram')
99
+ plt.ylabel('MACD', fontsize=FONT_SIZE)
100
+
101
+ return plot_to_image(plt, f'{company_name} ({ticker}) {indicator}', market_cap)
102
+
103
+ def plot_indicators(company_names, indicator_types):
104
+ """Plot the selected indicators for the selected companies."""
105
+ images = []
106
+ if len(company_names) > 5:
107
+ return None, "You can select up to 5 companies at the same time."
108
+ if len(company_names) > 1 and len(indicator_types) > 1:
109
+ return None, "You can only select one indicator when selecting multiple companies."
110
+
111
+ with ThreadPoolExecutor() as executor:
112
+ future_to_company = {
113
+ executor.submit(fetch_historical_data, COMPANY_TICKERS[company], '2000-01-01', datetime.now().strftime('%Y-%m-%d')): (company, indicator)
114
+ for company in company_names
115
+ for indicator in indicator_types
116
+ }
117
+
118
+ for future in as_completed(future_to_company):
119
+ company, indicator = future_to_company[future]
120
+ ticker = COMPANY_TICKERS[company]
121
+ data, market_cap = future.result()
122
+ if data is None:
123
+ continue
124
+ images.append(plot_indicator(data, company, ticker, indicator, market_cap))
125
+
126
+ return images, ""
127
+
128
+ def select_all_indicators(select_all):
129
+ """Select or deselect all indicators based on the select_all flag."""
130
+ indicators = ["SMA", "MACD"]
131
+ return indicators if select_all else []
132
+
133
+ def launch_gradio_app():
134
+ """Launch the Gradio app for interactive plotting."""
135
+ company_choices = list(COMPANY_TICKERS.keys())
136
+ indicators = ["SMA", "MACD"]
137
+
138
+ def fetch_and_plot(company_names, indicator_types):
139
+ images, error_message = plot_indicators(company_names, indicator_types)
140
+ if error_message:
141
+ return [None] * len(indicator_types), error_message
142
+ return images, ""
143
+
144
+ with gr.Blocks() as demo:
145
+ company_checkboxgroup = gr.CheckboxGroup(choices=company_choices, label="Select Companies")
146
+
147
+ select_all_checkbox = gr.Checkbox(label="Select All Indicators", value=False, interactive=True)
148
+ indicator_types_checkboxgroup = gr.CheckboxGroup(choices=indicators, label="Select Technical Indicators")
149
+ select_all_checkbox.change(select_all_indicators, inputs=select_all_checkbox, outputs=indicator_types_checkboxgroup)
150
+
151
+ plot_gallery = gr.Gallery(label="Indicator Plots")
152
+ error_markdown = gr.Markdown()
153
+
154
+ gr.Interface(
155
+ fetch_and_plot,
156
+ [company_checkboxgroup, indicator_types_checkboxgroup],
157
+ [plot_gallery, error_markdown]
158
+ )
159
+
160
+ demo.launch()
161
+
162
+ def profile_code():
163
+ """Profile the main functions to find speed bottlenecks."""
164
+ profiler = cProfile.Profile()
165
+ profiler.enable()
166
+
167
+ launch_gradio_app()
168
+
169
+ profiler.disable()
170
+ stats = pstats.Stats(profiler).sort_stats('cumtime')
171
+ stats.print_stats(10)
172
+
173
+ if __name__ == "__main__":
174
+ profile_code()