feat: Integrate portfolio tracking and cash balance management in trading system
This commit is contained in:
parent
529875527b
commit
838a2ac7d0
@ -7,6 +7,53 @@ from db.db_connection import create_client
|
||||
from trading.position_calculator import PositionCalculator
|
||||
from utils.data_utils import get_user_input
|
||||
|
||||
def create_portfolio_table():
|
||||
with create_client() as client:
|
||||
query = """
|
||||
CREATE TABLE IF NOT EXISTS stock_db.portfolio_history (
|
||||
id UInt32,
|
||||
date DateTime,
|
||||
total_value Float64,
|
||||
cash_balance Float64,
|
||||
notes Nullable(String),
|
||||
created_at DateTime DEFAULT now()
|
||||
) ENGINE = MergeTree()
|
||||
ORDER BY (date, id)
|
||||
"""
|
||||
client.command(query)
|
||||
|
||||
def update_portfolio_value(total_value: float, cash_balance: float, notes: Optional[str] = None):
|
||||
with create_client() as client:
|
||||
query = f"""
|
||||
INSERT INTO stock_db.portfolio_history (
|
||||
id, date, total_value, cash_balance, notes
|
||||
) VALUES (
|
||||
{generate_id()},
|
||||
'{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}',
|
||||
{total_value},
|
||||
{cash_balance},
|
||||
{f"'{notes}'" if notes else 'NULL'}
|
||||
)
|
||||
"""
|
||||
client.command(query)
|
||||
|
||||
def get_latest_portfolio_value() -> Optional[dict]:
|
||||
with create_client() as client:
|
||||
query = """
|
||||
SELECT total_value, cash_balance, date
|
||||
FROM stock_db.portfolio_history
|
||||
ORDER BY date DESC
|
||||
LIMIT 1
|
||||
"""
|
||||
result = client.query(query).result_rows
|
||||
if result:
|
||||
return {
|
||||
'total_value': result[0][0],
|
||||
'cash_balance': result[0][1],
|
||||
'date': result[0][2]
|
||||
}
|
||||
return None
|
||||
|
||||
@dataclass
|
||||
class TradeEntry:
|
||||
ticker: str
|
||||
|
||||
@ -1,21 +1,53 @@
|
||||
from datetime import datetime
|
||||
from trading.position_calculator import PositionCalculator
|
||||
from trading.portfolio import Portfolio, Position
|
||||
from trading.journal import (TradeEntry, add_trade, get_open_trades,
|
||||
create_portfolio_table, update_portfolio_value,
|
||||
get_latest_portfolio_value, get_datetime_input,
|
||||
get_order_type)
|
||||
|
||||
def get_float_input(prompt: str) -> float:
|
||||
while True:
|
||||
try:
|
||||
return float(input(prompt))
|
||||
value = input(prompt)
|
||||
if value.lower() in ['q', 'quit', 'exit']:
|
||||
return None
|
||||
return float(value)
|
||||
except ValueError:
|
||||
print("Please enter a valid number")
|
||||
|
||||
def main():
|
||||
# Get initial portfolio value from user
|
||||
portfolio_value = get_float_input("Enter your portfolio value: $")
|
||||
# Initialize tables
|
||||
create_portfolio_table()
|
||||
|
||||
# Initialize portfolio and position calculator
|
||||
portfolio = Portfolio()
|
||||
calculator = PositionCalculator(account_size=portfolio_value) # Use user's portfolio value
|
||||
# Get latest portfolio value or ask for initial value
|
||||
portfolio_data = get_latest_portfolio_value()
|
||||
if portfolio_
|
||||
portfolio_value = portfolio_data['total_value']
|
||||
cash_balance = portfolio_data['cash_balance']
|
||||
print(f"\nCurrent Portfolio Value: ${portfolio_value:.2f}")
|
||||
print(f"Cash Balance: ${cash_balance:.2f}")
|
||||
print(f"Last Updated: {portfolio_data['date']}")
|
||||
|
||||
if input("\nUpdate portfolio value? (y/n): ").lower() == 'y':
|
||||
new_value = get_float_input("Enter new portfolio value: $")
|
||||
new_cash = get_float_input("Enter new cash balance: $")
|
||||
notes = input("Notes (optional): ")
|
||||
if new_value and new_cash:
|
||||
portfolio_value = new_value
|
||||
cash_balance = new_cash
|
||||
update_portfolio_value(portfolio_value, cash_balance, notes)
|
||||
else:
|
||||
portfolio_value = get_float_input("Enter your initial portfolio value: $")
|
||||
cash_balance = get_float_input("Enter your cash balance: $")
|
||||
if portfolio_value and cash_balance:
|
||||
update_portfolio_value(portfolio_value, cash_balance, "Initial portfolio setup")
|
||||
|
||||
if not portfolio_value or not cash_balance:
|
||||
return
|
||||
|
||||
# Initialize calculator with current portfolio value
|
||||
calculator = PositionCalculator(account_size=portfolio_value)
|
||||
|
||||
while True:
|
||||
print("\nTrading Management System")
|
||||
@ -23,9 +55,10 @@ def main():
|
||||
print("2. Add Position")
|
||||
print("3. View Portfolio")
|
||||
print("4. Remove Position")
|
||||
print("5. Exit")
|
||||
print("5. Update Portfolio Value")
|
||||
print("6. Exit")
|
||||
|
||||
choice = input("\nSelect an option (1-5): ")
|
||||
choice = input("\nSelect an option (1-6): ")
|
||||
|
||||
if choice == "1":
|
||||
try:
|
||||
|
||||
Loading…
Reference in New Issue
Block a user