<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: GeekyHumans</title>
    <description>The latest articles on DEV Community by GeekyHumans (@geekyhumans).</description>
    <link>https://dev.to/geekyhumans</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F677917%2F2e2846d7-3e23-4c6b-a12d-2e914482e73a.png</url>
      <title>DEV Community: GeekyHumans</title>
      <link>https://dev.to/geekyhumans</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/geekyhumans"/>
    <language>en</language>
    <item>
      <title>How to predict US Stock Price using Python?</title>
      <dc:creator>GeekyHumans</dc:creator>
      <pubDate>Thu, 14 Jul 2022 05:56:00 +0000</pubDate>
      <link>https://dev.to/geekyhumans/how-to-predict-us-stock-price-using-python-1ce2</link>
      <guid>https://dev.to/geekyhumans/how-to-predict-us-stock-price-using-python-1ce2</guid>
      <description>&lt;p&gt;Stock market prediction is a hot topic nowadays. Because of the big speculation risk, the stock market is highly influenced by the news, such as the policy change caused by the Federal Reserve, the interest rate, and so on. This article describes how to predict US stock price using Python with the help of artificial intelligence technology of deep neural networks to predict US stock prices. We will write a program in python that predicts the movement of the US stock market by using historical data.&lt;/p&gt;

&lt;h2&gt;
  
  
  Pre-Requisites:
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Numpy:
&lt;/h3&gt;

&lt;p&gt;NumPy, short for Numerical Python, is a Python library used for scientific computing and data processing. This library makes it easier to run Python code on arrays and matrices instead of lists. It has many functions to make your mathematics faster.&lt;/p&gt;

&lt;p&gt;You can install the Jupyter notebook using the following command in your conda terminal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install numpy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Matplotlib:
&lt;/h3&gt;

&lt;p&gt;Matplotlib is a very extensive library. Matplotlin was created as the graphical user interface for a program named MATLAB. Engineers and data scientists primarily use MATLAB, although it also works well with Python. Since we’re going to create charts and graphs, therefore, we need to install matplotlib.&lt;/p&gt;

&lt;p&gt;You can install the Jupyter notebook using the following command in your conda terminal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install Matplotlib
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Tensorflow:
&lt;/h3&gt;

&lt;p&gt;TensorFlow is an open-source software library for numerical computation using data flow graphs. The graph nodes represent mathematical operations, while the graph edges represent the multidimensional data arrays (tensors) that flow between them. The flexible architecture allows you to deploy computation to one or more CPUs or GPUs in a desktop, server, or mobile device with a single API.&lt;/p&gt;

&lt;p&gt;You can install the Jupyter notebook using the following command in your conda terminal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install --upgrade tensorflow
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Sklearn:
&lt;/h3&gt;

&lt;p&gt;SK-learn is a python library that makes the machine learning process easy to understand&lt;/p&gt;

&lt;p&gt;You can install the Jupyter notebook using the following command in your conda terminal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install -U scikit-learn
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Pandas_datareader:
&lt;/h3&gt;

&lt;p&gt;Pandas DataReader is a Python package that allows us to create a pandas DataFrame object by using various data sources from the internet. It is popularly used for real-time stock price datasets.&lt;/p&gt;

&lt;p&gt;You can install the Jupyter notebook using the following command in your conda terminal.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install pandas-datareader
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step -1: Import dependencies
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.feature_selection import SequentialFeatureSelector
from sklearn.model_selection import PredefinedSplit
import pandas_datareader as web
import datetime as dt

from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, LSTM
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step -2: Load the data
&lt;/h2&gt;

&lt;p&gt;For that, we have to specify from what point we want to take the data to predict and we also defined the ticker symbol you can get the ticker symbol of any company from the google&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;company = 'FB'
start = dt.datetime(2014,1,1)
end = dt.datetime(2022,1,1)

# define ticker symbol
data = web.DataReader(company, 'yahoo', start, end)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step -3: Preparing the data
&lt;/h2&gt;

&lt;p&gt;To prepare the data we are not going to use the whole data frame we are only using the closing price.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1, 1))

# how many days we want to look at the past to predict
prediction_days = 60

# defining two empty lists for preparing the training data
x_train = []
y_train = []

# we are counting from the 60th index to the last index
for x in range(prediction_days, len(scaled_data)):
    x_train.append(scaled_data[x-prediction_days:x, 0])
    y_train.append(scaled_data[x, 0])

