Home

Individual Review

Development Journey


Getting data

Objective: Get real time stock data


Connecting frontend and backend

Objective: Send data from frontend to backend and get data


Code Snippet


These are some code snippets I think show contribution to the code

Python

This code snippet I worked on is how the data for the graph is created

from flask import Blueprint, jsonify, request
import pandas as pd
import yfinance as yf
import plotly.graph_objs as go
from flask_restful import Api, Resource
import numpy as np
from flask_cors import CORS

stock_api = Blueprint('stock_api', __name__, url_prefix='/api/stocks')
api = Api(stock_api)

CORS(stock_api)


def get_stock_graph(stock_name):
    end_date = datetime.now()
    start_date = end_date - pd.Timedelta(days=4856)

    df = yf.download(stock_name, start=start_date, end=end_date)

    graph = go.Figure(data=go.Candlestick(x=df.index,
                                          open=df['Open'],
                                          high=df['High'],
                                          low=df['Low'],
                                          close=df['Close'],
                                          name=stock_name))
    graph.update_layout(title=f'{stock_name} Stock Price',
                        xaxis_title='Date',
                        yaxis_title='Price')

    graph_data = graph.to_dict()
    graph_data['data'][0]['x'] = graph_data['data'][0]['x'].astype(
        str).tolist()
    graph_data['data'][0]['open'] = graph_data['data'][0]['open'].tolist()
    graph_data['data'][0]['high'] = graph_data['data'][0]['high'].tolist()
    graph_data['data'][0]['low'] = graph_data['data'][0]['low'].tolist()
    graph_data['data'][0]['close'] = graph_data['data'][0]['close'].tolist()

    return graph_data


class _ReadStockGraph(Resource):
    def get(self, stock_name):
        graph = get_stock_graph(stock_name)
        return graph

JavaScript

This is the code that connects the backend and frontend Via JavaScript to send a request for the graph data and plots it

%%js
function getStockGraph() {
            const selectedStock = document.getElementById('stock-input').value;
            const button = document.getElementById('collect');
            const apiUrl = 'http://localhost:8282/api/stocks/stock_graph/' + selectedStock;
            button.textContent = 'Loading...';
            fetch(apiUrl)
                .then(response => response.json())
                .then(graphData => {
                    Plotly.newPlot('graph', graphData.data, graphData.layout);
                    button.textContent = 'Display Graph';
                })
                .catch(error => {
                    console.error('Error:', error);
                    button.textContent = 'Display Graph';
                });
        }
        const stockInput = document.getElementById('stock-input');
        const collectButton = document.getElementById('collect');
        stockInput.addEventListener("keydown", function (event) {
            if (event.key === 'Enter') {
                getStockGraph();
            }
        });
        collectButton.addEventListener("click", getStockGraph);

Github Analytics

Key Commits:

Issues:


Individual Blog

Snippet from Simulations team teach

Hack: Given initial parameters for a car simulation, including its initial speed, acceleration rate, deceleration rate, maximum speed, and initial distance, write a program to simulate the cars journey and determine the final speed, distance covered, and time taken before it either covers 1000 meters or slows down to below 5 m/s?
initial_speed = 10
acceleration_rate = 2
deceleration_rate = -1
max_speed = 20
initial_distance = 0
target_distance = 1000
min_speed = 5

speed = initial_speed
distance = initial_distance
time = 0

while distance < target_distance and speed >= min_speed:
    time_to_max_speed = (max_speed - speed) / acceleration_rate
    distance_covered_acceleration = speed * time_to_max_speed + 0.5 * acceleration_rate * time_to_max_speed ** 2

    if distance + distance_covered_acceleration >= target_distance:
        time += (-speed + (speed ** 2 + 2 * acceleration_rate * (target_distance - distance)) ** 0.5) / acceleration_rate
        speed = max_speed
        distance = target_distance
    else:
        time += time_to_max_speed
        speed = max_speed
        distance += distance_covered_acceleration

        if distance < target_distance:
            time_to_decelerate = (speed - min_speed) / abs(deceleration_rate)
            distance_covered_deceleration = speed * time_to_decelerate + 0.5 * deceleration_rate * time_to_decelerate ** 2

            if distance + distance_covered_deceleration >= target_distance:
                time += (-speed + (speed ** 2 - 2 * deceleration_rate * (distance - target_distance)) ** 0.5) / abs(deceleration_rate)
                speed = min_speed
                distance = target_distance
            else:
                time += time_to_decelerate
                speed = min_speed
                distance += distance_covered_deceleration

print(f"Final Speed: {speed} m/s")
print(f"Distance Covered: {distance} meters")
print(f"Time Taken: {time} seconds")

Trimester One Reflections

Memories and Learning:

Positive Accomplishments

Opportunites for Growth and things I hope to learn in Tri 2

© 2024    •  Powered by Soopr   •  Theme  Moonwalk