File size: 4,360 Bytes
a2d3623
1e716d6
38f860b
1e716d6
ed74d2e
 
882c412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e716d6
f2567ce
a2d3623
 
aadb13b
87d437c
 
aadb13b
a2d3623
87d437c
ed74d2e
a2d3623
ed74d2e
a2d3623
aadb13b
87d437c
 
1c9bac5
87d437c
 
aadb13b
 
 
 
ed74d2e
 
87d437c
ed74d2e
 
87d437c
ed74d2e
 
87d437c
ed74d2e
 
87d437c
ed74d2e
 
 
a2d3623
ed74d2e
 
 
f2567ce
ed74d2e
 
87d437c
ed74d2e
a2d3623
 
 
 
ed74d2e
a2d3623
 
ddd2d15
 
 
f1e8a20
a2d3623
882c412
 
a2d3623
 
 
ed74d2e
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
92
93
94
95
96
97
98
99
100
101
102
103
import gradio as gr
import yfinance as yf
import pandas as pd
from sklearn.linear_model import LinearRegression
import plotly.graph_objects as go

markdown_content = """
# Asset Price Prediction Tool

## Introduction
This tool uses historical stock price data to predict future prices. It's designed to provide insights into potential price trends based on past performance.

## How to Use
1. **Enter the Ticker Symbol:** Input the stock ticker (e.g., 'AAPL' for Apple Inc.).
2. **Select Start and End Dates:** Choose the historical data range for analysis. Dates must be entered in the format YYYY-MM-DD (e.g., 2023-01-01).
3. **Set Prediction Days:** Decide how many days into the future you want to predict.
4. **Submit:** Click 'Run' to view the predictions.

## How It Works
- **Data Fetching:** The tool fetches historical closing prices of the specified asset using `yfinance` for the date range you provide.
- **Model Training:** It then trains a linear regression model on this data. The model learns the relationship between dates and closing prices during this period.
- **Making Predictions:** Based on the learned relationship, the model attempts to predict future prices for the number of days you specified.

## Understanding Linear Regression
- Linear regression is a statistical method that models the relationship between a dependent variable and one or more independent variables.
- In this tool, the dependent variable is the asset's price, and the independent variable is time (dates).
- The model assumes a linear relationship (a straight line trend) between dates and prices.
- It's important to note that this method works best when the relationship between the data points is linear and may not capture complex market dynamics.

## Interpreting Data
- **Historical Prices:** Displayed as a solid blue line, representing actual past closing prices.
- **Predicted Prices:** Shown as a solid red line, indicating the model's predictions.
- **Limitations:** The predictions are based on historical trends and do not account for unforeseen market events or changes in market conditions. They should be used as a guideline rather than definitive financial advice.

Remember, investing in the stock market involves risks, and past performance is not indicative of future results.
"""

def train_predict_wrapper(ticker, start_date, end_date, prediction_days):
    # Download asset data
    data = yf.download(ticker, start=start_date, end=end_date)
    data = data["Close"]

    # Convert index to Unix timestamp (seconds)
    data.index = (data.index - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s')

    # Train linear regression model
    X = data.index.values[:-prediction_days].reshape(-1, 1)
    y = data.values[:-prediction_days]
    model = LinearRegression()
    model.fit(X, y)

    # Prepare data for prediction
    last_timestamp = data.index[-1]
    future_timestamps = pd.date_range(start=pd.to_datetime(last_timestamp, unit='s'), 
                                      periods=prediction_days, freq='D')
    future_timestamps = (future_timestamps - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s')
    X_future = future_timestamps.values.reshape(-1, 1)

    # Predict future prices
    predicted_prices = model.predict(X_future)

    # Prepare data for plotting
    historical_prices = go.Scatter(
        x=pd.to_datetime(data.index, unit='s'),
        y=data.values,
        mode="lines",
        name="Historical Prices"
    )
    predicted_prices_trace = go.Scatter(
        x=pd.to_datetime(future_timestamps, unit='s'),
        y=predicted_prices,
        mode="lines",
        name="Predicted Prices"
    )

    # Plot data
    fig = go.Figure()
    fig.add_trace(historical_prices)
    fig.add_trace(predicted_prices_trace)
    fig.update_layout(
        title="Asset Price Prediction",
        xaxis_title="Date",
        yaxis_title="Price",
        legend_title_text="Data"
    )

    return fig

# Define Gradio interface
interface = gr.Interface(
    fn=train_predict_wrapper,
    inputs=[
        gr.Textbox(label="Ticker Symbol"),
        gr.Textbox(label="Start Date (YYYY-MM-DD)"),
        gr.Textbox(label="End Date (YYYY-MM-DD)"),
        gr.Slider(minimum=1, maximum=365, step=1, label="Prediction Days"),
    ],
    outputs="plot",
    description=markdown_content
)

# Launch the app
interface.launch()