Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update the balance model to have more rizz #17

Merged
merged 1 commit into from
Jun 9, 2024
Merged
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
30 changes: 16 additions & 14 deletions database/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from sqlalchemy import Column, Integer, String, Float, DateTime, create_engine, ForeignKey
from sqlalchemy import Column, Integer, String, Float, DateTime, create_engine, ForeignKey, PrimaryKeyConstraint, ForeignKeyConstraint
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from datetime import datetime
Expand All @@ -17,10 +17,9 @@ class Trade(Base):
status = Column(String, nullable=False)
timestamp = Column(DateTime, nullable=False, default=datetime.utcnow)
broker = Column(String, nullable=False)
strategy = Column(String, nullable=False)
strategy = Column(String, nullable=True)
profit_loss = Column(Float, nullable=True)
success = Column(String, nullable=True)
balance_id = Column(Integer, ForeignKey('balances.id'))

class AccountInfo(Base):
__tablename__ = 'account_info'
Expand All @@ -31,31 +30,34 @@ class AccountInfo(Base):
class Balance(Base):
__tablename__ = 'balances'
id = Column(Integer, primary_key=True, autoincrement=True)
broker = Column(String)
strategy = Column(String)
initial_balance = Column(Float, default=0.0)
total_balance = Column(Float, default=0.0)
broker = Column(String, nullable=False)
strategy = Column(String, nullable=True)
type = Column(String, nullable=False) # 'cash' or 'positions'
balance = Column(Float, default=0.0)
timestamp = Column(DateTime, nullable=False, default=datetime.utcnow)
trades = relationship('Trade', backref='balance')
positions = relationship("Position", back_populates="balance")

positions = relationship("Position", back_populates="balance", foreign_keys="[Position.balance_id]", primaryjoin="and_(Balance.id==Position.balance_id, Balance.type=='positions')")

__table_args__ = (
PrimaryKeyConstraint('id', name='balance_pk'),
)

class Position(Base):
__tablename__ = 'positions'

id = Column(Integer, primary_key=True, autoincrement=True)
balance_id = Column(Integer, ForeignKey('balances.id'), nullable=True)
strategy = Column(String)
broker = Column(String, nullable=False)
strategy = Column(String, nullable=True)
balance_id = Column(Integer, ForeignKey('balances.id'), nullable=True)
symbol = Column(String, nullable=False)
quantity = Column(Float, nullable=False)
latest_price = Column(Float, nullable=False)
last_updated = Column(DateTime, nullable=False, default=datetime.utcnow)

balance = relationship("Balance", back_populates="positions")

balance = relationship("Balance", back_populates="positions", foreign_keys=[balance_id])

def drop_then_init_db(engine):
Base.metadata.drop_all(engine) # Create new tables
Base.metadata.drop_all(engine) # Drop existing tables
Base.metadata.create_all(engine) # Create new tables

def init_db(engine):
Expand Down
32 changes: 22 additions & 10 deletions init_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
drop_then_init_db(engine)

# Define brokers and strategies
brokers = ['E*TRADE', 'Tradier', 'Tastytrade']
strategies = ['SMA', 'EMA', 'RSI', 'Bollinger Bands', 'MACD', 'VWAP', 'Ichimoku']
brokers = ['Tradier', 'Tastytrade']
strategies = ['RSI', 'Bollinger Bands', 'MACD', 'Ichimoku']

