빅데이터 김교수의 "AI노마드연구소" AI로 열어가는 노마드 세상!

빅데이터 김교수의 "AI노마드연구소" AI로 열어가는 노마드 세상입니다. AI 코딩작성, SNS 분석, AI업무자동화 컨설팅 0507-1419-0222

자세히보기

교육/인공지능교육

chatGTP를 이용해서 2023년 테슬라 주가를 예측하는 프로그램을 작성해 보았습니다. 10분만 투자하시면 ..대박!!.^^

빅데이터 김교수 2023. 2. 4. 15:06

안녕하세요 빅데이터 김교수입니다. ^^

 제가 2023년 테슬라 주가 예측분석해 보기 위해 LSTM 알고리즘을 이용해서 코딩해보았습니다. 

 참 좋은 세상이지 않습니까? 전 대박사건이라 생각해요^^

우선 영상을 먼저 참고하시고, 보시면 더욱 효과적으로 이해하실 수 있습니다. 

 

 

 여러분들이 많은 관심을 가지시는 올해 23년도 테슬라 주가 전망을 chatGTP에게 물어보고, 파이썬 프로그램으로 작성해 보았습니다.

작업 순서는 다음과 같습니다.

  1. 명령 프로프트(명령 문장) 만들기
  2. 명령어 실행
    • 이부분은 코랩이라는 프로그램 환경을 구축해야합니다. 이를 위해서는 추가 설명드리겠습니다.

3. 실행결과 디버깅 및 결과 보기

- 이 부분은 파이썬 코딩을 좀 알시는 분이 좋겠으나, 코딩을 몰라도 챗지피티와 대화를 통해 해결은 할 수 있습니다. 

시간이 다소 걸릴 수는 있습니다

자 그럼 챗지티에게 먼저 순서를 물어보았습니다.

Developing a stock price prediction program is a popular use case for machine learning and LSTM is a popular choice for time series data analysis. However, as a language model AI, I can provide you a brief overview of the steps involved in building a stock price prediction program using Python and LSTM:

  1. Data collection(데이터 수집): Collect the historical stock price data for Tesla from a reliable source such as Yahoo Finance.
  2. Data preprocessing(데이터 가공): Clean and preprocess the data to handle missing values, outliers, and to ensure that the data is suitable for modeling.
  3. Feature engineering(형태소화): Create new features from the existing data, such as moving averages, to help the model make better predictions.
  4. Model selection(데이터 분석 모델): Choose an appropriate model for the task, such as a Long Short-Term Memory (LSTM) network.
  5. Model training(인공지능 학습): Train the selected model on the preprocessed data using suitable hyperparameters.
  6. Model evaluation(구현): Evaluate the performance of the trained model on the test data.
  7. Model deployment(신규데이터를 입력해서 적용): Deploy the model to make predictions on new data.

Here is an example of code that you can use to get started with building the LSTM model:

그럼 프롬프트를 정리해 보겠습니다.

 

* 프롬프트는 동일한 내용으로 입력해도 사용자의 사용량과 질의문에 따라 다르게 결과가 나오는 경우가 있으니, 참고하시기 바랍니다.

 

 저는 "

  LSTM알고리즘을 이용해서 테슬라 주가를 예측하는 파이썬 프로그램을 작성해줘 조건은 10년동안 테슬라 주가 그래프를 그려줘.
 변동상 원인이 되는 주가변동, 경기, 금리 등을 반영해서 2023년도 테슬라 주가를 예측해줘. 
그리고, 알고리즘의 정확도로 출력해줘

 "라고 입력했습니다. 

 

 번역한 프롬프트 내용은 " Write a Python program that predicts the Tesla stock price using the LSTM algorithm. The condition is to draw a graph of the Tesla stock price for 10 years.
  Predict the Tesla stock price in 2023 by reflecting stock price fluctuations, economic conditions, interest rates, etc. that cause fluctuations.
And, output it with the accuracy of the algorithm" 입니다. 

 

 챗지피티에게 명령한 결과는 

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import LSTM, Dense
import yfinance as yf

# Get Tesla's stock data from Yahoo Finance
ticker = "TSLA"
df = yf.download(ticker, start="2013-01-01", end="2023-01-01")
df.drop(['Open', 'High', 'Low', 'Adj Close', 'Volume'], axis=1, inplace=True)
df.rename(columns={'Close': 'close'}, inplace=True)

# Scale the stock data
scaler = MinMaxScaler()
df = scaler.fit_transform(df)

# Split the data into training and test sets
train_data = df[:int(df.shape[0] * 0.8), :]
test_data = df[int(df.shape[0] * 0.8):, :]

# Build the LSTM model
look_back = 10
model = Sequential()
model.add(LSTM(10, input_shape=(1, look_back)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')

# Train the model
X_train = np.array([train_data[i:i + look_back, 0] for i in range(train_data.shape[0] - look_back)])
y_train = np.array([train_data[i + look_back, 0] for i in range(train_data.shape[0] - look_back)])
X_train = np.reshape(X_train, (X_train.shape[0], 1, X_train.shape[1]))
model.fit(X_train, y_train, epochs=100, batch_size=1, verbose=0)

# Test the model
X_test = np.array([test_data[i:i + look_back, 0] for i in range(test_data.shape[0] - look_back)])
y_test = np.array([test_data[i + look_back, 0] for i in range(test_data.shape[0] - look_back)])
X_test = np.reshape(X_test, (X_test.shape[0], 1, X_test.shape[1]))
y_pred = model.predict(X_test)

# Inverse transform the predicted data
y_pred = scaler.inverse_transform(y_pred.reshape(-1, 1))

# Plot the actual and predicted stock prices
plt.plot(test_data[:, 0], label="Actual Stock Price")
plt.plot(y_pred, label="Predicted Stock Price")
plt.legend()
plt.show()

 
accuracy = model.evaluate(X_test, y_test, verbose=0)
# Print the accuracy of the model
print("Accuracy: {:.2f}%".format(accuracy * 100))
#Get the last look_back data points of the training set as input for prediction
last_look_back_data = df[-look_back:, 0].reshape(1, 1, look_back)

#Make the prediction for 2023
prediction = model.predict(last_look_back_data)

#Inverse transform the predicted data
prediction = scaler.inverse_transform(prediction.reshape(-1, 1))

# Print the predicted stock price for 2023
print("The predicted stock price for 2023 is: {:.2f}".format(prediction[0][0]))

위의 코드를 실행하면, 정확도는 0,29로 약간 떨어지고 나왔습니다. 여러분들이 알고리즘의 값을 변경하면서 좀더 정확한 주가를 예측해 보시기 바랍니다.