Spaces:
Runtime error
Runtime error
import streamlit as st | |
import pandas as pd | |
import numpy as np | |
import yfinance as yf | |
import matplotlib.pyplot as plt | |
# Function to fetch data | |
def fetch_data(ticker, start_date, end_date): | |
data = yf.download(ticker, start=start_date, end=end_date) | |
return data | |
# Function to calculate support and resistance | |
def calculate_support_resistance(data): | |
data['Support'] = data['Low'].rolling(window=20, min_periods=1).min() | |
data['Resistance'] = data['High'].rolling(window=20, min_periods=1).max() | |
return data | |
# Function to plot data | |
def plot_data(data): | |
plt.figure(figsize=(10, 5)) | |
plt.plot(data['Close'], label='Close Price', color='blue') | |
plt.plot(data['Support'], label='Support', linestyle='--', color='green') | |
plt.plot(data['Resistance'], label='Resistance', linestyle='--', color='red') | |
plt.title('Range Trading Strategy Visualization') | |
plt.xlabel('Date') | |
plt.ylabel('Price') | |
plt.legend() | |
plt.grid(True) | |
st.pyplot(plt) | |
# Sidebar | |
st.sidebar.header('User Input Parameters') | |
ticker = st.sidebar.text_input('Ticker Symbol', value='AAPL') | |
start_date = st.sidebar.date_input('Start Date', pd.to_datetime('2020-01-01')) | |
end_date = st.sidebar.date_input('End Date', pd.to_datetime('today')) | |
if st.sidebar.button('Analyze'): | |
data = fetch_data(ticker, start_date, end_date) | |
if not data.empty: | |
data = calculate_support_resistance(data) | |
plot_data(data) | |
else: | |
st.error("No data found for the given ticker and date range. Please adjust your inputs and try again.") | |
# Main screen | |
st.title('Range Trading Strategy Visualizer') | |
st.markdown(""" | |
This app retrieves stock data from Yahoo Finance and visualizes the range trading strategy by identifying and plotting support and resistance levels. | |
To use this app: | |
- Enter the stock ticker symbol in the sidebar. | |
- Choose the start and end date for your analysis. | |
- Click on the 'Analyze' button to display the stock chart with marked support and resistance levels. | |
""") | |