Certainly! Let's enhance your Dash application by integrating real-time data from Yahoo Finance and adding the functionality to select different ticker symbols. We'll achieve this using the yfinance library, which is a convenient way to fetch financial data.
Overview of Enhancements
-
Fetch Real Data from Yahoo Finance:
- Use the
yfinance library to fetch historical stock data.
- Update data processing functions to handle real data.
-
Add Ticker Selection Capability:
- Introduce a dropdown or input field for users to select or input a stock ticker.
- Update the dashboard dynamically based on the selected ticker.
-
Adjust Machine Learning Workflow:
- Re-train the model whenever a new ticker is selected.
- Ensure predictions are made based on the latest selected stock.
Step-by-Step Implementation
1. Install Required Libraries
First, ensure you have the necessary libraries installed. You can install yfinance using pip:
pip install yfinance
2. Updated Code with Yahoo Finance Integration and Ticker Selection
Below is the modified code that incorporates real data from Yahoo Finance and allows users to choose different ticker symbols.
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import pandas as pd
import numpy as np
import yfinance as yf # New import for fetching real data
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from datetime import datetime, timedelta
import warnings
# Suppress specific UserWarnings if needed
warnings.filterwarnings("ignore", message="X does not have valid feature names")
# Function to fetch real data from Yahoo Finance
def fetch_real_data(ticker, start_date, end_date):
try:
stock = yf.download(ticker, start=start_date, end=end_date)
if stock.empty:
raise ValueError("No data found for the given ticker.")
stock.reset_index(inplace=True)
stock.rename(columns={'Adj Close': 'Price'}, inplace=True)
stock['Volume'] = stock['Volume'].astype(int)
return stock
except Exception as e:
print(f"Error fetching data: {e}")
return pd.DataFrame()
# Add technical indicators to the dataframe
def add_technical_indicators(data):
# Simple Moving Averages
data['SMA_10'] = data['Price'].rolling(window=10).mean()
data['SMA_50'] = data['Price'].rolling(window=50).mean()
# Exponential Moving Averages
data['EMA_10'] = data['Price'].ewm(span=10, adjust=False).mean()
data['EMA_50'] = data['Price'].ewm(span=50, adjust=False).mean()
data['EMA_12'] = data['Price'].ewm(span=12, adjust=False).mean()
data['EMA_26'] = data['Price'].ewm(span=26, adjust=False).mean()
# Relative Strength Index
delta = data['Price'].diff()
up = delta.clip(lower=0)
down = -1 * delta.clip(upper=0)
ema_up = up.ewm(com=13, adjust=False).mean()
ema_down = down.ewm(com=13, adjust=False).mean()
rs = ema_up / ema_down
data['RSI'] = 100 - (100 / (1 + rs))
# Moving Average Convergence Divergence
ema_12 = data['EMA_12']
ema_26 = data['EMA_26']
data['MACD'] = ema_12 - ema_26
data['Signal_Line'] = data['MACD'].ewm(span=9, adjust=False).mean()
# Initialize EMA_up and EMA_down for RSI calculation
data['EMA_up'] = ema_up
data['EMA_down'] = ema_down
# Forward-fill and backward-fill missing values
data = data.ffill().bfill()
return data
# Prepare machine learning model for price prediction
def prepare_model(data):
feature_cols = ['Price', 'Volume', 'SMA_10', 'SMA_50', 'EMA_10', 'EMA_50', 'RSI', 'MACD', 'Signal_Line']
X = data[feature_cols]
y = data['Price'].shift(-1) # Predict the next day's price
X = X[:-1]
y = y[:-1]
# Feature Scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Initialize the model
model = RandomForestRegressor(n_estimators=100, random_state=42)
# Cross-validation
cv_scores = cross_val_score(model, X_scaled, y, cv=5, scoring='neg_mean_squared_error')
rmse_scores = np.sqrt(-cv_scores)
print(f"Average CV RMSE Score: {np.mean(rmse_scores):.4f}")
# Fit the model
model.fit(X_scaled, y)
return model, scaler, feature_cols
# Predict future prices
def predict_future(model, scaler, feature_cols, data, num_days=30):
predictions = []
dates = []
new_rows = [] # Collect new rows here
current_data = data.copy().reset_index(drop=True)
# Initialize EMA_up and EMA_down if not present
if 'EMA_up' not in current_data.columns:
current_data['EMA_up'] = 0
if 'EMA_down' not in current_data.columns:
current_data['EMA_down'] = 0
for _ in range(num_days):
last_row = current_data.iloc[-1]
X_new = last_row[feature_cols].values.reshape(1, -1)
X_new_scaled = scaler.transform(X_new)
pred_price = model.predict(X_new_scaled)[0]
# Create new date
new_date = last_row['Date'] + timedelta(days=1)
# Generate random volume for the new day (or use the last known volume)
new_volume = np.random.randint(100, 1000)
# Calculate new technical indicators
new_sma_10 = (last_row['SMA_10'] * 9 + pred_price) / 10
new_sma_50 = (last_row['SMA_50'] * 49 + pred_price) / 50
new_ema_10 = (pred_price - last_row['EMA_10']) * (2 / (10 + 1)) + last_row['EMA_10']
new_ema_50 = (pred_price - last_row['EMA_50']) * (2 / (50 + 1)) + last_row['EMA_50']
new_ema_12 = (pred_price - last_row['EMA_12']) * (2 / (12 + 1)) + last_row['EMA_12']
new_ema_26 = (pred_price - last_row['EMA_26']) * (2 / (26 + 1)) + last_row['EMA_26']
# RSI calculation
delta = pred_price - last_row['Price']
gain = max(delta, 0)
loss = max(-delta, 0)
ema_up = (last_row['EMA_up'] * 13 + gain) / 14
ema_down = (last_row['EMA_down'] * 13 + loss) / 14
if ema_down == 0:
rsi = 100
else:
rs = ema_up / ema_down
rsi = 100 - (100 / (1 + rs))
# MACD and Signal Line
new_macd = new_ema_12 - new_ema_26
new_signal_line = (last_row['Signal_Line'] * 8 + new_macd) / 9
# Append the new data to list
new_data = {
'Date': new_date,
'Price': pred_price,
'Volume': new_volume,
'SMA_10': new_sma_10,
'SMA_50': new_sma_50,
'EMA_10': new_ema_10,
'EMA_50': new_ema_50,
'EMA_12': new_ema_12,
'EMA_26': new_ema_26,
'RSI': rsi,
'MACD': new_macd,
'Signal_Line': new_signal_line,
'EMA_up': ema_up,
'EMA_down': ema_down
}
new_rows.append(new_data)
predictions.append(pred_price)
dates.append(new_date)
# Update current_data with the new row for next iteration
current_data = pd.concat([current_data, pd.DataFrame([new_data])], ignore_index=True)
prediction_df = pd.DataFrame({
'Date': dates,
'Predicted_Price': predictions
})
return prediction_df
# Initialize Dash app
app = dash.Dash(__name__)
app.title = "AI-Powered Financial Analytics Dashboard"
# Define the list of default tickers or allow input
default_ticker = 'AAPL'
# Define the layout of the dashboard
app.layout = html.Div([
html.H1("AI-Powered Financial Analytics Dashboard", style={'textAlign': 'center'}),
# Ticker Selection
html.Div([
html.Label("Select Ticker:", style={'fontSize': 20, 'marginRight': '10px'}),
dcc.Dropdown(
id='ticker-dropdown',
options=[
{'label': 'Apple (AAPL)', 'value': 'AAPL'},
{'label': 'Microsoft (MSFT)', 'value': 'MSFT'},
{'label': 'Google (GOOGL)', 'value': 'GOOGL'},
{'label': 'Amazon (AMZN)', 'value': 'AMZN'},
{'label': 'Tesla (TSLA)', 'value': 'TSLA'},
{'label': 'Facebook (META)', 'value': 'META'},
{'label': 'Netflix (NFLX)', 'value': 'NFLX'},
{'label': 'NVIDIA (NVDA)', 'value': 'NVDA'},
# Add more tickers as needed
],
value=default_ticker,
style={'width': '300px'}
)
], style={'textAlign': 'center', 'padding': '20px'}),
# Graphs
dcc.Loading(
id="loading-1",
type="default",
children=[
html.Div([
dcc.Graph(id='price-chart')
], style={'width': '90%', 'margin': 'auto'}),
html.Div([
dcc.Graph(id='technical-indicators')
], style={'width': '90%', 'margin': 'auto', 'paddingTop': '50px'}),
html.Div([
dcc.Graph(id='volume-chart')
], style={'width': '90%', 'margin': 'auto', 'paddingTop': '50px'}),
html.Div([
html.H3("Predictive Insights", style={'textAlign': 'center'}),
html.P("The model incorporates technical indicators such as Moving Averages, RSI, and MACD to enhance prediction accuracy. A Random Forest Regressor captures complex patterns in the data. For further improvements, consider integrating more advanced machine learning models like Gradient Boosting or Neural Networks, and implementing backtesting strategies to validate model performance.")
], style={'width': '90%', 'margin': 'auto', 'paddingTop': '20px'})
]
)
])
# Callback to update graphs based on selected ticker
@app.callback(
[
Output('price-chart', 'figure'),
Output('technical-indicators', 'figure'),
Output('volume-chart', 'figure')
],
[Input('ticker-dropdown', 'value')]
)
def update_dashboard(selected_ticker):
# Define the date range
end_date = datetime.today()
start_date = end_date - timedelta(days=365) # Last one year data
# Fetch real data
df = fetch_real_data(selected_ticker, start_date, end_date)
if df.empty:
return {}, {}, {}
# Add technical indicators
df = add_technical_indicators(df)
# Prepare machine learning model for price prediction
model, scaler, feature_cols = prepare_model(df)
# Predict future prices
prediction_df = predict_future(model, scaler, feature_cols, df, num_days=30)
# Price Chart
price_fig = {
'data': [
go.Scatter(
x=df['Date'],
y=df['Price'],
mode='lines',
name='Historical Price'
),
go.Scatter(
x=prediction_df['Date'],
y=prediction_df['Predicted_Price'],
mode='lines',
name='Predicted Price',
line=dict(dash='dash')
),
go.Scatter(
x=df['Date'],
y=df['SMA_10'],
mode='lines',
name='SMA 10',
line=dict(color='orange')
),
go.Scatter(
x=df['Date'],
y=df['SMA_50'],
mode='lines',
name='SMA 50',
line=dict(color='magenta')
)
],
'layout': go.Layout(
title=f'Stock Price Over Time for {selected_ticker}',
xaxis={'title': 'Date'},
yaxis={'title': 'Price ($)'},
hovermode='closest',
legend=dict(x=0, y=1)
)
}
# Technical Indicators Chart
technical_fig = {
'data': [
go.Scatter(
x=df['Date'],
y=df['RSI'],
mode='lines',
name='RSI',
yaxis='y2'
),
go.Scatter(
x=df['Date'],
y=df['MACD'],
mode='lines',
name='MACD',
yaxis='y3'
),
go.Scatter(
x=df['Date'],
y=df['Signal_Line'],
mode='lines',
name='Signal Line',
yaxis='y3',
line=dict(dash='dash')
)
],
'layout': go.Layout(
title='Technical Indicators',
xaxis={'title': 'Date'},
yaxis=dict(title='RSI', side='left'),
yaxis2=dict(title='MACD', overlaying='y', side='right'),
yaxis3=dict(title='Signal Line', overlaying='y', side='right', anchor='free', position=0.85),
hovermode='closest',
legend=dict(x=0, y=1)
)
}
# Volume Chart
volume_fig = {
'data': [
go.Bar(
x=df['Date'],
y=df['Volume'],
name='Volume'
)
],
'layout': go.Layout(
title='Trading Volume Over Time',
xaxis={'title': 'Date'},
yaxis={'title': 'Volume'},
hovermode='closest'
)
}
return price_fig, technical_fig, volume_fig
# Run the Dash app
if __name__ == '__main__':
app.run_server(debug=True)
Detailed Explanation
-
Fetching Real Data with yfinance:
fetch_real_data Function: This function takes a ticker symbol, start date, and end date to fetch historical stock data using yfinance. It ensures the data is properly formatted and handles any fetching errors gracefully.
- Date Range: In the callback, we set the date range to the past year (
365 days), but you can adjust this as needed.
-
Technical Indicators:
- The
add_technical_indicators function remains largely the same but now operates on real stock data.
- It computes various indicators like SMA, EMA, RSI, and MACD based on the fetched
Price and Volume.
-
Machine Learning Model:
- The
prepare_model function trains a RandomForestRegressor on the real data.
- It performs feature scaling and cross-validation to evaluate the model's performance.
- The model predicts the next day's price, and we use this to forecast future prices.
-
Predicting Future Prices:
- The
predict_future function generates future price predictions for a specified number of days (num_days=30 by default).
- It simulates future technical indicators based on the predicted prices.
-
Dash Layout Enhancements:
- Ticker Selection: Added a
dcc.Dropdown component allowing users to select from a list of popular ticker symbols. You can expand this list as needed or implement a search/autocomplete feature for a broader selection.
- Dynamic Graphs: Wrapped the graphs inside a
dcc.Loading component to indicate loading when data is being fetched or processed.
- Responsive Design: Ensured that all components are centered and responsive for better user experience.
-
Callbacks:
- The callback
update_dashboard listens to changes in the ticker-dropdown and updates all three graphs (price-chart, technical-indicators, and volume-chart) accordingly.
- This ensures that when a user selects a different ticker, the entire dashboard updates to reflect the new data.
Additional Enhancements (Optional)
-
Dynamic Ticker Input: Instead of a predefined dropdown, allow users to input any ticker symbol, possibly with validation to ensure it's a valid ticker.
# Replace the Dropdown with an Input
html.Div([
html.Label("Enter Ticker Symbol:", style={'fontSize': 20, 'marginRight': '10px'}),
dcc.Input(
id='ticker-input',
value=default_ticker,
type='text',
style={'width': '200px'}
)
], style={'textAlign': 'center', 'padding': '20px'}),
Update the callback to use Input('ticker-input', 'value') instead.
-
Caching: Implement caching mechanisms to store fetched data and models to reduce load times when users switch between frequently selected tickers.
-
Enhanced Error Messages: Provide user-friendly messages if an invalid ticker is entered or if data fetching fails.
-
More Technical Indicators: Incorporate additional indicators like Bollinger Bands, Stochastic Oscillator, etc., for deeper analysis.
-
Model Improvements: Explore more sophisticated machine learning models such as Gradient Boosting Machines, Support Vector Regressors, or even Deep Learning models like LSTM for time-series predictions.
Conclusion
By integrating real data from Yahoo Finance and adding a ticker selection feature, your Dash application becomes much more versatile and useful for users interested in analyzing various stocks. The above modifications provide a solid foundation, and you can continue to build upon them to enrich the dashboard's capabilities.
Feel free to reach out if you have any questions or need further assistance!