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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 17 |
+
COMPANY_TICKERS = {
|
| 18 |
+
'Apple': 'AAPL',
|
| 19 |
+
'Amazon': 'AMZN',
|
| 20 |
+
'Google Class A': 'GOOGL',
|
| 21 |
+
'NVIDIA': 'NVDA',
|
| 22 |
+
'Tesla': 'TSLA',
|
| 23 |
+
'Exxon Mobil': 'XOM',
|
| 24 |
+
'Home Depot': 'HD',
|
| 25 |
+
'Pfizer': 'PFE',
|
| 26 |
+
'Takeda Pharma': 'TAK',
|
| 27 |
+
'Energy Transfer LP': 'ET',
|
| 28 |
+
'Procter & Gamble': 'PG',
|
| 29 |
+
'PepsiCo': 'PEP',
|
| 30 |
+
'HCA Healthcare': 'HCA',
|
| 31 |
+
'FedEx': 'FDX',
|
| 32 |
+
'AutoZone': 'AZO',
|
| 33 |
+
'Tractor Supply': 'TSCO',
|
| 34 |
+
'Kinder Morgan': 'KMI',
|
| 35 |
+
'Eastman Chemical': 'EMN',
|
| 36 |
+
'Delek US Holdings': 'DK',
|
| 37 |
+
'MPLX LP': 'MPLX',
|
| 38 |
+
'i3 Verticals': 'IIIV',
|
| 39 |
+
'Forward Air International': 'FWRD'
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
# Cache with 1-day TTL
|
| 43 |
+
cache = TTLCache(maxsize=100, ttl=86400)
|
| 44 |
+
|
| 45 |
+
@cached(cache)
|
| 46 |
+
def fetch_historical_data(ticker, start_date, end_date):
|
| 47 |
+
"""Fetch historical stock data and market cap from Yahoo Finance."""
|
| 48 |
+
try:
|
| 49 |
+
data = yf.download(ticker, start=start_date, end=end_date)
|
| 50 |
+
if data.empty:
|
| 51 |
+
raise ValueError(f"No data found for ticker {ticker}")
|
| 52 |
+
info = yf.Ticker(ticker).info
|
| 53 |
+
market_cap = info.get('marketCap', 'N/A')
|
| 54 |
+
if market_cap != 'N/A':
|
| 55 |
+
market_cap = market_cap / 1e9 # Convert to billions
|
| 56 |
+
return data, market_cap
|
| 57 |
+
except Exception as e:
|
| 58 |
+
print(f"Error fetching data for {ticker}: {e}")
|
| 59 |
+
return None, 'N/A'
|
| 60 |
+
|
| 61 |
+
def calculate_trailing_annual_returns(data):
|
| 62 |
+
"""Calculate trailing annual returns from stock data using log returns."""
|
| 63 |
+
data['Daily Return'] = data['Close'].pct_change()
|
| 64 |
+
data['Log Return'] = np.log1p(data['Daily Return'])
|
| 65 |
+
data['Annual Log Return'] = data['Log Return'].rolling(window=252).sum()
|
| 66 |
+
data['Annual Return'] = np.expm1(data['Annual Log Return'])
|
| 67 |
+
return data['Annual Return']
|
| 68 |
+
|
| 69 |
+
def plot_to_image(plt, title, market_cap):
|
| 70 |
+
"""Convert plot to a PIL Image object."""
|
| 71 |
+
plt.title(title, fontsize=FONT_SIZE + 1, pad=40)
|
| 72 |
+
plt.suptitle(f'Market Cap: ${market_cap:.2f} Billion', fontsize=FONT_SIZE - 5, y=0.92, weight='bold')
|
| 73 |
+
plt.legend(fontsize=FONT_SIZE)
|
| 74 |
+
plt.xlabel('Date', fontsize=FONT_SIZE)
|
| 75 |
+
plt.ylabel('', fontsize=FONT_SIZE)
|
| 76 |
+
plt.grid(True)
|
| 77 |
+
plt.xticks(rotation=45, ha='right', fontsize=FONT_SIZE)
|
| 78 |
+
plt.yticks(fontsize=FONT_SIZE)
|
| 79 |
+
plt.tight_layout(rect=[0, 0, 1, 0.95])
|
| 80 |
+
|
| 81 |
+
buf = io.BytesIO()
|
| 82 |
+
plt.savefig(buf, format='png', dpi=400)
|
| 83 |
+
plt.close()
|
| 84 |
+
buf.seek(0)
|
| 85 |
+
return Image.open(buf)
|
| 86 |
+
|
| 87 |
+
def plot_indicator(data, company_name, ticker, indicator, market_cap):
|
| 88 |
+
"""Plot selected technical indicator for a single company."""
|
| 89 |
+
plt.figure(figsize=(16, 10))
|
| 90 |
+
if indicator == "Trailing Annual Returns":
|
| 91 |
+
annual_returns = calculate_trailing_annual_returns(data)
|
| 92 |
+
plt.plot(annual_returns.index, annual_returns, label='Trailing Annual Return', alpha=0.8, linewidth=1.5)
|
| 93 |
+
plt.ylabel('Trailing Annual Return', fontsize=FONT_SIZE)
|
| 94 |
+
plt.ylim(annual_returns.min(), annual_returns.max())
|
| 95 |
+
elif indicator == "SMA":
|
| 96 |
+
sma_55 = data['Close'].rolling(window=55).mean()
|
| 97 |
+
sma_200 = data['Close'].rolling(window=200).mean()
|
| 98 |
+
plt.plot(data.index, data['Close'], label='Close')
|
| 99 |
+
plt.plot(data.index, sma_55, label='55-day SMA')
|
| 100 |
+
plt.plot(data.index, sma_200, label='200-day SMA')
|
| 101 |
+
plt.ylabel('Price', fontsize=FONT_SIZE)
|
| 102 |
+
elif indicator == "MACD":
|
| 103 |
+
exp1 = data['Close'].ewm(span=12, adjust=False).mean()
|
| 104 |
+
exp2 = data['Close'].ewm(span=26, adjust=False).mean()
|
| 105 |
+
macd = exp1 - exp2
|
| 106 |
+
signal = macd.ewm(span=9, adjust=False).mean()
|
| 107 |
+
plt.plot(data.index, macd, label='MACD')
|
| 108 |
+
plt.plot(data.index, signal, label='Signal Line')
|
| 109 |
+
plt.bar(data.index, macd - signal, label='MACD Histogram')
|
| 110 |
+
plt.ylabel('MACD', fontsize=FONT_SIZE)
|
| 111 |
+
|
| 112 |
+
return plot_to_image(plt, f'{company_name} ({ticker}) {indicator}', market_cap)
|
| 113 |
+
|
| 114 |
+
def plot_indicators(company_names, indicator_types):
|
| 115 |
+
"""Plot the selected indicators for the selected companies."""
|
| 116 |
+
images = []
|
| 117 |
+
if len(company_names) > 1 and len(indicator_types) > 1:
|
| 118 |
+
return None, "You can only select one indicator when selecting multiple companies."
|
| 119 |
+
|
| 120 |
+
with ThreadPoolExecutor() as executor:
|
| 121 |
+
future_to_company = {
|
| 122 |
+
executor.submit(fetch_historical_data, COMPANY_TICKERS[company], '2000-01-01', datetime.now().strftime('%Y-%m-%d')): (company, indicator)
|
| 123 |
+
for company in company_names
|
| 124 |
+
for indicator in indicator_types
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
for future in as_completed(future_to_company):
|
| 128 |
+
company, indicator = future_to_company[future]
|
| 129 |
+
ticker = COMPANY_TICKERS[company]
|
| 130 |
+
data, market_cap = future.result()
|
| 131 |
+
if data is None:
|
| 132 |
+
continue
|
| 133 |
+
images.append(plot_indicator(data, company, ticker, indicator, market_cap))
|
| 134 |
+
|
| 135 |
+
return images, ""
|
| 136 |
+
|
| 137 |
+
def select_all_indicators(select_all):
|
| 138 |
+
"""Select or deselect all indicators based on the select_all flag."""
|
| 139 |
+
indicators = ["SMA", "MACD", "Trailing Annual Returns"]
|
| 140 |
+
return indicators if select_all else []
|
| 141 |
+
|
| 142 |
+
def launch_gradio_app():
|
| 143 |
+
"""Launch the Gradio app for interactive plotting."""
|
| 144 |
+
company_choices = list(COMPANY_TICKERS.keys())
|
| 145 |
+
indicators = ["SMA", "MACD", "Trailing Annual Returns"]
|
| 146 |
+
|
| 147 |
+
def fetch_and_plot(company_names, indicator_types):
|
| 148 |
+
images, error_message = plot_indicators(company_names, indicator_types)
|
| 149 |
+
if error_message:
|
| 150 |
+
return [None] * len(indicator_types), error_message
|
| 151 |
+
return images, ""
|
| 152 |
+
|
| 153 |
+
with gr.Blocks() as demo:
|
| 154 |
+
company_checkboxgroup = gr.CheckboxGroup(choices=company_choices, label="Select Companies")
|
| 155 |
+
|
| 156 |
+
select_all_checkbox = gr.Checkbox(label="Select All Indicators", value=False, interactive=True)
|
| 157 |
+
indicator_types_checkboxgroup = gr.CheckboxGroup(choices=indicators, label="Select Technical Indicators")
|
| 158 |
+
select_all_checkbox.change(select_all_indicators, inputs=select_all_checkbox, outputs=indicator_types_checkboxgroup)
|
| 159 |
+
|
| 160 |
+
plot_gallery = gr.Gallery(label="Indicator Plots")
|
| 161 |
+
error_markdown = gr.Markdown()
|
| 162 |
+
|
| 163 |
+
gr.Interface(
|
| 164 |
+
fetch_and_plot,
|
| 165 |
+
[company_checkboxgroup, indicator_types_checkboxgroup],
|
| 166 |
+
[plot_gallery, error_markdown]
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
demo.launch()
|
| 170 |
+
|
| 171 |
+
def profile_code():
|
| 172 |
+
"""Profile the main functions to find speed bottlenecks."""
|
| 173 |
+
profiler = cProfile.Profile()
|
| 174 |
+
profiler.enable()
|
| 175 |
+
|
| 176 |
+
launch_gradio_app()
|
| 177 |
+
|
| 178 |
+
profiler.disable()
|
| 179 |
+
stats = pstats.Stats(profiler).sort_stats('cumtime')
|
| 180 |
+
stats.print_stats(10)
|
| 181 |
+
|
| 182 |
+
if __name__ == "__main__":
|
| 183 |
+
profile_code()
|