import pandas as pd
import numpy as np
from statsmodels.tsa.stattools import adfuller
from numpy import log
import matplotlib.pyplot as plt
import statsmodels.api as sm
import pandas as pd
import matplotlib.pyplot as plt
path ='C:/Users/Usuario/Downloads/PG.csv'
df= pd.read_csv(path)
df.head()
date | open | high | low | close | volume | |
---|---|---|---|---|---|---|
0 | 1970-01-02 | 0.6890 | 0.6937 | 0.6882 | 0.6922 | 1664000 |
1 | 1970-01-05 | 0.6922 | 0.6969 | 0.6882 | 0.6953 | 1036800 |
2 | 1970-01-06 | 0.6937 | 0.6937 | 0.6874 | 0.6922 | 960000 |
3 | 1970-01-07 | 0.6937 | 0.7048 | 0.6937 | 0.7032 | 1420800 |
4 | 1970-01-08 | 0.7032 | 0.7142 | 0.7016 | 0.7110 | 1062400 |
df_final=df
df[['value']]=df[['close']]
df_final.head()
date | open | high | low | close | volume | value | |
---|---|---|---|---|---|---|---|
0 | 1970-01-02 | 0.6890 | 0.6937 | 0.6882 | 0.6922 | 1664000 | 0.6922 |
1 | 1970-01-05 | 0.6922 | 0.6969 | 0.6882 | 0.6953 | 1036800 | 0.6953 |
2 | 1970-01-06 | 0.6937 | 0.6937 | 0.6874 | 0.6922 | 960000 | 0.6922 |
3 | 1970-01-07 | 0.6937 | 0.7048 | 0.6937 | 0.7032 | 1420800 | 0.7032 |
4 | 1970-01-08 | 0.7032 | 0.7142 | 0.7016 | 0.7110 | 1062400 | 0.7110 |
last_=df_final.iloc[-1]
print(last_)
date 2023-03-17 open 142.5 high 143.39 low 141.53 close 142.93 volume 14390684 value 142.93 Name: 13420, dtype: object
result = adfuller(df_final.value.dropna())
print('ADF Statistic: %f' % result[0])
print('p-value: %f' % result[1])
ADF Statistic: 2.477690 p-value: 0.999042
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
# Load the data into a Pandas dataframe
df = pd.read_csv('C:/Users/Usuario/Downloads/PG.csv', parse_dates=['date'])
# Define the degree of the polynomial
degree = 3
# Create polynomial features from the date column
poly_features = PolynomialFeatures(degree=degree)
X = poly_features.fit_transform(df['date'].astype('int64').values.reshape(-1, 1))
y = df['close']
# Create a linear regression model and fit it to the data
model = LinearRegression()
model.fit(X, y)
# Make predictions for the next 20 years
future_dates = pd.date_range(start='2023-03-19', end='2043-03-19', freq='B')
X_future = poly_features.transform(future_dates.astype('int64').values.reshape(-1, 1))
y_pred = model.predict(X_future)
# Plot the actual and predicted values
plt.plot(df['date'], df['close'], label='Actual')
plt.plot(future_dates, y_pred, label='Predicted')
plt.legend()
plt.show()
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
# Load the data into a Pandas dataframe
df = pd.read_csv('C:/Users/Usuario/Downloads/PG.csv', parse_dates=['date'])
# Create polynomial features
poly = PolynomialFeatures(degree=2)
X_poly = poly.fit_transform(df['date'].values.reshape(-1, 1))
# Create a linear regression model and fit it to the data
model = LinearRegression()
model.fit(X_poly, df['close'])
# Make predictions for the next 20 years
future_dates = pd.date_range(start='2023-03-19', end='2043-03-19', freq='B')
X_future_poly = poly.transform(future_dates.astype('int64').values.reshape(-1, 1))
y_pred = model.predict(X_future_poly)
# Plot the actual and predicted values
plt.plot(df['date'], df['close'], label='Actual')
plt.plot(future_dates, y_pred, label='Predicted')
plt.legend()
plt.show()
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Load the data into a Pandas dataframe
df = pd.read_csv('C:/Users/Usuario/Downloads/PG.csv', parse_dates=['date'])
# Calculate the annualized return and standard deviation of the stock price
returns = df['close'].pct_change().dropna()
mu = returns.mean() * 252
sigma = returns.std() * 252 ** 0.5
# Calculate the projected future stock price
current_price = df['close'].iloc[-1]
years_to_project = 20
future_price = current_price * (1 + 0.05) ** years_to_project
# Plot the historical stock prices
fig, ax = plt.subplots()
ax.plot(df['date'], df['close'], label='Historical Prices')
# Plot the projected future stock price
ax.scatter(pd.to_datetime(f'{df["date"].dt.year.max()+years_to_project}-01-01'), future_price,
s=100, color='red', marker='*', label='Projected Future Price')
# Add labels and legend
ax.set_xlabel('Date')
ax.set_ylabel('Price ($)')
ax.set_title('Historical and Projected Future Stock Prices')
ax.legend()
plt.show()
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Load the data into a Pandas dataframe
df = pd.read_csv('C:/Users/Usuario/Downloads/PG.csv', parse_dates=['date'])
# Calculate the annualized return and standard deviation of the stock price
returns = df['close'].pct_change().dropna()
mu = returns.mean() * 252
sigma = returns.std() * 252 ** 0.5
# Calculate the projected future stock price and growth rate
current_price = df['close'].iloc[-1]
years_to_project = 20
future_price = current_price * (1 + 0.05) ** years_to_project
growth_rate = (future_price / current_price) ** (1 / years_to_project) - 1
# Plot the historical stock prices
fig, ax = plt.subplots()
ax.plot(df['date'], df['close'], label='Historical Prices')
# Plot the projected future stock price and growth rate
future_date = pd.to_datetime(f'{df["date"].dt.year.max()+years_to_project}-01-01')
ax.scatter(future_date, future_price, s=100, color='red', marker='*', label='Projected Future Price')
ax.plot([df['date'].max(), future_date], [current_price, future_price], linestyle='--', label='Projected Growth Rate')
# Add labels and legend
ax.set_xlabel('Date')
ax.set_ylabel('Price ($)')
ax.set_title('Historical and Projected Future Stock Prices')
ax.legend()
plt.show()
import pandas as pd
# Load the data into a Pandas dataframe
df = pd.read_csv('C:/Users/Usuario/Downloads/PG.csv', parse_dates=['date'])
# Calculate the annualized return and standard deviation of the stock price
returns = df['close'].pct_change().dropna()
mu = returns.mean() * 252
sigma = returns.std() * 252 ** 0.5
# Calculate the projected future stock price
current_price = df['close'].iloc[-1]
years_to_project = 20
future_price = current_price * (1 + 0.05) ** years_to_project
print(f"The projected stock price for {years_to_project} years from now is ${future_price:.2f}")
The projected stock price for 20 years from now is $379.24
While it's difficult to provide a projection that would work for predicting stock prices in the distant future, one approach you could try is to use a more conservative assumption for the growth rate of the stock price.
For example, you could assume that the stock price will grow at a constant rate of 5% per year, which is a common assumption used in financial modeling. With this assumption, you could project the future stock price as follows: