# Predict Stock Prices Using Machine Learning with ChatGPT in Python Part-3:

## Follow the Instructions from the above Video then go for the Code Input:

``````
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
import pandas as pd
from fyers_apiv3 import fyersModel
from datetime import datetime,timedelta
import matplotlib.pyplot as plt
fyers=fyersModel.FyersModel(client_id=client_id,token=token,log_path='C:/Users/VIKASH/Desktop/fyersv3')
days=1
symbol='NSE:NIFTY50-INDEX'
interval='1'
now=datetime.now()
from_date=now-timedelta(days=days)
from_date=datetime.strftime(from_date,'%Y-%m-%d')
to_date=datetime.strftime(now,'%Y-%m-%d')
print(now,symbol,interval,from_date,to_date)
def historical_data(symbol,interval,from_date,to_date):
data={'symbol':symbol,
'resolution':interval,
'date_format':'1',
'range_from':from_date,
'range_to':to_date,
'cont_flag':'1'
}
response=pd.DataFrame(fyers.history(data=data)['candles'],columns=['date','open','high','low','close','volume'])
return response
df=historical_data(symbol,interval,from_date,to_date)
#set feature and target
X=df[['open']]
y=df['close']
#split data for train and test
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=42)
#Train the Model
model=LinearRegression()
model.fit(X_train,y_train)
#Predict
y_pred=model.predict(X_test)
#Evaluate
mse=mean_squared_error(y_test,y_pred)
print(mse)
new_open_price=X_test
predicted=pd.DataFrame(model.predict(new_open_price))
predicted.plot()
plt.show()
```
```

# Create a FlowChart Diagram using Graphviz in Python:

## Follow the Instructions from the above Video then go for the Code Input:

``````
import graphviz
dot= """
digraph MachineLearning{
node[shape=box,style=filled,fillcolor=white];
Start[shape=square];
End[shape=square];
Start -> "Data Collection" [label="Collect Stock Prices Data"];
"Data Collection" -> "Data Preprocessing" [label="Clean and Normalize Data"];
"Data Preprocessing" -> "Model Training" [label="Train Linear regression Model"];
"Model Training" -> "Model Evaluation" [label="Evaluate Model"];
"Model Evaluation" -> "Prediction" [label="Predicting Future Stock Price"];
"Prediction" ->End;
}
"""
graph=graphviz.Source(dot)
graph.render(filename='ML_FLOWCHART',format='png')
```
```

# Predict Stock Prices using Machine Learning with ChatGPT in Python:

## CMD>>pip installation>> : pip install yfinance and pip install scikit-learn

### Predicting StockPrices based on OHLCV (Open, High, Low, Close, Volume) data from Yahoo Finance using machine learning in Python is a common task in quantitative finance and machine learning. Here's a high-level overview of how you can approach this task: 1. **Data Collection**: Obtain historical OHLCV data for the stock(s) you want to predict. You can use libraries like `yfinance` in Python to fetch this data directly from Yahoo Finance. 2. **Data Preprocessing**: Once you have the data, preprocess it by handling missing values, scaling the features, and splitting it into training and testing sets. You may also want to engineer additional features such as technical indicators (e.g., moving averages, RSI) or lagged variables. 3. **Feature Selection/Engineering**: Select relevant features for your prediction model. This could include not only OHLCV data but also any additional features you engineered in the preprocessing step. 4. **Model Selection**: Choose an appropriate machine learning model for your prediction task. Common choices for stock price prediction include linear regression, support vector machines (SVM), decision trees, random forests, gradient boosting, and neural networks. 5. **Training**: Train your selected model on the training data. You may need to tune hyperparameters using techniques like cross-validation to optimize model performance. 6. **Evaluation**: Evaluate the trained model on the testing data using appropriate evaluation metrics, such as mean squared error (MSE), mean absolute error (MAE), or root mean squared error (RMSE). 7. **Prediction**: Once the model is trained and evaluated, use it to make predictions on new, unseen data. Here's a simplified example using linear regression in Python:

``````
import yfinance as yf
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error

# Fetch historical data from Yahoo Finance

# Preprocess data
# (You may need to handle missing values, scale features, engineer additional features, etc.)

# Split data into features (X) and target (y)
X = data[['Open', 'High', 'Low', 'Close', 'Volume']]
y = data['Close']

# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train a linear regression model
model = LinearRegression()
model.fit(X_train, y_train)

# Evaluate the model
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse}")
```
```