File size: 3,019 Bytes
7930473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import gradio as gr

# Define stock tickers
stock_tickers = ["AAPL", "GOOGL", "MSFT", "AMZN", "TSLA", "FB", "NFLX", "NVDA", "BRK.B", "DIS"]

def fetch_data(ticker, start_date, end_date):
    """Fetch historical stock data."""
    data = yf.download(ticker, start=start_date, end=end_date)
    return data

def train_model(data):
    """Train a Linear Regression model on the stock data."""
    data['Date'] = data.index.map(pd.Timestamp.timestamp)
    X = data[['Date']]
    y = data['Close']

    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
    model = LinearRegression()
    model.fit(X_train, y_train)

    return model

def predict_price(model, today):
    """Predict the stock price using the trained model."""
    prediction = model.predict(np.array([[pd.Timestamp(today).timestamp()]]))
    return prediction[0]

def stock_analysis(ticker, start_date, end_date):
    """Perform stock analysis and predictions."""
    # Fetch data
    data = fetch_data(ticker, start_date, end_date)
    
    # Train model
    model = train_model(data)
    
    # Calculate statistics
    today = pd.Timestamp.today()
    predicted_price = predict_price(model, today)
    
    percentage_change = ((data['Close'][-1] - data['Close'][0]) / data['Close'][0]) * 100
    highest_value = data['Close'].max()
    lowest_value = data['Close'].min()
    
    # Create a plot for historical and predicted performance
    plt.figure(figsize=(12, 6))
    plt.plot(data.index, data['Close'], label='Historical Prices', color='blue')
    future_dates = pd.date_range(start=today, periods=90, freq='D')
    future_prices = [predict_price(model, date) for date in future_dates]
    plt.plot(future_dates, future_prices, label='Predicted Prices', color='orange')
    plt.title(f"{ticker} Stock Price Prediction")
    plt.xlabel("Date")
    plt.ylabel("Price")
    plt.legend()
    plt.grid()
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.savefig('stock_analysis.png')
    
    return (
        predicted_price,
        percentage_change,
        highest_value,
        lowest_value,
        'Buy' if predicted_price > data['Close'][-1] else 'Sell',
        'stock_analysis.png'
    )

# Gradio UI
inputs = [
    gr.inputs.Dropdown(choices=stock_tickers, label="Select Stock Ticker"),
    gr.inputs.Date(label="Start Date"),
    gr.inputs.Date(label="End Date"),
]

outputs = [
    gr.outputs.Textbox(label="Predicted Price"),
    gr.outputs.Textbox(label="Percentage Change (%)"),
    gr.outputs.Textbox(label="Highest Price"),
    gr.outputs.Textbox(label="Lowest Price"),
    gr.outputs.Textbox(label="Recommendation (Buy/Sell)"),
    gr.outputs.Image(label="Stock Price Analysis")
]

gr.Interface(fn=stock_analysis, inputs=inputs, outputs=outputs, title="Stock Price Predictor").launch()