Importing Libraries

In [1]:
import numpy as np
import pandas as pd
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential
import matplotlib.pyplot as plt
import time
import datetime as dt
import urllib.request, json
import os
from pandas_datareader import data
import tweepy
from textblob import TextBlob
import re
Using TensorFlow backend.

Getting data using Alpha Vantage API

In [2]:
data_source = 'alphavantage'

if data_source == 'alphavantage':
    # ====================== Loading Data from Alpha Vantage ==================================

    api_key = '7TONQ8CM5PXZ4YEO'

    # TCS stock market prices
    ticker = "TCS"

    # JSON file with all the stock market data for TCS
    url_string = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=%s&outputsize=full&apikey=%s"%(ticker,api_key)

    # Save data to this file
    file_to_save = 'stock_market_data-%s.csv'%ticker

    # If you haven't already saved data,
    # Go ahead and grab the data from the url
    # And store date, low, high, volume, close, open values to a Pandas DataFrame
    if not os.path.exists(file_to_save):
        with urllib.request.urlopen(url_string) as url:
            data = json.loads(url.read().decode())
            # extract stock market data
            data = data['Time Series (Daily)']
            df = pd.DataFrame(columns=['Date','Low','High','Close','Open'])
            for k,v in data.items():
                date = dt.datetime.strptime(k, '%Y-%m-%d')
                data_row = [date.date(),float(v['3. low']),float(v['2. high']),
                            float(v['4. close']),float(v['1. open'])]
                df.loc[-1,:] = data_row
                df.index = df.index + 1
        print('Data saved to : %s'%file_to_save)        
        df.to_csv(file_to_save)

    # If the data is already there, just load it from the CSV
    else:
        print('File already exists. Loading data from CSV')
        df = pd.read_csv(file_to_save)
File already exists. Loading data from CSV
In [3]:
df = pd.read_csv("stock_market_data-TCS.csv")
In [4]:
df = df[['Date', 'Open', 'Close', 'Low', 'High']]
In [5]:
df = df.sort_values('Date')
In [6]:
df.head()
Out[6]:
Date Open Close Low High
1259 2013-11-01 35.00 36.20 32.100 37.00
1258 2013-11-04 36.80 35.35 34.690 36.80
1257 2013-11-05 35.11 35.35 34.821 35.50
1256 2013-11-06 35.61 35.90 35.610 36.49
1255 2013-11-07 36.80 35.31 34.120 36.80
In [7]:
df.tail()
Out[7]:
Date Open Close Low High
4 2018-10-26 9.55 9.57 9.32 9.730
3 2018-10-29 9.70 9.69 9.57 9.930
2 2018-10-30 9.65 10.05 9.65 10.080
1 2018-10-31 6.82 5.91 5.72 7.840
0 2018-11-01 6.01 5.39 5.26 6.009
In [8]:
plt.figure(figsize = (18,9))
plt.plot(range(df.shape[0]),(df['Low']+df['High'])/2.0)
plt.xticks(range(0,df.shape[0],100),df['Date'].loc[::100],rotation=45)
plt.xlabel('Date',fontsize=18)
plt.ylabel('Mid Price',fontsize=18)
plt.show()
In [9]:
high_prices = df.loc[:,'High']
low_prices = df.loc[:,'Low']
df["Mid Prices"] = (high_prices+low_prices)/2.0
In [10]:
df.head()
Out[10]:
Date Open Close Low High Mid Prices
1259 2013-11-01 35.00 36.20 32.100 37.00 34.5500
1258 2013-11-04 36.80 35.35 34.690 36.80 35.7450
1257 2013-11-05 35.11 35.35 34.821 35.50 35.1605
1256 2013-11-06 35.61 35.90 35.610 36.49 36.0500
1255 2013-11-07 36.80 35.31 34.120 36.80 35.4600
In [11]:
df.tail()
Out[11]:
Date Open Close Low High Mid Prices
4 2018-10-26 9.55 9.57 9.32 9.730 9.5250
3 2018-10-29 9.70 9.69 9.57 9.930 9.7500
2 2018-10-30 9.65 10.05 9.65 10.080 9.8650
1 2018-10-31 6.82 5.91 5.72 7.840 6.7800
0 2018-11-01 6.01 5.39 5.26 6.009 5.6345

Data Cleaning

