<jupyter_start><jupyter_text>The dataset has different variables, namely: High, Low, Open, Close, Volume and Adj Close. Also, we have the Date set as our index, which is highly significant in any timeseries problem.- Variables Open and Close show the starting and final price at which the stock is traded on a particular day.- Variables High, Low represent the maximum and minimum price of the stock for the day.- Volume is the number of shares bought or sold in the day.- While the Adj Close is the adjusted closing price of the stock. It alters the stock’s close price after accounting for any corporate actions. It’ll give us a better idea about the overall value of the stock and help make better decisions.<jupyter_code>data_df=data_df.drop(['Date','Adj Close'], axis=1)
data_df.head(10)
plt.plot(data_df['Close'],color = 'blue', label = 'Closing price')
plt.title('AAPL Stock Price')
plt.xlabel('Time')
plt.ylabel('Stock Price')
plt.legend()
plt.show()
data_df.shape
ma100=data_df.Close.rolling(100).mean()
ma100
plt.figure(figsize=(12,6))
plt.plot(data_df.Close)
plt.plot(ma100,'r')
ma200=data_df.Close.rolling(200).mean()
ma200
plt.figure(figsize=(12,6))
plt.plot(data_df.Close)
plt.plot(ma100,'r')
plt.plot(ma200,'g')
#split data into train and test

data_training=pd.DataFrame(data_df['Close'][0:int(len(data_df)*0.70)])
data_testing=pd.DataFrame(data_df['Close'][int(len(data_df)*0.70):int(len(data_df))])

print(data_training.shape)
print(data_testing.shape)
data_training.head()
data_testing.head()
scaler = MinMaxScaler(feature_range=(0,1))
data_training_array=scaler.fit_transform(data_training)
data_training_array
data_training_array.shape
#Now we have to divide training data into x_train and y_train
x_train=[]
y_train=[]

for i in range(60,data_training_array.shape[0]):
    x_train.append(data_training_array[i-60:i])
    y_train.append(data_training_array[i,0])
    
x_train,y_train=np.array(x_train),np.array(y_train)
x_train
x_train.shape
#Model Building
from keras.layers import Dense,Dropout,LSTM
from keras.models import Sequential
model=Sequential()
model.add(LSTM(units=50,activation='relu',return_sequences=True,input_shape=(x_train.shape[1],1)))
model.add(Dropout(0.2))
model.add(LSTM(units=60,activation='relu',return_sequences=True))
model.add(Dropout(0.3))
model.add(LSTM(units=80,activation='relu',return_sequences=True))
model.add(Dropout(0.4))
model.add(LSTM(units=120,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(units=1))

model.summary()
model.compile(optimizer='adam',loss='mean_squared_error')
model.fit(x_train,y_train,epochs=50)
model.save('keras_model.h5')
data_testing.head()
past_100_days=data_training.tail(60)
final_df=past_100_days.append(data_testing,ignore_index=True)
final_df.head()
input_data=scaler.fit_transform(final_df)
input_data
input_data.shape
x_test=[]
y_test=[]

for i in range(60,input_data.shape[0]):
    x_test.append(input_data[i-60:i])
    y_test.append(input_data[i,0])

x_test,y_test=np.array(x_test),np.array(y_test)
print(x_test.shape)
print(y_test.shape)
#Making Predictions

y_prediction=model.predict(x_test)
y_test
y_prediction
scaler.scale_
scale_factor=1/0.00626135
y_prediction=y_prediction*scale_factor
y_test=y_test*scale_factor
plt.figure(figsize=(12,6))
plt.plot(y_test,'b',label="Original Price")
plt.plot(y_prediction,'r',label="Predicted Price")
plt.xlabel("Time")
plt.ylabel("Price")
plt.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>Sentiment Analysis   Gathering dataset<jupyter_code>!pip install nltk
df_sentiment = pd.read_csv("india-news-headlines.csv")
df_sentiment.head()<jupyter_output><empty_output><jupyter_text>Importing necessary modules<jupyter_code>from nltk.sentiment.vader import SentimentIntensityAnalyzer
import nltk
nltk.downloader.download('vader_lexicon')<jupyter_output>[nltk_data] Downloading package vader_lexicon to
[nltk_data]     C:\Users\Adarsh\AppData\Roaming\nltk_data...<jupyter_text>Predicting if a news headline is positive , negative or neutral<jupyter_code>vader = SentimentIntensityAnalyzer()

sentiment = df_sentiment['headline_text'].apply(vader.polarity_scores).tolist()
sentiment_score = pd.DataFrame(sentiment)

df_sentiment = df_sentiment.join(sentiment_score, rsuffix='_right')


df_sentiment.head()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13137665967854648, 'fraction_numerical': 0.023526671325413463, 'mean_word_length': 8.416666666666666, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '645634', 'license': 'MIT', 'n_tokens_mistral': 1649, 'n_tokens_neox': 1557, 'n_words': 287, 'path': 'LSTM Model.ipynb', 'repo_name': 'theAdarshSrivastava/LSTM_stock_prediction-and-sentimental_analysis', 'size': '4293'}