Spaces:
Running
Running
File size: 2,210 Bytes
4414ced 649b4ce 4414ced 649b4ce 4414ced 649b4ce |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
import yfinance as yf
import pandas as pd
import plotly.graph_objects as go
import streamlit as st
# Sidebar inputs for stock symbol
sidebar = st.sidebar
symbol = sidebar.text_input("Enter stock symbol:", "AAPL")
data = yf.download(symbol, start="2020-01-01", end="2021-01-01")
# Check if data is empty
if data.empty:
st.error("No data available for the selected symbol. Please try another symbol.")
else:
# Determine the valid date range for Fibonacci analysis
min_date, max_date = data.index.min().date(), data.index.max().date()
# Dynamic default dates based on data range
default_start, default_end = min_date, max_date
# Sidebar inputs for Fibonacci time frame
fib_start_date = sidebar.date_input("Fibonacci Start Date", value=default_start, min_value=min_date, max_value=max_date)
fib_end_date = sidebar.date_input("Fibonacci End Date", value=default_end, min_value=min_date, max_value=max_date)
if fib_start_date >= fib_end_date:
st.error("Error: The start date must be before the end date.")
else:
# Filter data for Fibonacci analysis
fib_data = data.loc[fib_start_date:fib_end_date]
# Calculate high and low prices for Fibonacci levels
high_price = fib_data['High'].max()
low_price = fib_data['Low'].min()
# Fibonacci retracement levels
fib_levels = [0, 0.236, 0.382, 0.5, 0.618, 0.786, 1]
price_diff = high_price - low_price
# Initialize figure for plotting
fig = go.Figure()
# Plot close prices and moving averages
fig.add_trace(go.Scatter(x=data.index, y=data['Close'], name='Close Price', line=dict(color='black')))
for ma in [20, 50, 200]:
ma_label = f"MA{ma}"
data[ma_label] = data['Close'].rolling(window=ma).mean()
fig.add_trace(go.Scatter(x=data.index, y=data[ma_label], name=ma_label, line=dict(width=2)))
# Plot Fibonacci levels
for level in fib_levels:
value = high_price - (price_diff * level)
fig.add_hline(y=value, line_dash="dot", annotation_text=f"{level*100}%", annotation_position="right")
# Display chart
st.plotly_chart(fig)
|