In [11]:
df.drop("Date", axis = 1,inplace = True)
In [12]:
from sklearn.preprocessing import StandardScaler
In [13]:
scaler = StandardScaler()
scaler.fit(df)
Out[13]:
StandardScaler(copy=True, with_mean=True, with_std=True)
In [14]:
df = scaler.transform(df)

Building Long-Short Term Memory Cell to implement Recurrent Neural Network

In [15]:
def build_model(layers):
    model = Sequential()

    model.add(LSTM(
        input_shape=(None, layers[0]),
        units=50,
        return_sequences=True))
    model.add(Dropout(0.2))

    model.add(LSTM(
        100,
        return_sequences=False))
    model.add(Dropout(0.2))

    model.add(Dense(
        units=1))
    model.add(Activation('linear'))

    start = time.time()
    model.compile(loss='mse', optimizer='rmsprop')
    print ('compilation time : ', time.time() - start)
    return model

Load data as per model requirements

In [16]:
def load_data(stock, seq_len):
    amount_of_features = 5
    data = stock
    sequence_length = seq_len + 1
    result = []
    for index in range(len(data) - sequence_length):
        result.append(data[index: index + sequence_length])
    
    result =  np.array(result)
    row = round(0.75 * result.shape[0])
    train = result[:int(row), :]
    x_train = train[:, :-1]
    y_train = train[:, -1][:,-1]
    x_test = result[int(row):, :-1]
    y_test = result[int(row):, -1][:,-1]

    x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], amount_of_features))
    x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], amount_of_features))  

    return [x_train, y_train, x_test, y_test]
In [17]:
window = 5
X_train, y_train, X_test, y_test = load_data(df, window)
print("X_train", X_train.shape)
print("y_train", y_train.shape)
print("X_test", X_test.shape)
print("y_test", y_test.shape)
X_train (940, 5, 5)
y_train (940,)
X_test (314, 5, 5)
y_test (314,)
In [18]:
model = build_model([5,window,1])
compilation time :  0.02281332015991211

Training Time!

In [19]:
model.fit(
    X_train,
    y_train,
    batch_size=512,
    epochs=30,
    validation_split=0.1,
    verbose=1)
Train on 846 samples, validate on 94 samples
Epoch 1/30
846/846 [==============================] - 1s 2ms/step - loss: 0.9017 - val_loss: 0.2787
Epoch 2/30
846/846 [==============================] - 0s 132us/step - loss: 0.2839 - val_loss: 0.1093
Epoch 3/30
846/846 [==============================] - 0s 118us/step - loss: 0.0636 - val_loss: 0.0564
Epoch 4/30
846/846 [==============================] - 0s 120us/step - loss: 0.0418 - val_loss: 0.0276
Epoch 5/30
846/846 [==============================] - 0s 123us/step - loss: 0.0331 - val_loss: 0.0138
Epoch 6/30
846/846 [==============================] - 0s 119us/step - loss: 0.0273 - val_loss: 0.0066
Epoch 7/30
846/846 [==============================] - 0s 119us/step - loss: 0.0248 - val_loss: 0.0039
Epoch 8/30
846/846 [==============================] - 0s 117us/step - loss: 0.0251 - val_loss: 0.0031
Epoch 9/30
846/846 [==============================] - 0s 137us/step - loss: 0.0256 - val_loss: 0.0029
Epoch 10/30
846/846 [==============================] - 0s 137us/step - loss: 0.0202 - val_loss: 0.0029
Epoch 11/30
846/846 [==============================] - 0s 124us/step - loss: 0.0247 - val_loss: 0.0049
Epoch 12/30
846/846 [==============================] - 0s 120us/step - loss: 0.0373 - val_loss: 0.0136
Epoch 13/30
846/846 [==============================] - 0s 126us/step - loss: 0.0448 - val_loss: 0.0032
Epoch 14/30
846/846 [==============================] - 0s 115us/step - loss: 0.0230 - val_loss: 0.0014
Epoch 15/30
846/846 [==============================] - 0s 128us/step - loss: 0.0236 - val_loss: 0.0017
Epoch 16/30
846/846 [==============================] - 0s 116us/step - loss: 0.0212 - val_loss: 0.0018
Epoch 17/30
846/846 [==============================] - 0s 135us/step - loss: 0.0255 - val_loss: 0.0020
Epoch 18/30
846/846 [==============================] - 0s 115us/step - loss: 0.0525 - val_loss: 0.0019
Epoch 19/30
846/846 [==============================] - 0s 122us/step - loss: 0.0398 - val_loss: 0.0013
Epoch 20/30
846/846 [==============================] - 0s 116us/step - loss: 0.0261 - val_loss: 0.0015
Epoch 21/30
846/846 [==============================] - 0s 129us/step - loss: 0.0211 - val_loss: 0.0022
Epoch 22/30
846/846 [==============================] - 0s 131us/step - loss: 0.0195 - val_loss: 0.0021
Epoch 23/30
846/846 [==============================] - 0s 124us/step - loss: 0.0196 - val_loss: 0.0014
Epoch 24/30
846/846 [==============================] - 0s 131us/step - loss: 0.0246 - val_loss: 0.0019
Epoch 25/30
846/846 [==============================] - 0s 121us/step - loss: 0.0438 - val_loss: 0.0020
Epoch 26/30
846/846 [==============================] - 0s 124us/step - loss: 0.0427 - val_loss: 0.0014
Epoch 27/30
846/846 [==============================] - 0s 127us/step - loss: 0.0255 - val_loss: 0.0012
Epoch 28/30
846/846 [==============================] - 0s 126us/step - loss: 0.0221 - val_loss: 0.0012
Epoch 29/30
846/846 [==============================] - 0s 131us/step - loss: 0.0217 - val_loss: 0.0012
Epoch 30/30
846/846 [==============================] - 0s 120us/step - loss: 0.0224 - val_loss: 0.0012
Out[19]:
<keras.callbacks.History at 0x7f9b1c1dfc18>
In [20]:
trainScore = model.evaluate(X_train, y_train, verbose=0)
print(trainScore)
0.014827937394643123
In [21]:
accuracy = (1-trainScore)*100

Predictions

In [23]:
p = model.predict(X_test)
In [24]:
from sklearn.metrics import mean_squared_error
In [25]:
mse = mean_squared_error(y_test, p)
In [26]:
accuracy_test = (1-mse)*100

Visualizations

In [28]:
import matplotlib.pyplot as plt2
plt2.figure(figsize = (18,9))
plt2.plot(p,color='red', label='prediction')
plt2.plot(y_test,color='blue', label='y_test')
plt2.legend(loc='upper left')
plt2.show()

Sentiment Analysis

In [29]:
consumer_key= 'E0pFYVai9VaOhqLiRBEC6gpGF'
consumer_secret= 'XAMh4l9XL5nwFK3MN5tAjtXA2YgDN1tw5f7L2n6dz5ib8VYlbm'

access_token='3261604734-86c7DOJP98GwNeFWzvgPQKFUTyHn1ZFwlloJP3v'
access_token_secret='eXEmlEAdxaFjueVP03jsAWeOeNMkI7ToiDQkyvLDa6eX7'
In [30]:
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)
In [31]:
public_tweets = api.search('TCS', count = 1000)
In [32]:
def clean_tweet(tweet):
    return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())
In [33]:
def get_tweet_sentiment(tweet):
    analysis = TextBlob(clean_tweet(tweet))
    if analysis.sentiment.polarity > 0:
        return 'positive'
    elif analysis.sentiment.polarity == 0:
        return 'neutral'
    else:
        return 'negative'
In [34]:
positive = 0
negative = 0
neutral = 0
print(len(public_tweets))
for tweet in public_tweets:
#     print(tweet.text)
    print(clean_tweet(tweet.text))
    sentiment = get_tweet_sentiment(tweet.text) 
    print(sentiment)
    if sentiment == 'positive':
        positive += 1
    elif sentiment == 'negative':
        negative += 1
    elif sentiment == 'neutral':
        neutral += 1
    print("")
100
RT HappyHalloween For your chance to WIN this spook tacular bundle on this wicked WinItWednesday simply FOLLOW us and RT
positive

RT TCS makes first digital acquisition buys design studio W12 Technology News ETtech
positive

TCS makes its first digital acquisition all you need to know about TCS buyout of London s W12 Studio
positive

Stocks Radar Axis Bank Hindustan Petroleum Indraprastha Gas TCS
neutral

RT PLANNING YOUR RACE DAY OUTFIT Include our LovePartiesHateWhips accessories and share your pic with the LovePartiesHateWhips h
neutral

Se algu m que voc n o conhece lhe diz oi o que voc diz Oi
neutral

RT RT this post and follow us for your chance to twirl into winter and win a Ballet Theatre and Ice Skating Friends We ve g
positive

RT
neutral

Tcs acusa Bolsonaro de ditador fascista e agora o Bolsonaro chama um magistrado reconhecendo as
neutral

molliebanks 21
neutral

RT esports One of the worse goal I scored but the most satisfying to watch on stream Laughed way t
positive

RT Personendrohnen in Jetgr sse selbstfahrende Autos f hrerstandlose Z ge Welchen Einfluss die Digitalisierung auf di
neutral

RT RT this post and follow us for your chance to twirl into winter and win a Ballet Theatre and Ice Skating Friends We ve g
positive

RT na Check out Pepper the humanoid robot welcoming people to the TCSNYCMarathon
neutral

Stay tuned to know what s happening at the TCSNYCSMarathon
neutral

RT project ygo CS 12 22 Akkun CS 12 23 Tcs
neutral

RT RT this post and follow us for your chance to twirl into winter and win a Ballet Theatre and Ice Skating Friends We ve g
positive

RT RT this post and follow us for your chance to twirl into winter and win a Ballet Theatre and Ice Skating Friends We ve g
positive

RT RT this post and follow us for your chance to twirl into winter and win a Ballet Theatre and Ice Skating Friends We ve g
positive

CS 12 22 Akkun CS 12 23 Tcs
neutral

RT RT this post and follow us for your chance to twirl into winter and win a Ballet Theatre and Ice Skating Friends We ve g
positive

RT Running the NYC Marathon this Sunday You can follow my slow run via the TCS NYC marathon app and put my name in under tra
negative

RT RT this post and follow us for your chance to twirl into winter and win a Ballet Theatre and Ice Skating Friends We ve g
positive

RT The new Tax Collection at Source is here to ensure better and centralised compliance lesser revenue leakages for the gove
positive

Jobs Alert TCS is Hiring through a Mega Walk In TechGig Survey Understanding the top challenges faced by women in technology
positive

RT RT this post and follow us for your chance to twirl into winter and win a Ballet Theatre and Ice Skating Friends We ve g
positive

RT HappyHalloween For your chance to WIN this spook tacular bundle on this wicked WinItWednesday simply FOLLOW us and RT
positive

RT na Run through the finish line of the TCSNYCMarathon in our new interactive game Marathon City Sprint to Win Visit the expo
positive

RT feelings i accidentally dropped my ball in my water bowl technically making a soup i am an innovator
neutral

acquires London based digital design firm W12 Studios
negative

buys London based digital design company W12 Studios
neutral

TCS With GeoSight
neutral

Sir eMO was redirected to T B Sanatorium PO from Koyali PO on 22 09 2018 however the same is not ye
neutral

RT First Deposit Campaign Win 50 USDT 20 Winners How to Enter 1 Follow 2 RT 3 Sign up for a new OKEx account via http
positive

RT RT this post and follow us for your chance to twirl into winter and win a Ballet Theatre and Ice Skating Friends We ve g
positive


neutral

RT
neutral

RT
neutral

RT ROSSI nico jeito que eu gosto de mulher sangrando
neutral

RT It will inspire you 5 days It s getting real Before runners hit the streets of NYC RisingNYRR will take on the You
positive

ASPIREST ASPIREST 1448
neutral

RT RT this post and follow us for your chance to twirl into winter and win a Ballet Theatre and Ice Skating Friends We ve g
positive

Noticias 4 Visi n Reprise 12AM 1AM ahora por Canal4 en S varTV
neutral

tcs kia
neutral

RT TCS makes first digital acquisition buys design studio W12 Technology News ETtech
positive

Happy 53rd birthday and lots of cake from the whole team at Studio by TCS to SRK
positive

Happy 53rd birthday and lots of cake from the whole team at Studio by TCS to SRK
positive

RT 4 WelcomeGOT7toThailand
neutral

RT Happy publication DillyCourt THE CHRISTMAS ROSE is out today RT to win 1 of 3 copies Rose had risked everything to
positive

RT canada Asia Pacific companies like those at the ForbesGlobalCEO Conference are looking to Canada for investment opportunitie
neutral

RT There was inspiration every where you looked as the sun came out for a wonderful Wednesday of TCS Race Week Ab
positive

RT canada Yummy things are made in Brantford Ontario including Nutella and Ferrero Rocher InvestinCanada WBFMI Milan
neutral

AIIndia
neutral

RT Europe What do retailers value in their technology partners s shares her thoughts with
neutral

RT HappyHalloween For your chance to WIN this spook tacular bundle on this wicked WinItWednesday simply FOLLOW us and RT
positive

RT It will focus you 3 days Right about now you start to hone down on your training you re focused on running your be
positive

RT na Use our 2018 TCSNYCMarathon app to create digital cheer cards and show your support for friends and family in this year s race
neutral

RT Meet Canadian organizations innovative companies amp officials from municipalities looking at smart solutions Canada booth is
positive

RT ANZ After his first marathon earlier this year at the TCS Australian Running Festival in Canberra Rahul is in the US with his fel
positive

RT canada Attending WBFMI today Visit our booth to find out about why the time to InvestinCanada is now Milano SDC
neutral

Best of luck to Rowena Hubble ahead of first full marathon with TeamTCS at the TCSNYCmarathon What
positive

RT
neutral

With four Days To Next Earnings Report Container Store Group Inc NYSE TCS Close At 5 91
neutral

RT RT this post and follow us for your chance to twirl into winter and win a Ballet Theatre and Ice Skating Friends We ve g
positive

RT s not backing down from his own AAPL don t trade it mantra
positive

RT 16 down days in October most for any month since 1970 amp tied for 3rd worst month since S amp P s inception in 1928
negative

TCs in Ladies special 1st class coach to check if 2nd class pax in 1st Waste of time No point today C
positive

RT
neutral

RT Congrats to News a Leader in NelsonHall NEAT for Managed Security Services
neutral

RT Latest NelsonHall Quarterly Update on News Another very strong quarter as outsourcing contracts ramp and TCS gains m
positive

That s what I am saying Haven t been to bbsr but have a lot of friends working in Infy
neutral

RT News TCS acquires W12 Studios an award winning London based Digital Design Studio Read more
positive


neutral

MOSL 23rd Annual Wealth Creation Study shares the biggest wealth creators over the last 5 yrs Usual suspects lead
negative

Switch
neutral

RT TCS buys digital design firm W12 Studios in its 1st acquisition since 2013
negative

TCS
neutral

RT If u r looking for long term then go for TCS HDFC BANK Maruti Suzuki dmart ONGC infy Lnt
negative

RT estas son la cosas que me hacen decirles que son unos descarados ladrones evaden las preguntas cuando les conviene solo
neutral

RT RT this post and follow us for your chance to twirl into winter and win a Ballet Theatre and Ice Skating Friends We ve g
positive

anantapur ink pact
neutral

RT BG5 TCS
neutral

RT News TCS acquires W12 Studios an award winning London based Digital Design Studio Read more
positive

RT Interested in exciting business opportunities in Japan Check out JETRO s Japan Canada Innovation Partnership Forum
positive

RT Uniting the Swiss Rocket League community RocketLeague esports
neutral

ROSSI 100respeito
neutral

digitaldesigns technology digitaltransformation
neutral

RT BaNCS Photographs from last week s BigTechDinner with TCS BaNCS and Financial Times during Sibos are now available Click here t
positive

Acs Tcs
neutral

Photographs from last week s BigTechDinner with TCS BaNCS and Financial Times during Sibos are now available Cli
positive

SSR
neutral

RT Acquires W12 Studios an Award Winning London Based Digital Design Studio
positive


neutral

RT Latest India Business News 2nd November 2018 Business News Tentaran Investment BusinessNews Bajaj ITI Realme Tata
positive

RT
neutral

RT News TCS acquires W12 Studios an award winning London based Digital Design Studio Read more
positive

RT At SmartGridDayRome SDC presents world leader in controlled switching technologies ma
neutral

ROSSI nico jeito que eu gosto de mulher sangrando
neutral

RT November 5 is SmartGridDayRome SDC presents Voltra Technologie developer of innovative prod
positive

Buenas noches chica guapa Saludos a todos los amo mucho bendiciones
neutral

In [35]:
print('Positive:', positive)
print('Negative:', negative)
print('Neutral:', neutral)
Positive: 44
Negative: 6
Neutral: 50