R Squared Machine Learning Metrics from Scratch in Python:
VIDEO
VIDEO
import numpy as np
def r2_squared(y_test,y_pred):
y_mean=np.mean(y_test)
tss=np.sum((y_test-y_mean)**2)
rss=np.sum((y_test-y_pred)**2)
rt=1-(rss/tss)
return rt
print(r2_squared(y_test,y_pred))
R-squared (R²) Metrics to Evaluate the Performance of Machine Learning Models in Python:
VIDEO
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 r2_score
import pandas as pd
from fyers_apiv3 import fyersModel
from datetime import datetime,timedelta
import matplotlib.pyplot as plt
client_id=open('C:/Users/VIKASH/Desktop/fyersv3/app_id.txt','r').read()
token=open('C:/Users/VIKASH/Desktop/fyersv3/access_token.txt','r').read().strip()
fyers=fyersModel.FyersModel(client_id=client_id,token=token,log_path='C:/Users/.../Desktop/fyersv3')
days=1
symbol='NSE:NIFTYBANK-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)
#feature and target
X=df[['open']]
y=df['close']
#test and train
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2)
#Train Model
model=LinearRegression()
model.fit(X_train,y_train)
#predict
y_pred=model.predict(X_test)
print(r2_score(y_test,y_pred))
print(X_test.iloc[-1],y_test.iloc[-1],y_pred[-1])
plt.figure(figsize=(10,5))
plt.scatter(X_test,y_test,color='blue',label='Actual')
plt.plot(X_test,y_pred,color='red',label='Predicted')
plt.xlabel('open')
plt.ylabel('close')
plt.title('Actual V/s Predicted')
plt.legend()
plt.savefig('metrics.png')
plt.show()
Predict Stock Close Price Based on Open Price Using Machine Learning in Python:
Predict Stock Prices Using Machine Learning with ChatGPT in Python Part-2:
VIDEO
Predict Stock Prices Using Machine Learning with ChatGPT in Python Part-3:
VIDEO
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
client_id=open('C:/Users/VIKASH/Desktop/fyersv3/app_id.txt','r').read()
token=open('C:/Users/VIKASH/Desktop/fyersv3/access_token.txt','r').read().strip()
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:
VIDEO
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:
VIDEO
Follow the Instructions from the above Video then go for the Code Input:
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
data = yf.download('AAPL', start='2020-01-01', end='2021-01-01')
# 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}")
keep
in mind that this is a simplified example, and real-world stock price prediction tasks can be much more complex. You may need to experiment with different features, models, and hyperparameters to improve prediction accuracy. Additionally, predicting stock prices accurately is notoriously difficult due to the inherent unpredictability of financial markets.