-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
221 lines (183 loc) · 6.93 KB
/
Copy pathdatabase.py
File metadata and controls
221 lines (183 loc) · 6.93 KB
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
"""
database.py
------------
Market-data persistence layer. Same code path works against SQLite
(local/dev) or PostgreSQL (shared/production) -- only DATABASE_URL changes.
Tables
------
bars : OHLCV bars per symbol/timeframe (the "market database" box)
signals : generated signals (audit trail from Signal Generator)
orders : orders sent by the Execution Engine (audit trail / fills)
"""
from __future__ import annotations
import logging
from datetime import datetime
from dataclasses import field
import pandas as pd
from sqlalchemy import (
Column, DateTime, Float, Integer, String, UniqueConstraint,
create_engine, select, delete
)
from sqlalchemy.orm import declarative_base, sessionmaker
import config
logger = logging.getLogger(__name__)
Base = declarative_base()
_engine = None
_SessionFactory = None
class Bar(Base):
__tablename__ = "bars"
id = Column(Integer, primary_key=True, autoincrement=True)
symbol = Column(String(16), nullable=False, index=True)
timeframe = Column(String(8), nullable=False, default="1d")
ts = Column(DateTime, nullable=False, index=True)
open = Column(Float)
high = Column(Float)
low = Column(Float)
close = Column(Float)
volume = Column(Float)
__table_args__ = (
UniqueConstraint("symbol", "timeframe", "ts", name="uix_bar"),
)
class SignalRecord(Base):
__tablename__ = "signals"
id = Column(Integer, primary_key=True, autoincrement=True)
symbol = Column(String(16), nullable=False, index=True)
strategy = Column(String(64), nullable=False)
ts = Column(DateTime, nullable=False, index=True)
signal = Column(Integer, nullable=False) # 1 = long, -1 = flat/short, 0 = no-op
created_at = Column(DateTime, default=datetime.utcnow)
class OrderRecord(Base):
__tablename__ = "orders"
id = Column(Integer, primary_key=True, autoincrement=True)
symbol = Column(String(16), nullable=False, index=True)
action = Column(String(8), nullable=False) # BUY / SELL
quantity = Column(Float, nullable=False)
order_type = Column(String(16), nullable=False)
status = Column(String(32), default="CREATED")
ib_order_id = Column(Integer, nullable=True)
dry_run = Column(Integer, default=1)
created_at = Column(DateTime, default=datetime.utcnow)
def get_engine():
global _engine
if _engine is None:
_engine = create_engine(config.DATABASE_URL, future=True)
return _engine
def init_db() -> None:
"""Create all tables if they don't already exist."""
Base.metadata.create_all(get_engine())
logger.info("Database ready at %s", config.DATABASE_URL)
def get_session():
global _SessionFactory
if _SessionFactory is None:
_SessionFactory = sessionmaker(bind=get_engine(), future=True)
return _SessionFactory()
def upsert_bars(symbol: str, df: pd.DataFrame, timeframe: str = "1d") -> int:
"""
Insert new bars for a symbol, skipping timestamps already stored.
df must be indexed by timestamp with columns: open, high, low, close, volume
"""
if df.empty:
return 0
session = get_session()
try:
existing = set(
session.execute(
select(Bar.ts).where(Bar.symbol == symbol, Bar.timeframe == timeframe)
).scalars().all()
)
new_rows = []
for ts, row in df.iterrows():
ts_naive = pd.Timestamp(ts).to_pydatetime().replace(tzinfo=None)
if ts_naive in existing:
continue
new_rows.append(Bar(
symbol=symbol,
timeframe=timeframe,
ts=ts_naive,
open=float(row.get("open", row.get("Open", float("nan")))),
high=float(row.get("high", row.get("High", float("nan")))),
low=float(row.get("low", row.get("Low", float("nan")))),
close=float(row.get("close", row.get("Close", float("nan")))),
volume=float(row.get("volume", row.get("Volume", 0.0)) or 0.0),
))
if new_rows:
session.bulk_save_objects(new_rows)
session.commit()
return len(new_rows)
finally:
session.close()
def load_bars(
symbols: list[str] | str,
start: str | None = None,
end: str | None = None,
timeframe: str = "1d",
field: str = "close",
) -> pd.DataFrame:
"""
Load stored bars and return a wide DataFrame of the requested OHLCV field.
Parameters
----------
field : str
One of:
"open", "high", "low", "close", "volume"
Defaults to "close" so all existing callers continue to work
without modification.
"""
if isinstance(symbols, str):
symbols = [symbols]
engine = get_engine()
query = select(Bar).where(Bar.symbol.in_(symbols), Bar.timeframe == timeframe)
if start:
query = query.where(Bar.ts >= pd.Timestamp(start).to_pydatetime())
if end:
query = query.where(Bar.ts <= pd.Timestamp(end).to_pydatetime())
df = pd.read_sql(query, engine)
if df.empty:
return pd.DataFrame(columns=symbols)
field = field.lower()
if field not in {"open", "high", "low", "close", "volume"}:
raise ValueError(
f"Unsupported field '{field}'. "
"Choose one of: open, high, low, close, volume."
)
wide = (
df.pivot(index="ts", columns="symbol", values=field)
.sort_index()
)
wide.index.name = "datetime"
return wide[[s for s in symbols if s in wide.columns]]
def load_ohlcv(symbol: str, start: str | None = None, end: str | None = None,
timeframe: str = "1d") -> pd.DataFrame:
"""Load full OHLCV for a single symbol (used by the Feature Engine)."""
engine = get_engine()
query = select(Bar).where(Bar.symbol == symbol, Bar.timeframe == timeframe)
if start:
query = query.where(Bar.ts >= pd.Timestamp(start).to_pydatetime())
if end:
query = query.where(Bar.ts <= pd.Timestamp(end).to_pydatetime())
df = pd.read_sql(query, engine)
if df.empty:
return df
df = df.set_index("ts").sort_index()[["open", "high", "low", "close", "volume"]]
df.index.name = "datetime"
return df
def record_signal(symbol: str, strategy: str, ts, signal: int) -> None:
session = get_session()
try:
session.add(SignalRecord(symbol=symbol, strategy=strategy,
ts=pd.Timestamp(ts).to_pydatetime(), signal=signal))
session.commit()
finally:
session.close()
def record_order(symbol: str, action: str, quantity: float, order_type: str,
status: str = "CREATED", ib_order_id: int | None = None,
dry_run: bool = True) -> None:
session = get_session()
try:
session.add(OrderRecord(
symbol=symbol, action=action, quantity=quantity, order_type=order_type,
status=status, ib_order_id=ib_order_id, dry_run=int(dry_run),
))
session.commit()
finally:
session.close()