Project Name: Stock Trend Data Display

Update Project Delete Project

Project description

I created a simple stock trend web app. This app will retrieve data about the most active stocks in the market and present it in a user-friendly manner. Users can select different market trends such as most active, gainers, losers, etc., and view corresponding stock details

Project steps

Add Steps

Step1:Create a models.py

Update step Delete step

Step description:

from django.db import models
# Importing the models module from Django, which allows us to define database models.

# Create your models here.
from bs4 import BeautifulSoup
import requests
import pandas as pd 

# Importing BeautifulSoup, requests, and pandas libraries for web scraping and data manipulation.

# most active stock

class StockTrend(models.Model):
    # Defining a Django model called StockTrend.
    
    trend = models.CharField(max_length=50)
    # A field in the StockTrend model to store the trend of the stock.
    # It is a character field with a maximum length of 50 characters.

    stock_data = {}
    # Initializing an empty dictionary to store stock data fetched from the web.

    def stocktrend(self):
        # Method to fetch stock data based on the trend.
        
        self.stock_data[self.trend] = {'Name':[],'Price':[],'Change':[],'Percentage':[]}
        # Initializing a nested dictionary within stock_data to store stock data.

        base_url = 'https://www.google.com/finance/markets/'+ self.trend
        # Constructing the base URL for fetching stock data based on the trend.

        url_request = requests.get(base_url)
        # Sending an HTTP GET request to the specified URL.

        soup_obj = BeautifulSoup(url_request.content,'html.parser')
        # Creating a BeautifulSoup object by parsing the HTML content of the response.

        most_active_li = soup_obj.find_all('li')
        # Finding all the <li> elements in the parsed HTML content.

        for i in most_active_li:
            # Iterating over each <li> element.
            
            self.stock_data[self.trend]['Name'].append(i.find('div',attrs={'class':'ZvmM7'}).getText().strip())
            # Extracting and appending the stock name to the 'Name' list in stock_data.

            # Similar lines retrieve and append price, change, and percentage data to the corresponding lists in stock_data.

        stock_dic = {'Name': self.stock_data[self.trend]['Name'],'Price': self.stock_data[self.trend]['Price'],'Change': self.stock_data[self.trend]['Change'],'Percentage': self.stock_data[self.trend]['Percentage']}
        # Creating a dictionary containing the stock data lists fetched from stock_data.

        stock_df = pd.DataFrame(stock_dic)
        # Creating a pandas DataFrame from the stock_dic dictionary.

        return stock_df
        # Returning the DataFrame containing the stock data.

Step2:Create view.py

Update step Delete step

Step description:

def stocktrend(request):
    # View function to handle stock trend requests.
    
    stock_df = None
    # Initializing stock_df variable to None.

    if request.method == 'POST':
        # Checking if the request method is POST.

        if 'trend1' in request.POST:
            # Checking if 'trend1' is in the POST data.

            stock_obj = StockTrend(trend=str(request.POST['trend1']))
            # Creating a new StockTrend object with the specified trend.
            
            stock_obj.save()
            # Saving the StockTrend object to the database.

            stock_df = stock_obj.stocktrend()
            # Fetching stock data for the specified trend.

            today = str(date.today()) + '.' + str(request.POST['trend1']) + '.csv'
            # Creating a filename based on the current date and trend.
            
            response = HttpResponse(content_type='text/csv')
            # Creating an HTTP response object with content type text/csv.
            
            response['Content-Disposition'] = f'attachment; filename={today}'
            # Setting the Content-Disposition header for file download.

            stock_df.to_csv(path_or_buf=response)
            # Writing the DataFrame to a CSV file.

            return response
            # Returning the HTTP response.

        if 'trend' in request.POST:
            # Checking if 'trend' is in the POST data.

            stock_obj = StockTrend(trend=str(request.POST['trend']))
            # Creating a new StockTrend object with the specified trend.
            
            stock_obj.save()
            # Saving the StockTrend object to the database.

            stock_df = stock_obj.stocktrend().to_html(index=False)
            # Fetching stock data for the specified trend and converting it to HTML format.

    return render(request, 'home.html', {'stock_df': stock_df})
    # Rendering the 'home.html' template with stock data passed as context.

Step3:Create template to display the content

Update step Delete step

Step description:

Create two forms for the two sections. Use .to_html method to convert the data to html format

Step4:Create URL

Update step Delete step

Step description:

Create url to assign the view function

Step5:Upload it to the git repo

Update step Delete step

Step description:

add ignore.py to ignore some env variable

Step6:upload it to the server

Update step Delete step

Step description:

prepare the env in aws ec2

Step7:create Gunicorn socket, service file and nginx config file

Update step Delete step

Step description:

make sure the location

Step8:Set up the DNS/Domain and cashing in CF

Update step Delete step

Step description:

make sure the cashing settings