반응형

Create a python server code that allows users to access the web page and check Tesla's stock price for a month on a graph.

 

To create a Python server code that allows users to access a web page and check Tesla's stock price for a month on a graph, we can use the Flask web framework and the Plotly library for generating interactive graphs. Here's an example code:

 

from flask import Flask, render_template
import yfinance as yf
import plotly.graph_objs as go
from datetime import datetime, timedelta

app = Flask(__name__)

@app.route('/')
def index():
    # Create a Ticker object for Tesla's stock
    tesla = yf.Ticker("TSLA")

    # Get historical data for the past month
    start_date = datetime.now() - timedelta(days=30)
    end_date = datetime.now()
    data = tesla.history(start=start_date, end=end_date)

    # Create a Plotly graph object
    graph = go.Figure()
    graph.add_trace(go.Scatter(x=data.index, y=data['Close']))

    # Configure the graph layout
    graph.update_layout(
        title="Tesla's Stock Price for the Past Month",
        xaxis_title="Date",
        yaxis_title="Price (USD)",
    )

    # Render the HTML template with the graph
    return render_template('index.html', graphJSON=graph.to_json())

if __name__ == '__main__':
    app.run(debug=True)

In this code, we define a route for the root URL / that returns an HTML template with a Plotly graph of Tesla's stock price for the past month. We use the yfinance library to get historical data for the past month, and we use the plotly.graph_objs module to create an interactive line graph of the data. We then configure the graph layout with a title, axis labels, and other parameters. Finally, we render an HTML template with the graph as a JSON object, using the render_template function from Flask.

To make this code work, you'll need to create an index.html template file in a templates subdirectory of your project directory, with the following contents:

 

<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
  </head>
  <body>
    <div id="graph"></div>
    <script>
      var graphJSON = {{ graphJSON|safe }};
      var graph = document.getElementById('graph');
      Plotly.newPlot(graph, JSON.parse(graphJSON));
    </script>
  </body>
</html>

This template file includes a script tag that loads the Plotly library from a CDN, and a div element with an ID of graph that will be replaced with the actual graph when the page is loaded. The script at the bottom of the file uses the graphJSON variable passed from the Python code to create a new Plotly graph and display it in the graph div.

Once you have the Python and HTML code set up, you can run the server by running the Python script in a terminal or command prompt. The server will start on port 5000 by default, and you can access it by opening a web browser and navigating to http://localhost:5000/. You should see a graph of Tesla's stock price for the past month displayed on the page.

반응형

+ Recent posts