[당신의 전문 분야, 예: UX 디자인]에 특화된 디지털 일자리를 찾기 위한 플랫
Wikiprompt, 무료 프롬프트 백과사전에서
[당신의 전문 분야, 예: UX 디자인]에 특화된 디지털 일자리를 찾기 위한 플랫 주식 데이터를 스크래핑하고, ML을 적용하여 추세를 예측하며, 결과를 시각화하는 Python 스크립트 생성을 위한 프롬프트입니다.
프롬프트 내용저장
🌐
Here is the optimized Python script that scrapes real-time stock data from Yahoo Finance, applies a machine learning model for short-term trend prediction, and visualizes the results.
```python
import yfinance as yf
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')
# ================= CONFIGURATION =================
TICKER = "AAPL" # Stock symbol
LOOKBACK = 60 # Days of historical data for training
PREDICT_DAYS = 5 # Number of days to predict ahead
TEST_SIZE = 0.2 # Train/test split ratio
# ================= DATA SCRAPING =================
def fetch_stock_data(ticker, period="1y", interval="1d"):
"""Fetch real-time stock data from Yahoo Finance."""
stock = yf.Ticker(ticker)
df = stock.history(period=period, interval=interval)
if df.empty:
raise ValueError(f"No data found for {ticker}")
return df
# ================= FEATURE ENGINEERING =================
def create_features(df):
"""Generate technical indicators and lag features."""
df = df.copy()
# Price-based features
df['Returns'] = df['Close'].pct_change()
df['High_Low_Spread'] = (df['High'] - df['Low']) / df['Close']
df['Close_Open_Spread'] = (df['Close'] - df['Open']) / df['Open']
# Moving averages
df['MA_7'] = df['Close'].rolling(window=7).mean()
df['MA_21'] = df['Close'].rolling(window=21).mean()
df['MA_50'] = df['Close'].rolling(window=50).mean()
# Volatility
df['Volatility'] = df['Returns'].rolling(window=10).std()
# Volume features
df['Volume_MA'] = df['Volume'].rolling(window=7).mean()
df['Volume_Change'] = df['Volume'].pct_change()
# Lag features for time series
for lag in [1, 2, 3, 5]:
df[f'Close_lag_{lag}'] = df['Close'].shift(lag)
df[f'Volume_lag_{lag}'] = df['Volume'].shift(lag)
# Target: future price (next 'PREDICT_DAYS' days average)
df['Target'] = df['Close'].shift(-PREDICT_DAYS).rolling(window=PREDICT_DAYS).mean()
# Drop rows with NaN values
df = df.dropna()
return df
# ================= MODEL TRAINING =================
def train_model(X_train, y_train):
"""Train Random Forest Regressor with optimized parameters."""
model = RandomForestRegressor(
n_estimators=200,
max_depth=10,
min_samples_split=5,
min_samples_leaf=2,
max_features='sqrt',
random_state=42,
n_jobs=-1
)
model.fit(X_train, y_train)
return model
# ================= PREDICTION =================
def predict_future(model, scaler, last_data, days=PREDICT_DAYS):
"""Predict future stock prices using recursive forecasting."""
predictions = []
current_data = last_data.copy()
for _ in range(days):
# Scale the current data
current_scaled = scaler.transform(current_data.reshape(1, -1))
# Predict next value
next_pred = model.predict(current_scaled)[0]
predictions.append(next_pred)
# Update features for next iteration (simplified - in production use full feature engineering)
current_data = np.roll(current_data, -1)
current_data[-1] = next_pred
return predictions
# ================= VISUALIZATION =================
def visualize_results(df, predictions, ticker):
"""Create comprehensive visualization with Matplotlib."""
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
fig.suptitle(f'{ticker} - Stock Price Analysis & Prediction', fontsize=16, fontweight='bold')
# 1. Historical price with moving averages
ax1 = axes[0, 0]
ax1.plot(df.index, df['Close'], label='Close Price', color='blue', linewidth=1.5)
ax1.plot(df.index, df['MA_7'], label='7-Day MA', color='orange', alpha=0.7)
ax1.plot(df.index, df['MA_21'], label='21-Day MA', color='green', alpha=0.7)
ax1.set_title('Historical Price & Moving Averages')
ax1.set_xlabel('Date')
ax1.set_ylabel('Price ($)')
ax1.legend(loc='upper left')
ax1.grid(True, alpha=0.3)
# 2. Volume analysis
ax2 = axes[0, 1]
ax2.bar(df.index, df['Volume'], color='steelblue', alpha=0.6, label='Volume')
ax2.plot(df.index, df['Volume_MA'], color='red', label='7-Day Volume MA')
ax2.set_title('Trading Volume Analysis')
ax2.set_xlabel('Date')
ax2.set_ylabel('Volume')
ax2.legend(loc='upper left')
ax2.grid(True, alpha=0.3)
# 3. Actual vs Predicted (test set)
ax3 = axes[1, 0]
# Split data for visualization
split_idx = int(len(df) * (1 - TEST_SIZE))
test_df = df.iloc[split_idx:]
# Get predictions for test set
X_test = test_df.drop(['Target'], axis=1).values
y_test = test_df['Target'].values
X_test_scaled = scaler.transform(X_test)
y_pred = model.predict(X_test_scaled)
ax3.plot(test_df.index, y_test, label='Actual', color='blue', linewidth=2)
ax3.plot(test_df.index, y_pred, label='Predicted', color='red', linestyle='--', alpha=0.7)
ax3.set_title('Model Performance (Test Set)')
ax3.set_xlabel('Date')
ax3.set_ylabel('Price ($)')
ax3.legend(loc='upper left')
ax3.grid(True, alpha=0.3)
# 4. Future predictions
ax4 = axes[1, 1]
future_dates = [df.index[-1] + timedelta(days=i) for i in range(1, PREDICT_DAYS + 1)]
# Plot historical tail
tail_days = 30
ax4.plot(df.index[-tail_days:], df['Close'][-tail_days:], label='Historical', color='blue', linewidth=2)
# Plot predictions
ax4.plot(future_dates, predictions, label='Predicted', color='red', marker='o', linestyle='--', linewidth=2)
# Add confidence interval (simplified)
std_dev = df['Close'].tail(30).std()
ax4.fill_between(future_dates,
[p - std_dev for p in predictions],
[p + std_dev for p in predictions],
alpha=0.2, color='red', label='Confidence Interval')
ax4.set_title(f'Future Price Prediction ({PREDICT_DAYS} Days)')
ax4.set_xlabel('Date')
ax4.set_ylabel('Price ($)')
ax4.legend(loc='upper left')
ax4.grid(True, alpha=0.3)
# Format x-axis dates
for ax in axes.flat:
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.xaxis.set_major_locator(mdates.AutoDateLocator())
plt.setp(ax.xaxis.get_majorticklabels(), rotation=45, ha='right')
plt.tight_layout()
plt.show()
# ================= MAIN EXECUTION =================
if __name__ == "__main__":
print(f"Fetching data for {TICKER}...")
# Fetch data
stock_data = fetch_stock_data(TICKER)
print(f"Fetched {len(stock_data)} days of data")
# Feature engineering
df = create_features(stock_data)
print(f"Features created: {df.shape[1]} columns")
# Prepare data for training
feature_cols = [col for col in df.columns if col != 'Target']
X = df[feature_cols].values
y = df['Target'].values
# Split data
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=TEST_SIZE, shuffle=False, random_state=42
)
# Scale features
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Train model
print("Training model...")
model = train_model(X_train_scaled, y_train)
# Evaluate model
train_score = model.score(X_train_scaled, y_train)
test_score = model.score(X_test_scaled, y_test)
print(f"Training R² Score: {train_score:.4f}")
print(f"Test R² Score: {test_score:.4f}")
# Make future predictions
print(f"Predicting next {PREDICT_DAYS} days...")
last_data = X[-1] # Use last available data point
future_predictions = predict_future(model, scaler, last_data)
# Display predictions
print("\nPredicted future prices:")
for i, pred in enumerate(future_predictions, 1):
future_date = df.index[-1] + timedelta(days=i)
print(f" {future_date.strftime('%Y-%m-%d')}: ${pred:.2f}")
# Visualize results
print("\nGenerating visualization...")
visualize_results(df, future_predictions, TICKER)
print("\nAnalysis complete!")
```
**Key Features of the Script:**
1. **Real-time Data Scraping**: Uses `yfinance` to fetch live stock data from Yahoo Finance
2. **Feature Engineering**: Creates technical indicators (moving averages, volatility, lag features)
3. **Machine Learning**: Uses Random Forest Regressor optimized for time series prediction
4. **Recursive Forecasting**: Predicts multiple days ahead using recursive prediction
5. **Comprehensive Visualization**: 4-panel matplotlib visualization showing:
- Historical prices with moving averages
- Trading volume analysis
- Model performance on test data
- Future price predictions with confidence intervals
**Dependencies to Install:**
```bash
pip install yfinance pandas numpy scikit-learn matplotlib
```
**Usage:**
- Change the `TICKER` variable to analyze different stocks (e.g., "GOOGL", "MSFT", "TSLA")
- Adjust `PREDICT_DAYS` for different prediction horizons
- Modify `LOOKBACK` to change training window size
The script is optimized with:
- Efficient data handling using pandas
- Parallel processing in Random Forest (`n_jobs=-1`)
- Feature scaling for better model performance
- Clean separation of concerns with modular functions
전체 프롬프트를 보려면 로그인하세요
Continue with:
By logging in, you agree to our Terms of Use and Privacy Policy
사용법
이 프롬프트는 coding와 함께 사용하도록 설계되었습니다. 위의 프롬프트 내용을 복사하여 원하는 AI 도구에 붙여넣으세요.
최상의 결과를 얻으려면 자리 표시자(대괄호 또는 대문자로 표시)를 특정 요구 사항으로 사용자 지정할 수 있습니다.
토론
댓글 0개