Skip to content

Commit 24a4ecc

Browse files
committed
fix: fixing sec.
1 parent c955456 commit 24a4ecc

File tree

13 files changed

+198
-55
lines changed

13 files changed

+198
-55
lines changed

β€Žbullish/analysis/analysis.pyβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -666,6 +666,7 @@ def run_signal_series_analysis(bullish_db: "BullishDb") -> None:
666666

667667

668668
def run_analysis(bullish_db: "BullishDb") -> None:
669+
bullish_db.copy_sec_to_analysis()
669670
tickers = list(set(bullish_db._read_tracker(TrackerQuery(), PriceTracker)))
670671
parallel = Parallel(n_jobs=-1)
671672

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""
2+
3+
Revision ID: 55553b8098f9
4+
Revises: c06dc04e782b
5+
Create Date: 2025-11-19 20:51:32.350934
6+
7+
"""
8+
9+
from typing import Sequence, Union
10+
11+
from alembic import op
12+
import sqlalchemy as sa
13+
from sqlalchemy.dialects import sqlite
14+
15+
# revision identifiers, used by Alembic.
16+
revision: str = "55553b8098f9"
17+
down_revision: Union[str, None] = "c06dc04e782b"
18+
branch_labels: Union[str, Sequence[str], None] = None
19+
depends_on: Union[str, Sequence[str], None] = None
20+
21+
22+
def upgrade() -> None:
23+
# ### commands auto generated by Alembic - please adjust! ###
24+
25+
with op.batch_alter_table("analysis", schema=None) as batch_op:
26+
batch_op.add_column(sa.Column("occurrences", sa.Integer(), nullable=True))
27+
batch_op.add_column(sa.Column("total_value", sa.Float(), nullable=True))
28+
batch_op.add_column(sa.Column("total_increase", sa.Float(), nullable=True))
29+
batch_op.create_index("ix_analysis_occurrences", ["occurrences"], unique=False)
30+
batch_op.create_index(
31+
"ix_analysis_total_increase", ["total_increase"], unique=False
32+
)
33+
batch_op.create_index("ix_analysis_total_value", ["total_value"], unique=False)
34+
35+
# ### end Alembic commands ###
36+
37+
38+
def downgrade() -> None:
39+
# ### commands auto generated by Alembic - please adjust! ###
40+
with op.batch_alter_table("analysis", schema=None) as batch_op:
41+
batch_op.drop_index("ix_analysis_total_value")
42+
batch_op.drop_index("ix_analysis_total_increase")
43+
batch_op.drop_index("ix_analysis_occurrences")
44+
batch_op.drop_column("total_increase")
45+
batch_op.drop_column("total_value")
46+
batch_op.drop_column("occurrences")

β€Žbullish/database/crud.pyβ€Ž

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -62,13 +62,21 @@ def _engine(self) -> Engine:
6262
if not self.valid():
6363
raise DatabaseFileNotFoundError("Database file not found.")
6464
database_url = f"sqlite:///{Path(self.database_path)}"
65+
try:
66+
upgrade(self.database_path)
67+
except Exception as e:
68+
print(
69+
f"Failed to upgrade the database at {self.database_path}. "
70+
f"Reason: {e}"
71+
"Skipping upgrade. "
72+
)
73+
logger.error(
74+
f"Failed to upgrade the database at {self.database_path}. "
75+
f"Reason: {e}"
76+
"Skipping upgrade. "
77+
)
6578
engine = create_engine(database_url)
6679
inspector = inspect(engine)
67-
if "analysis" not in inspector.get_table_names():
68-
upgrade(self.database_path)
69-
70-
engine = create_engine(database_url)
71-
inspector = inspect(engine)
7280
if "subject" not in inspector.get_table_names():
7381
logger.info(
7482
"Running tickermood upgrade to create the subject table in the database."
@@ -116,20 +124,33 @@ def read_symbols(self) -> List[str]:
116124
data = pd.read_sql_query(query, self._engine)
117125
return data["symbol"].tolist()
118126

127+
def copy_sec_to_analysis(self) -> None:
128+
with Session(self._engine) as session:
129+
query = text(
130+
"""UPDATE analysis
131+
SET
132+
occurrences = (SELECT secshareincrease.occurrences
133+
FROM secshareincrease WHERE secshareincrease.ticker = analysis.symbol),
134+
total_value = (SELECT secshareincrease.total_value
135+
FROM secshareincrease WHERE secshareincrease.ticker = analysis.symbol),
136+
total_increase = (SELECT secshareincrease.total_increase
137+
FROM secshareincrease WHERE secshareincrease.ticker = analysis.symbol)
138+
WHERE EXISTS (SELECT 1 FROM secshareincrease WHERE secshareincrease.ticker = analysis.symbol);"""
139+
)
140+
session.exec(query) # type: ignore
141+
session.commit()
142+
119143
def _read_analysis_data(
120144
self, columns: List[str], symbols: Optional[List[str]] = None
121145
) -> pd.DataFrame:
122-
columns__ = columns.copy()
123146

124-
columns_ = ",".join(columns__)
147+
columns_ = ",".join(columns)
125148

126149
if symbols:
127150
symbols_str = ",".join([f"'{s}'" for s in symbols])
128-
query = f"""SELECT {columns_} FROM analysis
129-
LEFT JOIN secshareincrease ON secshareincrease.ticker=analysis.symbol WHERE symbol IN ({symbols_str})""" # noqa: S608
151+
query = f"""SELECT {columns_} FROM analysis WHERE symbol IN ({symbols_str})""" # noqa: S608
130152
else:
131-
query = f"""SELECT {columns_} FROM analysis
132-
LEFT JOIN secshareincrease ON secshareincrease.ticker=analysis.symbol""" # noqa: S608
153+
query = f"""SELECT {columns_} FROM analysis""" # noqa: S608
133154
return pd.read_sql_query(query, self._engine)
134155

135156
def _read_filter_query(self, query: str) -> pd.DataFrame:

β€Žbullish/interface/interface.pyβ€Ž

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -35,26 +35,17 @@ def read_filter_query(self, query: FilterQuery) -> pd.DataFrame:
3535

3636
query_ = query.to_query()
3737
columns = list(AnalysisView.model_fields)
38-
columns_copy = columns.copy()
39-
if "name" in columns_copy:
40-
columns_copy.remove("name")
41-
columns_copy.append("analysis.name AS name")
42-
fields = ",".join(columns_copy)
38+
fields = ",".join(columns)
4339
query_str: str = f"""
44-
SELECT {fields} FROM analysis
45-
LEFT JOIN secshareincrease ON secshareincrease.ticker=analysis.symbol WHERE {query_}
40+
SELECT {fields} FROM analysis WHERE {query_}
4641
""" # noqa: S608
4742
return self._read_filter_query(query_str)
4843

4944
def read_analysis_data(
5045
self, columns: Optional[List[str]] = None, symbols: Optional[List[str]] = None
5146
) -> pd.DataFrame:
5247
columns = columns or list(AnalysisView.model_fields)
53-
columns_copy = columns.copy()
54-
if "name" in columns_copy:
55-
columns_copy.remove("name")
56-
columns_copy.append("analysis.name AS name")
57-
data = self._read_analysis_data(columns_copy, symbols=symbols)
48+
data = self._read_analysis_data(columns, symbols=symbols)
5849
if set(data.columns) != set(columns):
5950
raise ValueError(
6051
f"Expected columns {columns}, but got {data.columns.tolist()}"

β€Žpoetry.lockβ€Ž

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žpyproject.tomlβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ readme = "README.md"
77
packages = [{ include = "bullish" }]
88
[tool.poetry.dependencies]
99
python = ">=3.12,<3.13"
10-
bearishpy = ">=0.45.0, <1.0.0"
10+
bearishpy = ">=0.49.0, <1.0.0"
1111
tickermood = "^0.29.0"
1212
streamlit = "^1.45.1"
1313
streamlit-pydantic = "^v0.6.1-rc.3"

β€Žtests/conftest.pyβ€Ž

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,6 @@
1212

1313

1414
DATABASE_PATH = Path(__file__).parent / "data" / "bear.db"
15-
DATABASE_PATH_VIEW = Path(__file__).parent / "data" / "filter_bear.db"
16-
DATABASE_PATH_WITH_SERIES = Path(__file__).parent / "data" / "filter_bear_series.db"
1715

1816

1917
def delete_tables(database_path: Path):
@@ -33,38 +31,39 @@ def delete_tables(database_path: Path):
3331
conn.commit()
3432

3533

36-
@pytest.fixture
34+
@pytest.fixture(scope="session")
3735
def bullish_db() -> BullishDb:
3836
delete_tables(DATABASE_PATH)
3937

4038
return BullishDb(database_path=DATABASE_PATH)
4139

4240

43-
@pytest.fixture
41+
@pytest.fixture(scope="session")
4442
def bullish_db_with_analysis(bullish_db: BullishDb) -> BullishDb:
4543
run_analysis(bullish_db)
4644
return bullish_db
4745

4846

49-
@pytest.fixture
50-
def bullish_view() -> BullishDb:
51-
return BullishDb(database_path=DATABASE_PATH_VIEW)
47+
@pytest.fixture(scope="session")
48+
def bullish_view(bullish_db: BullishDb) -> BullishDb:
49+
run_analysis(bullish_db)
50+
return bullish_db
5251

5352

54-
@pytest.fixture
53+
@pytest.fixture(scope="session")
5554
def data_aapl(bullish_db: BullishDb) -> pd.DataFrame:
5655
ticker = Ticker(symbol="AAPL")
5756
prices = Prices.from_ticker(bullish_db, ticker)
5857
return prices.to_dataframe()
5958

6059

61-
@pytest.fixture
60+
@pytest.fixture(scope="session")
6261
def bullish_db_with_signal_series(bullish_view: BullishDb) -> BullishDb:
6362

6463
bullish_db = BullishDb(database_path=DATABASE_PATH_WITH_SERIES)
6564
return bullish_db
6665

6766

68-
@pytest.fixture
67+
@pytest.fixture(scope="session")
6968
def custom_filter_path() -> Path:
7069
return Path(__file__).parent / "data" / "custom_filter.json"

β€Žtests/data/bear.dbβ€Ž

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
version https://git-lfs.github.com/spec/v1
2-
oid sha256:dec564bf631cdd7fcb9752baf4ba1b354bb93041a5c61aff9ccf8cb72387d387
3-
size 163594240
2+
oid sha256:a1d78672d9ba33ca4a140730f5089fcdb25f36e84e48a232e3669c12ac0e8870
3+
size 186888192

β€Žtests/data/custom_filter.jsonβ€Ž

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
[
22
{
33
"symbol": [
4-
"BPOST.BR",
5-
"LOTB.BR"
4+
"AAPL",
5+
"NVDA"
66
],
77
"name": "Sold Positions"
88
},
99
{
1010
"symbol": [
11-
"KBC.BR"
11+
"AMZN"
1212
],
1313
"name": "Selection"
1414
}

β€Žtests/data/filter_bear.dbβ€Ž

Lines changed: 0 additions & 3 deletions
This file was deleted.

0 commit comments

Comments
Β (0)