analyze Korean and US stocks, ETFs, and indices with this indicator. In the code I upload, there is a code to analyze ‘Korean and US stocks, ETFs, and indices’. This code is used to fetch data from yFinance and analyze it.
나는 한국과 미국의 주식, etf, Index를 이 지표로 분석하고 싶어. 내가 업로드하는 코드에 '한국과 미국의 주식, etf, Index' 를 분석하는 코드가 있어. 이를 활용해서yFinance 에서 data를 불러와 분석하는 코드로 Inverse Fisher Python을 바꿔줘
``` from flask import Flask, request, jsonify, render_template, redirect, url_for
import pandas as pd
import numpy as np
import yfinance as yf
from datetime import datetime, timedelta
import matplotlib
matplotlib.use('Agg') # Use a non-GUI backend for Matplotlib
import matplotlib.pyplot as plt
import io
import base64
import os
app = Flask(__name__)
# Function to load data from Yahoo Finance
def load_stock_data(ticker, start_date, end_date):
stock = yf.download(ticker, start=start_date, end=end_date)
stock.reset_index(inplace=True)
return stock
# Function to format the ticker for Yahoo Finance
def format_ticker(ticker):
if ticker.isdigit(): # Korean stock ticker
return ticker + ".KS"
return ticker # US or other tickers
# DMI and ADX Calculation
def calculate_dmi_adx(data, period=14):
high = data['High']
low = data['Low']
close = data['Close']
plus_dm = high.diff()
minus_dm = low.diff()
plus_dm[plus_dm < 0] = 0
minus_dm[minus_dm > 0] = 0
tr1 = high - low
tr2 = abs(high - close.shift(1))
tr3 = abs(low - close.shift(1))
tr = pd.concat([tr1, tr2, tr3], axis=1).max(axis=1)
tr_smooth = tr.rolling(window=period).sum()
plus_dm_smooth = plus_dm.rolling(window=period).sum()
minus_dm_smooth = abs(minus_dm.rolling(window=period).sum())
plus_di = 100 * (plus_dm_smooth / tr_smooth)
minus_di = 100 * (minus_dm_smooth / tr_smooth)
dx = (abs(plus_di - minus_di) / (plus_di + minus_di)) * 100
adx = dx.rolling(window=period).mean()
return plus_di, minus_di, adx
@app.route('/')
def index():
return render_template('index.html')
@app.route('/analyze', methods=['POST'])
def analyze():
ticker = request.form['ticker']
ticker = format_ticker(ticker)
end_date = datetime.now()
start_date = end_date - timedelta(days=200)
data = load_stock_data(ticker, start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'))
if data.empty:
return render_template('index.html', error="No data found for the given ticker. Please try again.")
# Apply DMI and ADX calculation
data['plus_di'], data['minus_di'], data['adx'] = calculate_dmi_adx(data)
# Calculate Bostian's IIX
data['bostian_iix'] = (data['Volume'] * ((data['Close'] - data['Low']) ** 2 - (data['High'] - data['Close']) ** 2) / (data['High'] - data['Low'])).cumsum()
# Volatility Analysis (Bollinger Bandwidth)
length = 20
source = data['Close']
basis = source.rolling(window=length).mean()
dev = source.rolling(window=length).std()
upper = basis + 2 * dev
lower = basis - 2 * dev
data['bandwidth'] = (upper - lower) / basis * 100
# Historical Mean and Standard Deviation
data['historical_mean'] = data['bandwidth'].rolling(window=length).mean()
data['historical_std'] = data['bandwidth'].rolling(window=length).std()
# Percentile Calculation
data['percentile'] = data['bandwidth'].rolling(window=length).apply(lambda x: np.sum(x <= x.iloc[-1]) / len(x) * 100, raw=False)
# Regime Classification
data['regime'] = np.where(data['bandwidth'] > (data['historical_mean'] + data['historical_std']), 'High',
np.where(data['bandwidth'] < (data['historical_mean'] - data['historical_std']), 'Low', 'Normal'))
# Plot Results
plt.figure(figsize=(14, 12))
# Plot Closing Price
plt.subplot(4, 1, 1)
plt.plot(data['Date'], data['Close'], label='Close Price', color='black')
plt.title('Stock Price')
plt.legend()
# Plot Bollinger Bandwidth
plt.subplot(4, 1, 2)
plt.plot(data['Date'], data['bandwidth'], label='Bandwidth', color='blue')
plt.plot(data['Date'], data['historical_mean'], label='Mean', color='green')
plt.plot(data['Date'], data['historical_mean'] + data['historical_std'], label='Mean + 1 Std Dev', color='red')
plt.plot(data['Date'], data['historical_mean'] - data['historical_std'], label='Mean - 1 Std Dev', color='red')
plt.title('Volatility Analysis (Bandwidth)')
plt.legend()
# Plot Bostian's IIX
plt.subplot(4, 1, 3)
plt.plot(data['Date'], data['bostian_iix'], label="Bostian's IIX", color='#2962FF')
plt.fill_between(data['Date'], data['bostian_iix'], color=np.where(data['bostian_iix'] >= 0, '#26A69A', '#B2DFDB'))
plt.title("Bostian's IIX Accumulated")
plt.legend()
# Plot Percentile of Bandwidth
plt.subplot(4, 1, 4)
plt.plot(data['Date'], data['percentile'], label='Bandwidth Percentile', color='purple')
plt.axhline(50, color='gray', linestyle='--', label='Median (50th Percentile)')
plt.title('Percentile of Bandwidth')
plt.legend()
plt.tight_layout()
# Save plot to a PNG image and encode it to base64
img = io.BytesIO()
plt.savefig(img, format='png')
img.seek(0)
plot_url = base64.b64encode(img.getvalue()).decode()
plt.close()
return render_template('result.html', plot_url=plot_url)
@app.route('/favicon.ico')
def favicon():
return '', 204
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host="0.0.0.0", port=port, debug=False) ```
I want you to write a code for printing recent 10 days value of ‘fish’ , can’t you?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
from datetime import datetime, timedelta
from flask import Flask, request, render_template, redirect, url_for
import io
import base64
import os
app = Flask(__name__)
# Function to load data from Yahoo Finance
def load_stock_data(ticker, start_date, end_date):
stock = yf.download(ticker, start=start_date, end=end_date)
stock.reset_index(inplace=True)
return stock
# Function to format the ticker for Yahoo Finance
def format_ticker(ticker):
if ticker.isdigit(): # Korean stock ticker
return ticker + ".KS"
return ticker # US or other tickers
@app.route('/')
def index():
return render_template('index.html')
@app.route('/analyze', methods=['POST'])
def analyze():
ticker = request.form['ticker']
ticker = format_ticker(ticker)
end_date = datetime.now()
start_date = end_date - timedelta(days=200)
data = load_stock_data(ticker, start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'))
if data.empty:
return render_template('index.html', error="No data found for the given ticker. Please try again.")
# Calculate Price as the average of High and Low
data['Price'] = (data['High'] + data['Low']) / 2
# Input length
Len = 10
# Calculate MaxH and MinL for each rolling window of 'Len'
data['MaxH'] = data['Price'].rolling(window=Len).max()
data['MinL'] = data['Price'].rolling(window=Len).min()
# Calculate value11 and value1
data['value11'] = 0.5 * 2 * ((data['Price'] - data['MinL']) / (data['MaxH'] - data['MinL']) - 0.5)
data['value12'] = 0.5 * data['value11'].shift(1)
data['value1'] = data['value11'] + data['value12']
# Clamp value1 between -0.9999 and 0.9999
data['value2'] = data['value1'].apply(lambda x: min(max(x, -0.9999), 0.9999))
# Calculate Inverse Fisher Transform
data['fish1'] = 0.25 * np.log((1 + data['value2']) / (1 - data['value2']))
data['fish2'] = 0.5 * data['fish1'].shift(1)
data['fish'] = data['fish1'] + data['fish2']
# Print recent 10 days of 'fish' values
recent_fish = data[['Date', 'fish']].tail(10)
recent_fish['Date'] = recent_fish['Date'].dt.strftime('%Y-%m-%d') # Convert Date to string for HTML rendering
print("Recent 10 days of 'fish' values:")
print(recent_fish)
# Plotting the results
plt.figure(figsize=(10, 5))
plt.plot(data['Date'], data['fish'], color='red', linewidth=2, label='Fish')
plt.plot(data['Date'], data['fish'].shift(1), color='blue', linewidth=1, label='Fish (Previous)')
plt.axhline(0, color='black', linestyle='--')
plt.legend()
plt.title('Inverse Fisher Transform on High Low')
# Save plot to a PNG image and encode it to base64
img = io.BytesIO()
plt.savefig(img, format='png')
img.seek(0)
plot_url = base64.b64encode(img.getvalue()).decode()
plt.close()
return render_template('result.html', plot_url=plot_url, recent_fish=recent_fish.to_html(index=False, classes='table table-striped'))
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port, debug=False)
I’m going to use this code as a backend and deploy it to Heroku to do a webservice. I’ll upload the index.html and result.html that I’ve used in the past here. Use them as a reference to create index.html and result.html for your frontend. … this is a sample request
At the end of the index.html, create another button and add a link to Trailing Stop Analysis , https://fractaltrail20241130r-51f17984f38c.herokuapp.com/ … this is a sample
The code content appears to be the same, so there was no change detected. Let me provide you with the new index.html
file as you requested, with the additional button for the Trailing Stop Analysis link.