# Generate unique hourly timestamps for the past 30 days
start_date = datetime.utcnow() - timedelta(days=5)
Expand Down Expand Up @@ -54,20 +54,31 @@
print("Generating and inserting fake balance data and positions...")
for broker in brokers:
for strategy in strategies:
initial_balance = random.uniform(5000, 20000)
initial_cash_balance = random.uniform(5000, 20000)
initial_position_balance = random.uniform(5000, 20000)
for timestamp in timestamps:
total_balance = initial_balance + random.uniform(-1000, 1000) # Simulate some profit/loss
balance_record = Balance(
cash_balance = initial_cash_balance + random.uniform(-1000, 1000) # Simulate some profit/loss for cash
position_balance = initial_position_balance + random.uniform(-1000, 1000) # Simulate some profit/loss for positions
cash_balance_record = Balance(
broker=broker,
strategy=strategy,
initial_balance=initial_balance,
total_balance=total_balance,
type='cash',
balance=cash_balance,
timestamp=timestamp
)
session.add(balance_record)
position_balance_record = Balance(
broker=broker,
strategy=strategy,
type='positions',
balance=position_balance,
timestamp=timestamp
)
session.add(cash_balance_record)
session.add(position_balance_record)
session.commit() # Commit each balance record individually
initial_balance = total_balance # Update the initial balance for the next timestamp
print(f"Inserted balance record for {broker}, {strategy} at {timestamp}. Total balance: {total_balance}")
initial_cash_balance = cash_balance # Update the initial balance for the next timestamp
initial_position_balance = position_balance # Update the initial balance for the next timestamp
print(f"Inserted balance records for {broker}, {strategy} at {timestamp}. Cash balance: {cash_balance}, Position balance: {position_balance}")

# Generate and insert fake positions for each balance record
for symbol in ['AAPL', 'GOOG', 'TSLA', 'MSFT', 'NFLX', 'AMZN', 'FB', 'NVDA']:
Expand Down Expand Up @@ -98,3 +109,4 @@
session.add_all(fake_accounts)
session.commit()
print("Fake account data inserted into the database.")

6 changes: 4 additions & 2 deletions strategies/base_strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,16 @@ def initialize_starting_balance(self):
with self.broker.Session() as session:
strategy_balance = session.query(Balance).filter_by(
strategy=self.strategy_name,
broker=self.broker.broker_name
broker=self.broker.broker_name,
type='cash'
).first()

if strategy_balance is None:
strategy_balance = Balance(
strategy=self.strategy_name,
broker=self.broker.broker_name,
total_balance=self.starting_capital
type='cash',
balance=self.starting_capital
)
session.add(strategy_balance)
session.commit()
11 changes: 6 additions & 5 deletions strategies/constant_percentage_strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@ def rebalance(self):
with self.broker.Session() as session:
balance = session.query(Balance).filter_by(
strategy=self.strategy_name,
broker=self.broker.broker_name
broker=self.broker.broker_name,
type='cash'
).first()
if balance is None:
raise ValueError("Strategy balance not initialized for {self.strategy_name} strategy on {self.broker}.")
total_balance = balance.total_balance
raise ValueError(f"Strategy balance not initialized for {self.strategy_name} strategy on {self.broker}.")
total_balance = balance.balance

target_cash_balance = total_balance * self.cash_percentage
target_investment_balance = total_balance - target_cash_balance
Expand All @@ -37,9 +38,9 @@ def rebalance(self):
current_price = self.broker.get_current_price(stock)
target_quantity = target_balance // current_price
if current_position < target_quantity:
self.broker.place_order(stock, target_quantity - current_position, 'buy', 'constant_percentage')
self.broker.place_order(stock, target_quantity - current_position, 'buy', self.strategy_name)
elif current_position > target_quantity:
self.broker.place_order(stock, current_position - target_quantity, 'sell', 'constant_percentage')
self.broker.place_order(stock, current_position - target_quantity, 'sell', self.strategy_name)

def get_current_positions(self):
positions = self.broker.get_positions()
Expand Down
2 changes: 1 addition & 1 deletion trading-dashboard/src/Dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ const Dashboard = () => {
}
historicalData[key].push({
x: item.hour,
y: item.total_balance
y: item.balance
});
}
});
Expand Down
6 changes: 3 additions & 3 deletions ui/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,19 @@ def historic_balance_per_strategy():
Balance.strategy,
Balance.broker,
func.strftime('%Y-%m-%d %H', Balance.timestamp).label('hour'),
Balance.total_balance,
Balance.balance,
).group_by(
Balance.strategy, Balance.broker, 'hour'
).order_by(
Balance.strategy, Balance.broker, 'hour'
).all()
historical_balances_serializable = []
for strategy, broker, hour, total_balance in historical_balances:
for strategy, broker, hour, balance in historical_balances:
historical_balances_serializable.append({
"strategy": strategy,
"broker": broker,
"hour": hour,
"total_balance": total_balance
"balance": balance
})
return jsonify({"historic_balance_per_strategy": historical_balances_serializable})
finally:
Expand Down
Loading