Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 50 additions & 4 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ dependencies = [
"langgraph>=0.2.0",
"langchain-openai>=0.2.0",
"langchain-anthropic>=0.2.0",
"apscheduler (>=3.10.0)",
]


Expand Down
22 changes: 18 additions & 4 deletions src/fin_trade/app.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import streamlit as st
from pathlib import Path

from fin_trade.services import PortfolioService, AgentService, SecurityService
from fin_trade.services import (
PortfolioService,
AgentService,
SecurityService,
ExecutionLogService,
SchedulerService,
)
from fin_trade.pages.overview import render_overview_page
from fin_trade.pages.portfolio_detail import render_portfolio_detail_page
from fin_trade.pages.system_health import render_system_health_page
Expand Down Expand Up @@ -34,9 +40,16 @@ def get_services():
security_service = SecurityService()
portfolio_service = PortfolioService(security_service=security_service)
agent_service = AgentService(security_service=security_service)
return security_service, portfolio_service, agent_service
scheduler_service = SchedulerService(
portfolio_service=portfolio_service,
agent_service=agent_service,
execution_log_service=ExecutionLogService(),
security_service=security_service,
)
scheduler_service.start()
return security_service, portfolio_service, agent_service, scheduler_service

security_service, portfolio_service, agent_service = get_services()
security_service, portfolio_service, agent_service, scheduler_service = get_services()

# Initialize session state
if "current_page" not in st.session_state:
Expand Down Expand Up @@ -118,7 +131,7 @@ def get_services():
st.rerun()

elif st.session_state.current_page == "dashboard":
render_dashboard_page(portfolio_service)
render_dashboard_page(portfolio_service, scheduler_service)

elif st.session_state.current_page == "detail":
if st.session_state.selected_portfolio:
Expand All @@ -141,6 +154,7 @@ def on_navigate_to_portfolio(name: str):
portfolio_service,
agent_service,
security_service,
scheduler_service,
on_back=on_back,
on_navigate_to_portfolio=on_navigate_to_portfolio,
)
Expand Down
2 changes: 2 additions & 0 deletions src/fin_trade/models/portfolio.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ class PortfolioConfig:
asset_class: AssetClass = AssetClass.STOCKS
agent_mode: Literal["simple", "langgraph", "debate"] = "langgraph"
debate_config: DebateConfig | None = None
scheduler_enabled: bool = False
auto_apply_trades: bool = False


@dataclass
Expand Down
104 changes: 59 additions & 45 deletions src/fin_trade/pages/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,22 @@
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
from datetime import datetime, timedelta
from datetime import datetime

from fin_trade.cache import get_portfolio_metrics
from fin_trade.services import PortfolioService, AttributionService, SecurityService
from fin_trade.services import (
PortfolioService,
AttributionService,
SecurityService,
SchedulerService,
)
from fin_trade.services.attribution import SectorAttribution, HoldingAttribution


def render_dashboard_page(portfolio_service: PortfolioService) -> None:
def render_dashboard_page(
portfolio_service: PortfolioService,
scheduler_service: SchedulerService,
) -> None:
"""Render the summary dashboard page."""
st.title("Summary Dashboard")

Expand Down Expand Up @@ -107,51 +115,57 @@ def render_dashboard_page(portfolio_service: PortfolioService) -> None:

st.divider()

# Scheduler Status
st.subheader("Scheduler Status")
status = scheduler_service.get_status()
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Scheduler", "Running" if status["running"] else "Stopped")
with col2:
st.metric("Enabled Schedules", status["enabled"])
with col3:
st.metric("Active Jobs", status["jobs"])

st.divider()

# Upcoming Runs Schedule
st.subheader("Upcoming Scheduled Runs")

schedule_data = []
for p in portfolio_metrics:
last_run = p["Last Run"]
freq = p["Frequency"]

if not last_run:
next_run = datetime.now() # Run immediately if never run
status = "Pending (New)"
else:
if freq == "daily":
next_run = last_run + timedelta(days=1)
elif freq == "weekly":
next_run = last_run + timedelta(weeks=1)
elif freq == "monthly":
next_run = last_run + timedelta(days=30)
else:
next_run = last_run + timedelta(days=1) # Default

if datetime.now() > next_run:
status = "Overdue"

scheduled = scheduler_service.get_scheduled_portfolios()
if not scheduled:
st.info("No portfolios are enabled for scheduled execution.")
else:
schedule_data = []
now = datetime.now()

for item in scheduled:
if item.next_run is None:
status_label = "Pending"
elif item.next_run <= now:
status_label = "Due"
else:
status = "Scheduled"

schedule_data.append({
"Strategy": p["Name"],
"Last Run": last_run,
"Next Run": next_run,
"Status": status
})

df_schedule = pd.DataFrame(schedule_data).sort_values("Next Run")

