Find and Plot Moving Average From Stock Market Data from MongoDB

Do you have stock markets data in MongoDB and wants to find moving average from it ? If  yes then this post is for you. In this tutorial you will know how to find moving average from stock market data from MongoDB and plot the line chart for the close and moving average on a single figure.

Steps to Find Moving Average from Stocks Market Data

Step 1: Import required libraries

Import all the necessary libraries you will use in this example. Import all them using the import statement.

``````import pandas as pd
import pymongo
import matplotlib.pyplot as plt``````

Step 2: Connect the MongoDB database

I have already stocks data inserted in the MongoDB database. There you will connect to the database using the pymongo module using the pymongo.MongoClient(). Use the below lines of code to make connection to collection of the database.

``````client = pymongo.MongoClient("mongodb://localhost:27017")
db = client["stocks_data"]
collection = db["IBM"]``````

Step 3: Fetch the data from MongoDB

You can fetch all the data from the collection using the find() function. The cursor will point to the first row of the collection the data will be converted to the list from the memory. After that it will be converted to the dataframe using the pandas.DataFrame() function.

``````cursor = collection.find()
db_data = list(cursor)
# Convert data to a DataFrame
df = pd.DataFrame(db_data)``````

Step 4: Find the Moving Average From Stock Market Data

Lets calculate the 50 day moving average for the stocks data you have fetched. To do this you will use the rolling(window=50) with the mean function to find the moving average using the last 50 rows on the close price of the dataframe.

``````window_size= 50
df['MA'] = df['close'].rolling(window=window_size).mean()``````

Step 5:  Plot the Moving average

Now the last step is to plot the moving average with the close price of the stocks data. You will use the matplotlib module for that. Use the below lines of code to plot the line chart for the close with the calculated moving average.

``````# Plotting the closing prices and the moving average
plt.figure(figsize=(10, 6))
plt.plot(df['timestamp'], df['close'], label='Closing Price', color='blue')
plt.plot(df['timestamp'], df['MA'], label=f'{window_size}-Day Moving Average', color='red')

plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Stock Closing Price and Moving Average')
plt.legend()
plt.grid(True)
plt.show()
print(df)
``````

Full Code

``````import pandas as pd
import pymongo
import matplotlib.pyplot as plt
client = pymongo.MongoClient("mongodb://localhost:27017")
db = client["stocks_data"]
collection = db["IBM"]
# # Fetch data from MongoDB
cursor = collection.find()
db_data = list(cursor)
# Convert data to a DataFrame
df = pd.DataFrame(db_data)
print(df)
window_size= 50
df['MA'] = df['close'].rolling(window=window_size).mean()

# Plotting the closing prices and the moving average
plt.figure(figsize=(10, 6))
plt.plot(df['timestamp'], df['close'], label='Closing Price', color='blue')
plt.plot(df['timestamp'], df['MA'], label=f'{window_size}-Day Moving Average', color='red')

plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Stock Closing Price and Moving Average')
plt.legend()
plt.grid(True)
plt.show()
print(df)
``````

Output