x_train, y_train = np.array(x_train), np.array(y_train)
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step -4: Build the model and specify the layers
&lt;/h2&gt;

&lt;p&gt;Here we are always going to include a single LSTM layer, followed by a dropout layer in the sequence. After that, we are going to have dense layers which will be many units in size and each unit will be the stock price prediction. You can change the number of units used but you need to know that more units mean a longer training time since there is more computation required per layer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;model = Sequential()
# specify the layer
model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
# this is going to be a prediction of the next closing value
model.add(Dense(units=1))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step -5: Compiling the Model
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;model.compile(optimizer='adam', loss='mean_squared_error')
# fit the model in the training data
model.fit(x_train, y_train, epochs=25, batch_size=32)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step -6: Testing the model
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Load Test Data
test_start = dt.datetime(2020,1,1)
test_end = dt.datetime.now()

test_data = web.DataReader(company, 'yahoo', test_start, test_end)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now what we are going to do with the data from this company is that we need to see how predictive it can be. We need to get prices, scale the prices, and then create a total data set consisting of both tested and untested information so firstly, we’ll use actual stock market data which is not related to any predictions made. In the real world the type of data we would use will be closing values and then, what we will do is combine all the information into one big data set to help us make our predictions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;actual_prices = test_data['Close'].values
total_dataset = pd.concat((data['Close'],test_data['Close']), axis=0)

model_input = total_dataset[len(total_dataset)- len(test_data) - prediction_days:].values
# reshaping the model
model_input = model_input.reshape(-1, 1)
# scaling down the model
model_input = scaler.transform(model_input)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Step -7: Predict the next day’s data
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x_test = []
for x in range(prediction_days, len(model_input)):
    x_test.append(model_input[x-prediction_days:x, 0])

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

predicted_price = model.predict(x_test)
predicted_price = scaler.inverse_transform(predicted_price)

# plot the test Predictions
plt.plot(actual_prices, color="black", label=f"Actual{company} price")
plt.plot(predicted_price, color='green', label="Predicted {company} Price")
plt.title(f"{company} Share price")
plt.xlabel('Time')
plt.ylabel(f'{company} share price')
plt.legend
plt.show()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we are going to use real data as an input to predict the data for the next day.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;prediction = model.predict(real_data)
prediction = scaler.inverse_transform(prediction)
print(f"Prediction: {prediction}")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--X7Lh12Uh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://lh6.googleusercontent.com/RIl0yE6pOiMob9vbWx7kMqgxJuzgQF1nJihdv0CxgDnhisN0R7-xx-Celg0g_ZhUi7Fd2NrAJU03NKv_lkCAbkOtW0y-pi-egCyOeyLB1JBzk4U09siNO44Cer-RH9oxzZooMmfn" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--X7Lh12Uh--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://lh6.googleusercontent.com/RIl0yE6pOiMob9vbWx7kMqgxJuzgQF1nJihdv0CxgDnhisN0R7-xx-Celg0g_ZhUi7Fd2NrAJU03NKv_lkCAbkOtW0y-pi-egCyOeyLB1JBzk4U09siNO44Cer-RH9oxzZooMmfn" alt="" width="880" height="158"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--GcbI3wb_--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://lh3.googleusercontent.com/4Gmwlj_kCmr0mNK_AOPs3XtZDHUHNNA4YpJvp3RxEd9XfXaw91QTfdYI_hqEy1ApVCR1xMoJCpNDa4K2ca3_Kqy01mxfYJMYcPjke0DG2AjKXuDHzY0Ck6VB7BL6DIZ10PBXkDWS" alt="" width="796" height="680"&gt;
&lt;/h2&gt;

&lt;h2&gt;
  
  
  Final Words
&lt;/h2&gt;

&lt;p&gt;In this blog, we learned how to predict the stock market with Python! Here we took a 60-day long time series of data, then predicted the next day’s data. It’s a little bit of a complicated process but it’s not that hard either. That said, I do not recommend using this for trading. I consider this more a learning experience than anything else. So hope you liked the tutorial and if you have any questions, please feel free to leave them down below and I’ll do my best to answer them!&lt;/p&gt;

