-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathinit_db.py
174 lines (158 loc) · 8.56 KB
/
init_db.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import asyncio
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from database.models import Trade, AccountInfo, Balance, Position, drop_then_init_db
from datetime import datetime, timedelta, UTC
import random
DATABASE_URL = "sqlite+aiosqlite:///trading.db"
engine = create_async_engine(DATABASE_URL, echo=True)
Session = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)
async def main():
async with engine.begin() as conn:
# Initialize the database
await drop_then_init_db(engine)
async with Session() as session:
# Define brokers and strategies
brokers = ['tradier', 'tastytrade']
strategies = ['RSI', 'MACD']
# Generate unique hourly timestamps for the past 5 days
start_date = datetime.now(UTC) - timedelta(days=5)
end_date = datetime.now(UTC)
timestamps = [start_date + timedelta(hours=i) for i in range((end_date - start_date).days * 24)]
# Generate fake trade data
num_trades_per_hour = 1 # Number of trades per hour
fake_trades = []
print("Generating fake trade data...")
for timestamp in timestamps:
for _ in range(num_trades_per_hour):
side = random.choice(['buy', 'sell'])
quantity = random.randint(1, 20)
price = random.uniform(100, 3000)
executed_price = price if side == 'buy' else price + random.uniform(-50, 50)
profit_loss = None if side == 'buy' else (executed_price - price) * quantity
fake_trades.append(Trade(
symbol=random.choice(['AAPL', 'GOOG', 'TSLA', 'MSFT', 'NFLX', 'AMZN', 'FB', 'NVDA']),
quantity=quantity,
price=price,
executed_price=executed_price,
side=side,
status='executed',
timestamp=timestamp,
broker=random.choice(brokers),
strategy=random.choice(strategies),
profit_loss=profit_loss,
success=random.choice(['yes', 'no'])
))
print("Fake trade data generation completed.")
# Insert fake trades into the database
print("Inserting fake trades into the database...")
session.add_all(fake_trades)
await session.commit()
print("Fake trades inserted into the database.")
# Option symbols example
option_symbols = [
'AAPL230721C00250000', 'GOOG230721P00150000', 'TSLA230721C01000000', 'MSFT230721P00200000'
]
# Generate and insert fake balance data and positions
print("Generating and inserting fake balance data and positions...")
for broker in brokers:
# Generate uncategorized balances for each broker
initial_cash_balance_uncategorized = round(random.uniform(5000, 20000), 2)
initial_position_balance_uncategorized = round(random.uniform(5000, 20000), 2)
for timestamp in timestamps:
cash_balance_uncategorized = initial_cash_balance_uncategorized + round(random.uniform(-1000, 1000), 2)
position_balance_uncategorized = initial_position_balance_uncategorized + round(random.uniform(-1000, 1000), 2)
cash_balance_record_uncategorized = Balance(
broker=broker,
strategy='uncategorized',
type='cash',
balance=cash_balance_uncategorized,
timestamp=timestamp
)
position_balance_record_uncategorized = Balance(
broker=broker,
strategy='uncategorized',
type='positions',
balance=position_balance_uncategorized,
timestamp=timestamp
)
session.add(cash_balance_record_uncategorized)
session.add(position_balance_record_uncategorized)
await session.commit()
initial_cash_balance_uncategorized = cash_balance_uncategorized
initial_position_balance_uncategorized = position_balance_uncategorized
print(f"Inserted uncategorized balance records for {broker} at {timestamp}. Cash balance: {cash_balance_uncategorized}, Position balance: {position_balance_uncategorized}")
for strategy in strategies:
initial_cash_balance = round(random.uniform(5000, 20000), 2)
initial_position_balance = round(random.uniform(5000, 20000), 2)
for timestamp in timestamps:
cash_balance = initial_cash_balance + round(random.uniform(-1000, 1000), 2) # Simulate some profit/loss for cash
position_balance = initial_position_balance + round(random.uniform(-1000, 1000), 2) # Simulate some profit/loss for positions
cash_balance_record = Balance(
broker=broker,
strategy=strategy,
type='cash',
balance=cash_balance,
timestamp=timestamp
)
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)
await session.commit() # Commit each balance record individually
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']:
quantity = random.randint(1, 100)
latest_price = round(random.uniform(100, 3000), 2)
cost_basis = quantity * latest_price
position_record = Position(
broker=broker,
strategy=strategy,
symbol=symbol,
quantity=quantity,
latest_price=latest_price,
cost_basis=cost_basis,
last_updated=timestamp
)
session.add(position_record)
await session.commit()
print(f"Inserted position record for {broker}, {strategy}, {symbol} at {timestamp}. Quantity: {quantity}, Latest price: {latest_price}, Cost basis: {cost_basis}")
# Generate and insert fake positions for option symbols
for symbol in option_symbols:
quantity = random.randint(1, 100)
latest_price = round(random.uniform(1, 100), 2) # Options prices are generally lower
cost_basis = quantity * latest_price
position_record = Position(
broker=broker,
strategy=strategy,
symbol=symbol,
quantity=quantity,
latest_price=latest_price,
cost_basis=cost_basis,
last_updated=timestamp
)
session.add(position_record)
await session.commit()
print(f"Inserted position record for {broker}, {strategy}, {symbol} at {timestamp}. Quantity: {quantity}, Latest price: {latest_price}, Cost basis: {cost_basis}")
print("Fake balance data and positions generation and insertion completed.")
# Generate fake account data
fake_accounts = [
AccountInfo(broker='E*TRADE', value=10000.0),
AccountInfo(broker='Tradier', value=15000.0),
AccountInfo(broker='Tastytrade', value=20000.0),
]
# Insert fake account data into the database
print("Inserting fake account data into the database...")
session.add_all(fake_accounts)
await session.commit()
print("Fake account data inserted into the database.")
# Run the async function
asyncio.run(main())