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
from sklearn.linear_model import LinearRegression
from datetime import datetime, timedelta

# Generate synthetic financial data
def generate_data(num_days=100):
    np.random.seed(0)
    dates = [datetime.today() - timedelta(days=x) for x in range(num_days)][::-1]
    prices = np.cumsum(np.random.randn(num_days)) + 100  # Random walk around 100
    volume = np.random.randint(100, 1000, size=num_days)
    data = pd.DataFrame({
        'Date': dates,
        'Price': prices,
        'Volume': volume
    })
    return data

# Prepare machine learning model for price prediction
def prepare_model(data):
    X = data[['Days']]
    y = data['Price']
    model = LinearRegression()
    model.fit(X, y)
    return model

# Predict future prices
def predict_future(model, last_day, num_days=30):
    future_days = np.array([last_day + i for i in range(1, num_days + 1)]).reshape(-1, 1)
    predictions = model.predict(future_days)
    future_dates = [df['Date'].max() + timedelta(days=i) for i in range(1, num_days + 1)]
    prediction_df = pd.DataFrame({
        'Date': future_dates,
        'Predicted_Price': predictions
    })
    return prediction_df

# Prepare data
df = generate_data()
df['Days'] = (df['Date'] - df['Date'].min()).dt.days  # Add 'Days' column to df

# Prepare machine learning model for price prediction
model = prepare_model(df)

# Predict future prices
last_day = df['Days'].max()  # Now 'Days' column exists in df
prediction_df = predict_future(model, last_day)

# Initialize Dash app
app = dash.Dash(__name__)
app.title = "Financial Analytics Dashboard"

# Layout of the dashboard
app.layout = html.Div([
    html.H1("AI-Powered Financial Analytics Dashboard", style={'textAlign': 'center'}),
    
    html.Div([
        dcc.Graph(
            id='price-chart',
            figure={
                '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')
                    )
                ],
                'layout': go.Layout(
                    title='Stock Price Over Time',
                    xaxis={'title': 'Date'},
                    yaxis={'title': 'Price ($)'},
                    hovermode='closest'
                )
            }
        )
    ], style={'width': '80%', 'margin': 'auto'}),
    
    html.Div([
        dcc.Graph(
            id='volume-chart',
            figure={
                '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'
                )
            }
        )
    ], style={'width': '80%', 'margin': 'auto', 'paddingTop': '50px'}),
    
    html.Div([
        html.H3("Predictive Insights", style={'textAlign': 'center'}),
        html.P("The model used here is a simple Linear Regression to predict future stock prices based on historical data. For more accurate predictions, consider using more advanced models and incorporating additional features.")
    ], style={'width': '80%', 'margin': 'auto', 'paddingTop': '20px'})
])

# Run the Dash app
if __name__ == '__main__':
    app.run_server(debug=True)

UserWarning: X does not have valid feature names, but LinearRegression was fitted with feature names
  warnings.warn(