&lt;p&gt;Here are some useful tutorials that you can read:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://geekyhumans.com/concurrency-in-python/"&gt;Concurrency in Python&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://geekyhumans.com/basic-neural-network-in-python-to-make-predictions/(opens%20in%20a%20new%20tab)"&gt;Basic Neural Network in Python to Make Predictions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://geekyhumans.com/monitor-python-scripts-using-prometheus/"&gt;Monitor Python scripts using Prometheus&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://geekyhumans.com/how-to-implement-google-login-in-flask-app/"&gt;How to Implement Google Login in Flask App&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://geekyhumans.com/how-to-create-a-word-guessing-game-in-python/"&gt;How to create a Word Guessing Game in Python&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://geekyhumans.com/convert-images-to-8-bit-images-using-python/"&gt;Convert an image to 8-bit image&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://geekyhumans.com/schedule-python-scripts-with-apache-airflow/"&gt;Schedule Python Scripts with Apache Airflow&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://geekyhumans.com/heres-the-sudoku-game-in-python-source-code/"&gt;Create Sudoku game in Python using Pygame&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://geekyhumans.com/how-to-deploy-flask-api-on-heroku/"&gt;How to Deploy Flask API on Heroku?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://geekyhumans.com/create-api-using-grpc-in-python/"&gt;Create APIs using gRPC in Python&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The post &lt;a href="https://geekyhumans.com/how-to-predict-us-stock-price-using-python/"&gt;How to predict US Stock Price using Python?&lt;/a&gt; appeared first on &lt;a href="https://geekyhumans.com"&gt;Geeky Humans&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>datascience</category>
      <category>mlai</category>
    </item>
    <item>
      <title>How to use Twitter API in Python</title>
      <dc:creator>GeekyHumans</dc:creator>
      <pubDate>Fri, 18 Dec 2020 10:03:50 +0000</pubDate>
      <link>https://dev.to/geekyhumans/how-to-use-twitter-api-in-python-1mkd</link>
      <guid>https://dev.to/geekyhumans/how-to-use-twitter-api-in-python-1mkd</guid>
      <description>&lt;p&gt;Twitter, one of the most popular websites where you can share your thoughts. A lot of people use Twitter for different purposes like marketing, sharing knowledge, etc. Being a developer, the Twitter API is one of the most important APIs. Let’s say a marketing agency wants to collect Twitter data, analyze it, and make tweets according to the stats. This task will definitely require them to use the API else they’ll have to spend so much money just to collect the data is unimaginable. To help you out we have created this tutorial. In this tutorial, we’ll be covering the Twitter API, how to connect to API, and how to tweet on Twitter using the API. So let’s get started:&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Twitter account&lt;/li&gt;
&lt;li&gt;Basic Knowledge of Python&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Step -1: Getting Access to Twitter API
&lt;/h2&gt;

&lt;p&gt;In order to get started with the Twitter API, you not only need a normal Twitter account but also require a Twitter Developer Account. Head over to &lt;a href="https://developer.twitter.com/en"&gt;https://developer.twitter.com/en&lt;/a&gt; and login with your credentials. Once you’re in, go to this URL: &lt;a href="https://developer.twitter.com/en/apply-for-access"&gt;https://developer.twitter.com/en/apply-for-access&lt;/a&gt; and click on Apply for a developer account.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s---UbLI_62--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://geekyhumans.com/wp-content/uploads/2020/12/Screenshot-2020-12-13-at-12.11.40-AM-1024x438.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s---UbLI_62--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://geekyhumans.com/wp-content/uploads/2020/12/Screenshot-2020-12-13-at-12.11.40-AM-1024x438.jpg" alt="twitter-api-using-api"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now select the Making a bot option and then next:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--eBAsQONe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://geekyhumans.com/wp-content/uploads/2020/12/Screenshot-2020-12-13-at-12.13.08-AM-1024x490.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--eBAsQONe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://geekyhumans.com/wp-content/uploads/2020/12/Screenshot-2020-12-13-at-12.13.08-AM-1024x490.jpg" alt="twitter-api-using-python"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;On the next page just cross-check if all the details are correct and then select your country and enter a name for your application. In my case, I have just passed my name.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--cQDrkHgz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://geekyhumans.com/wp-content/uploads/2020/12/Screenshot-2020-12-13-at-12.14.33-AM-1024x489.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--cQDrkHgz--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://geekyhumans.com/wp-content/uploads/2020/12/Screenshot-2020-12-13-at-12.14.33-AM-1024x489.jpg" alt="twitter-api-using-python"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now click on the Next button. On the next page Twitter will ask you a few questions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;“In English, please describe how you plan to use Twitter data and/or APIs. The more detailed the response, the easier it is to review and approve.“&lt;/li&gt;
&lt;li&gt;“Are you planning to analyze Twitter data?“ Just select “No” here&lt;/li&gt;
&lt;li&gt;“Will your app use Tweet, Retweet, like, follow, or Direct Message functionality?” You can mention here that yes my app will use a tweet feature here.&lt;/li&gt;
&lt;li&gt;“Do you plan to display Tweets or aggregate data about Twitter content outside of Twitter? You can select “No” here.&lt;/li&gt;
&lt;li&gt;”Will your product, service, or analysis make Twitter content or derived information available to a government entity?”. Select “No” here also.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Once you’re done with the adobe details, click on next, and on the next page, you can see all your submitted values. Cross-check them once and click on the “Looks Good” button. On the next page, you’ll have to accept the Terms and Conditions, read it thoroughly, and accept. You’ll receive an email to verify your account, you can follow the link in the email. You’ll also receive an acknowledgment email from Twitter that they have received your application. TADA!! Your application has been submitted for approval now. It doesn’t take more than a couple of hours for the review team of Twitter to review the application.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step -2: Twitter App Setup
&lt;/h2&gt;

