Spaces:
Sleeping
Sleeping
improving requirements
Browse files
app.py
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
from openai import OpenAI
|
| 2 |
import streamlit as st
|
| 3 |
-
import utils as u
|
| 4 |
from langchain_openai import ChatOpenAI
|
| 5 |
from tools import sentiment_analysis_util
|
| 6 |
import numpy as np
|
|
|
|
| 1 |
from openai import OpenAI
|
| 2 |
import streamlit as st
|
|
|
|
| 3 |
from langchain_openai import ChatOpenAI
|
| 4 |
from tools import sentiment_analysis_util
|
| 5 |
import numpy as np
|
utils.py
DELETED
|
@@ -1,177 +0,0 @@
|
|
| 1 |
-
import matplotlib.pyplot as plt
|
| 2 |
-
import plotly.graph_objects as go
|
| 3 |
-
import pandas as pd
|
| 4 |
-
import numpy as np
|
| 5 |
-
from datetime import datetime, timedelta
|
| 6 |
-
import yfinance as yf
|
| 7 |
-
from plotly.subplots import make_subplots
|
| 8 |
-
|
| 9 |
-
def get_stock_price(stockticker: str) -> str:
|
| 10 |
-
ticker = yf.Ticker(stockticker)
|
| 11 |
-
todays_data = ticker.history(period='1d')
|
| 12 |
-
return str(round(todays_data['Close'][0], 2))
|
| 13 |
-
|
| 14 |
-
def plot_candlestick_stock_price(historical_data):
|
| 15 |
-
"""Useful for plotting candlestick plot for stock prices.
|
| 16 |
-
Use historical stock price data from yahoo finance for the week and plot them."""
|
| 17 |
-
df=historical_data[['Close','Open','High','Low']]
|
| 18 |
-
df.index=pd.to_datetime(df.index)
|
| 19 |
-
df.index.names=['Date']
|
| 20 |
-
df=df.reset_index()
|
| 21 |
-
|
| 22 |
-
fig = go.Figure(data=[go.Candlestick(x=df['Date'],
|
| 23 |
-
open=df['Open'],
|
| 24 |
-
high=df['High'],
|
| 25 |
-
low=df['Low'],
|
| 26 |
-
close=df['Close'])])
|
| 27 |
-
fig.show()
|
| 28 |
-
|
| 29 |
-
def historical_stock_prices(stockticker, days_ago):
|
| 30 |
-
"""Upload accurate data to accurate dates from yahoo finance."""
|
| 31 |
-
ticker = yf.Ticker(stockticker)
|
| 32 |
-
end_date = datetime.now()
|
| 33 |
-
start_date = end_date - timedelta(days=days_ago)
|
| 34 |
-
start_date = start_date.strftime('%Y-%m-%d')
|
| 35 |
-
end_date = end_date.strftime('%Y-%m-%d')
|
| 36 |
-
historical_data = ticker.history(start=start_date, end=end_date)
|
| 37 |
-
return historical_data
|
| 38 |
-
|
| 39 |
-
def plot_macd2(df):
|
| 40 |
-
try:
|
| 41 |
-
# Debugging: Print the dataframe columns and a few rows
|
| 42 |
-
print("DataFrame columns:", df.columns)
|
| 43 |
-
print("DataFrame head:\n", df.head())
|
| 44 |
-
|
| 45 |
-
# Convert DataFrame index and columns to numpy arrays
|
| 46 |
-
index = df.index.to_numpy()
|
| 47 |
-
close_prices = df['Close'].to_numpy()
|
| 48 |
-
macd = df['MACD'].to_numpy()
|
| 49 |
-
signal_line = df['Signal_Line'].to_numpy()
|
| 50 |
-
macd_histogram = df['MACD_Histogram'].to_numpy()
|
| 51 |
-
|
| 52 |
-
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(10, 8), gridspec_kw={'height_ratios': [3, 1]})
|
| 53 |
-
|
| 54 |
-
# Subplot 1: Candlestick chart
|
| 55 |
-
ax1.plot(index, close_prices, label='Close', color='black')
|
| 56 |
-
ax1.set_title("Candlestick Chart")
|
| 57 |
-
ax1.set_ylabel("Price")
|
| 58 |
-
ax1.legend()
|
| 59 |
-
|
| 60 |
-
# Subplot 2: MACD
|
| 61 |
-
ax2.plot(index, macd, label='MACD', color='blue')
|
| 62 |
-
ax2.plot(index, signal_line, label='Signal Line', color='red')
|
| 63 |
-
|
| 64 |
-
histogram_colors = np.where(macd_histogram >= 0, 'green', 'red')
|
| 65 |
-
ax2.bar(index, macd_histogram, color=histogram_colors, alpha=0.6)
|
| 66 |
-
|
| 67 |
-
ax2.set_title("MACD")
|
| 68 |
-
ax2.set_ylabel("MACD Value")
|
| 69 |
-
ax2.legend()
|
| 70 |
-
|
| 71 |
-
plt.xlabel("Date")
|
| 72 |
-
plt.tight_layout()
|
| 73 |
-
|
| 74 |
-
return fig
|
| 75 |
-
except Exception as e:
|
| 76 |
-
print(f"Error in plot_macd: {e}")
|
| 77 |
-
return None
|
| 78 |
-
|
| 79 |
-
def plot_macd(df):
|
| 80 |
-
|
| 81 |
-
# Create Figure
|
| 82 |
-
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, row_heights=[0.2, 0.1],
|
| 83 |
-
vertical_spacing=0.15, # Adjust vertical spacing between subplots
|
| 84 |
-
subplot_titles=("Candlestick Chart", "MACD")) # Add subplot titles
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
# Subplot 1: Plot candlestick chart
|
| 88 |
-
fig.add_trace(go.Candlestick(
|
| 89 |
-
x=df.index,
|
| 90 |
-
open=df['Open'],
|
| 91 |
-
high=df['High'],
|
| 92 |
-
low=df['Low'],
|
| 93 |
-
close=df['Close'],
|
| 94 |
-
increasing_line_color='#00cc96', # Green for increasing
|
| 95 |
-
decreasing_line_color='#ff3e3e', # Red for decreasing
|
| 96 |
-
showlegend=False
|
| 97 |
-
), row=1, col=1) # Specify row and column indices
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
# Subplot 2: Plot MACD
|
| 101 |
-
fig.add_trace(
|
| 102 |
-
go.Scatter(
|
| 103 |
-
x=df.index,
|
| 104 |
-
y=df['MACD'],
|
| 105 |
-
mode='lines',
|
| 106 |
-
name='MACD',
|
| 107 |
-
line=dict(color='blue')
|
| 108 |
-
),
|
| 109 |
-
row=2, col=1
|
| 110 |
-
)
|
| 111 |
-
|
| 112 |
-
fig.add_trace(
|
| 113 |
-
go.Scatter(
|
| 114 |
-
x=df.index,
|
| 115 |
-
y=df['Signal_Line'],
|
| 116 |
-
mode='lines',
|
| 117 |
-
name='Signal Line',
|
| 118 |
-
line=dict(color='red')
|
| 119 |
-
),
|
| 120 |
-
row=2, col=1
|
| 121 |
-
)
|
| 122 |
-
|
| 123 |
-
# Plot MACD Histogram with different colors for positive and negative values
|
| 124 |
-
histogram_colors = ['green' if val >= 0 else 'red' for val in df['MACD_Histogram']]
|
| 125 |
-
|
| 126 |
-
fig.add_trace(
|
| 127 |
-
go.Bar(
|
| 128 |
-
x=df.index,
|
| 129 |
-
y=df['MACD_Histogram'],
|
| 130 |
-
name='MACD Histogram',
|
| 131 |
-
marker_color=histogram_colors
|
| 132 |
-
),
|
| 133 |
-
row=2, col=1
|
| 134 |
-
)
|
| 135 |
-
|
| 136 |
-
# Update layout with zoom and pan tools enabled
|
| 137 |
-
layout = go.Layout(
|
| 138 |
-
title='MSFT Candlestick Chart and MACD Subplots',
|
| 139 |
-
title_font=dict(size=12), # Adjust title font size
|
| 140 |
-
plot_bgcolor='#f2f2f2', # Light gray background
|
| 141 |
-
height=600,
|
| 142 |
-
width=1200,
|
| 143 |
-
xaxis_rangeslider=dict(visible=True, thickness=0.03),
|
| 144 |
-
)
|
| 145 |
-
|
| 146 |
-
# Update the layout of the entire figure
|
| 147 |
-
fig.update_layout(layout)
|
| 148 |
-
fig.update_yaxes(fixedrange=False, row=1, col=1)
|
| 149 |
-
fig.update_yaxes(fixedrange=True, row=2, col=1)
|
| 150 |
-
fig.update_xaxes(type='category', row=1, col=1)
|
| 151 |
-
fig.update_xaxes(type='category', nticks=10, row=2, col=1)
|
| 152 |
-
|
| 153 |
-
fig.show()
|
| 154 |
-
#return fig
|
| 155 |
-
|
| 156 |
-
def calculate_MACD(df, fast_period=12, slow_period=26, signal_period=9):
|
| 157 |
-
"""
|
| 158 |
-
Calculates the MACD (Moving Average Convergence Divergence) and related indicators.
|
| 159 |
-
|
| 160 |
-
Parameters:
|
| 161 |
-
df (DataFrame): A pandas DataFrame containing at least a 'Close' column with closing prices.
|
| 162 |
-
fast_period (int): The period for the fast EMA (default is 12).
|
| 163 |
-
slow_period (int): The period for the slow EMA (default is 26).
|
| 164 |
-
signal_period (int): The period for the signal line EMA (default is 9).
|
| 165 |
-
|
| 166 |
-
Returns:
|
| 167 |
-
DataFrame: A pandas DataFrame with the original data and added columns for MACD, Signal Line, and MACD Histogram.
|
| 168 |
-
"""
|
| 169 |
-
|
| 170 |
-
df['EMA_fast'] = df['Close'].ewm(span=fast_period, adjust=False).mean()
|
| 171 |
-
df['EMA_slow'] = df['Close'].ewm(span=slow_period, adjust=False).mean()
|
| 172 |
-
df['MACD'] = df['EMA_fast'] - df['EMA_slow']
|
| 173 |
-
|
| 174 |
-
df['Signal_Line'] = df['MACD'].ewm(span=signal_period, adjust=False).mean()
|
| 175 |
-
df['MACD_Histogram'] = df['MACD'] - df['Signal_Line']
|
| 176 |
-
|
| 177 |
-
return df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|