st.dataframe(
df_schedule,
column_config={
"Last Run": st.column_config.DatetimeColumn("Last Run", format="YYYY-MM-DD HH:mm"),
"Next Run": st.column_config.DatetimeColumn("Next Run", format="YYYY-MM-DD HH:mm"),
"Status": st.column_config.TextColumn("Status"),
},
hide_index=True,
use_container_width=True
)
status_label = "Scheduled"

schedule_data.append({
"Strategy": item.display_name,
"Frequency": item.frequency,
"Last Run": item.last_run,
"Next Run": item.next_run,
"Status": status_label,
})

df_schedule = pd.DataFrame(schedule_data).sort_values("Next Run")

st.dataframe(
df_schedule,
column_config={
"Last Run": st.column_config.DatetimeColumn("Last Run", format="YYYY-MM-DD HH:mm"),
"Next Run": st.column_config.DatetimeColumn("Next Run", format="YYYY-MM-DD HH:mm"),
"Status": st.column_config.TextColumn("Status"),
},
hide_index=True,
use_container_width=True
)

# Performance Attribution Section
st.divider()
Expand Down
75 changes: 73 additions & 2 deletions src/fin_trade/pages/portfolio_detail.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@
import plotly.graph_objects as go

from fin_trade.models import AssetClass, PortfolioConfig, PortfolioState, TradeRecommendation
from fin_trade.services import PortfolioService, AgentService, SecurityService
from fin_trade.services import (
PortfolioService,
AgentService,
SecurityService,
SchedulerService,
)
from fin_trade.agents.service import (
DebateAgentService,
LangGraphAgentService,
Expand Down Expand Up @@ -38,6 +43,7 @@ def render_portfolio_detail_page(
portfolio_service: PortfolioService,
agent_service: AgentService,
security_service: SecurityService,
scheduler_service: SchedulerService,
on_back: Callable | None = None,
on_navigate_to_portfolio: Callable[[str], None] | None = None,
) -> None:
Expand All @@ -64,7 +70,7 @@ def render_portfolio_detail_page(
portfolio_name, config, state, portfolio_service, on_back, on_navigate_to_portfolio
)

_render_summary(config, state, portfolio_service, security_service)
_render_summary(config, state, portfolio_service, security_service, scheduler_service, portfolio_name)

st.divider()

Expand All @@ -90,6 +96,8 @@ def _render_summary(
state: PortfolioState,
portfolio_service: PortfolioService,
security_service: SecurityService,
scheduler_service: SchedulerService,
portfolio_name: str,
) -> None:
"""Render the portfolio summary metrics."""
total_value = portfolio_service.calculate_value(state)
Expand Down Expand Up @@ -132,6 +140,69 @@ def _render_summary(
st.write(f"**LLM:** {config.llm_provider} / {config.llm_model}")
st.write(f"**Agent Mode:** {getattr(config, 'agent_mode', 'simple')}")

with st.expander("Scheduling"):
scheduled = {item.name: item for item in scheduler_service.get_scheduled_portfolios()}
schedule_info = scheduled.get(portfolio_name)

scheduler_enabled = st.toggle(
"Enable scheduled execution",
value=config.scheduler_enabled,
key=f"scheduler_enabled_{portfolio_name}",
help="Automatically run this portfolio on its configured cadence.",
)
if scheduler_enabled != config.scheduler_enabled:
try:
if scheduler_enabled:
scheduler_service.enable_portfolio(portfolio_name)
else:
scheduler_service.disable_portfolio(portfolio_name)
st.rerun()
except Exception as exc:
st.error(f"Failed to update schedule: {exc}")

auto_apply = st.toggle(
"Auto-apply trades",
value=config.auto_apply_trades,
key=f"auto_apply_{portfolio_name}",
help="Automatically apply trade recommendations after each run.",
)
if auto_apply != config.auto_apply_trades:
try:
config.auto_apply_trades = auto_apply
portfolio_service.save_config(config, filename=portfolio_name)
st.rerun()
except Exception as exc:
st.error(f"Failed to update auto-apply setting: {exc}")

last_run = schedule_info.last_run if schedule_info else state.last_execution
next_run = schedule_info.next_run if schedule_info else None

col1, col2 = st.columns(2)
with col1:
st.caption(
f"Last Run: {last_run.strftime('%Y-%m-%d %H:%M') if last_run else 'Never'}"
)
with col2:
if scheduler_enabled and next_run:
st.caption(f"Next Run: {next_run.strftime('%Y-%m-%d %H:%M')}")
elif scheduler_enabled:
st.caption("Next Run: Pending")
else:
st.caption("Next Run: Disabled")

if st.button("Run Now", type="primary", key=f"run_now_{portfolio_name}"):
with st.spinner("Running scheduled execution..."):
try:
success = scheduler_service.run_portfolio_now(portfolio_name)
except Exception as exc:
success = False
st.error(f"Execution failed: {exc}")
if success:
st.success("Execution completed.")
else:
st.error("Execution did not complete successfully.")
st.rerun()


def _render_portfolio_actions(
portfolio_name: str,
Expand Down
Loading