&lt;p&gt;Once the application has been accepted, you’ll get an email from the Twitter team. Now it’s time to create our app on. So head over to your Twitter Developer account and click on Developer Portal. You’ll see the below page:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ttdY8W3U--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://geekyhumans.com/wp-content/uploads/2020/12/Screenshot-2020-12-13-at-8.06.11-PM-1024x491.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ttdY8W3U--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://geekyhumans.com/wp-content/uploads/2020/12/Screenshot-2020-12-13-at-8.06.11-PM-1024x491.jpg" alt="twitter-api-using-python"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now click on “Create Project” and fill out the form details like project name, description, app name. Once done, you can now see your API KEY, API SECRET, and Bearer Token. Save them in a safe place, we’ll be needing these credentials for API connection. Once you’re done with that, open the settings of your app and enable “Read and Write” under the permissions of your app.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--GcjCbmq1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://geekyhumans.com/wp-content/uploads/2020/12/Screenshot-2020-12-13-at-10.42.06-PM-1024x496.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--GcjCbmq1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://geekyhumans.com/wp-content/uploads/2020/12/Screenshot-2020-12-13-at-10.42.06-PM-1024x496.jpg" alt="twitter-api-using-python"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Step -3: Implementing and Generating Authentication URL
&lt;/h2&gt;

&lt;p&gt;Once you’re done with all the above steps, it’s time to write some code! So open the terminal, create a new folder for this project and open it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir twitter-test
cd twitter-test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have to install some dependencies Once you’re in the folder, paste the below command to install the package:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python3 -m pip install twython
python3 -m pip install requests
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now create three files:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;authenticate.py&lt;/li&gt;
&lt;li&gt;generateToken.py&lt;/li&gt;
&lt;li&gt;post.py&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After that, open authenticate.py and paste the below code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from twython import Twython
import requests
APP_KEY = "YOUR API KEY FROM TWITTER"
APP_SECRET = "YOUR API SECRET FROM TWITTER"
twitter = Twython(APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
OAUTH_TOKEN = auth['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']
oauth_verifier_url = auth['auth_url']
oauth_verifier = requests.get(oauth_verifier_url)
print("Verifier URL is:" + oauth_verifier_url)
print("OAUTH_TOKEN is:" + OAUTH_TOKEN)
print("OAUTH TOKEN SECRET is:" + OAUTH_TOKEN_SECRET)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Code Explanation:
&lt;/h3&gt;

&lt;p&gt;We’re using twython here which makes it easier for us to make Twitter API calls and provides multiple functions for different API calls. We’re also using requests here which are used to make  GET requests so that we can get oauth_verifier. This code is basically used to get the authentication URL so that you can authorize the app to make tweets on your behalf.&lt;/p&gt;

&lt;p&gt;Now on your terminal run the above piece of code by using the below code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python3 authenticate.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On execution you’ll get something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Verifier URL is: https://api.twitter.com/oauth/authenticate?oauth_token=XXXXX
OAUTH_TOKEN is: XXXXX
OAUTH TOKEN SECRET is: XXXXX
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now open the above URL in a browser as you’ll see something like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--kQ6zJOT7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://geekyhumans.com/wp-content/uploads/2020/12/Screenshot-2020-12-14-at-11.58.56-PM-1024x449.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kQ6zJOT7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://geekyhumans.com/wp-content/uploads/2020/12/Screenshot-2020-12-14-at-11.58.56-PM-1024x449.jpg" alt="twitter-api-using-python"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once you authorize the app, you’ll get an auth code, store that as well.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step -4: Implementing Token Generator
&lt;/h2&gt;

&lt;p&gt;Once you’re done implementing the authentication, it’s time to implement the token generator. So open generateToken.py in a &lt;a href="https://geekyhumans.com/20-best-ide/"&gt;code editor&lt;/a&gt; and paste the below code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from twython import Twython
import requests
APP_KEY = "YOUR APP KEY FROM TWITTER"
APP_SECRET = "YOUR APP SECRET FROM TWITTER"
twitter = Twython(APP_KEY, APP_SECRET)
twitter = Twython(APP_KEY, APP_SECRET,
OAUTH TOKEN FROM ABOVE SCRIPT, OAUTH TOKEN SECRET FROM ABOVE SCRIPT)
final_step = twitter.get_authorized_tokens(YOUR AUTH CODE HERE)
OAUTH_TOKEN = final_step['oauth_token']
OAUTH_TOKEN_SECRET = final_step['oauth_token_secret']
print(‘Token: ’+OAUTH_TOKEN)
print(‘Secret:’ + OAUTH_TOKEN_SECRET)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Code Explanation:
&lt;/h3&gt;

&lt;p&gt;Here we’re again generating &lt;code&gt;OAUTH_TOKEN&lt;/code&gt; and &lt;code&gt;OAUTH_TOKEN_SECRET&lt;/code&gt; but this time these credentials are actually attached to your own profile so that the combination of APP_KEY, APP_SECRET can identify your profile’s credentials.&lt;/p&gt;

&lt;p&gt;Let’s execute this script also by using the command python3 generateToken.py and you’ll get something like this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Token: XXXXX&lt;/code&gt;&lt;br&gt;&lt;br&gt;
&lt;code&gt;Secret: XXXXX&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Store these credentials as they’re the final credentials. Now it’s the time to tweet something.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step -5: Tweet Code
&lt;/h2&gt;

&lt;p&gt;Now open post.py and paste the below code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from twython import Twython
import requests
APP_KEY = "YOUR APP API KEY"
APP_SECRET = "YOUR APP SECRET"
OAUTH_TOKEN = "TOKEN FROM ABOVE SCRIPT"
OAUTH_TOKEN_SECRET = "SECRET FROM ABOVE SCRIPT"
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
twitter.update_status(status='@geekyhumans I made it!!')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Code Explanation:
&lt;/h3&gt;

&lt;p&gt;Here we’re all done with the authentication and token generation part. Now we’re tweeting status on Twitter. First, we’re creating an object of Twython using our credentials and then we’re calling a function &lt;code&gt;update_status&lt;/code&gt; that is used for tweeting on Twitter.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Words:
&lt;/h2&gt;

&lt;p&gt;So we have learned how to connect to Twitter API and post on Twitter. You can do a lot more with this API. I have created a bot that picks up posts from different websites and posts the URL with the title on Twitter every hour. Remember sky’s the limit and there’s a lot more to explore at an advanced level. I have created a Twitter bot which uses &lt;code&gt;beautifulsoup&lt;/code&gt; to fetch newly published posts from the sitemap of this website and some others also and then fetched the &lt;/p&gt;
&lt;h1&gt; tag with meta description and tweets on Twitter every hour.

&lt;/h1&gt;
&lt;p&gt;The post &lt;a href="https://geekyhumans.com/use-twitter-api-in-python/"&gt;How to use Twitter API in Python&lt;/a&gt; appeared first on &lt;a href="https://geekyhumans.com"&gt;Geeky Humans&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>python</category>
      <category>twython</category>
      <category>automation</category>
      <category>api</category>
    </item>
  </channel>
</rss>
