Skip to content

Commit f01e27d

Browse files
committed
- Algorithm status iterator
- Add example for running algorithm as iterator - Add objects instead of dicts in result Dataframe - Add max_leverage parameter Signed-off-by: Nikola Losic <nikolalosic@protonmail.ch>
1 parent 798ba8d commit f01e27d

17 files changed

Lines changed: 654 additions & 298 deletions

examples/algorithms/test_algo/test_algo.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,5 +38,7 @@ async def handle_data(context, data):
3838
num_assets = len(context.assets)
3939
target_percent = 1.0 / num_assets
4040
for asset in context.assets:
41-
await context.order_target_percent(asset=asset,
42-
target=target_percent, style=MarketOrder())
41+
# await context.order_target_percent(asset=asset,
42+
# target=target_percent, style=MarketOrder())
43+
await context.order_target(asset=asset,
44+
target=0.1, style=MarketOrder())

examples/run_simulation_daily.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,10 +83,23 @@ async def _run_simulation():
8383
logger.error(result.errors)
8484
print(result.perf.head(n=10).to_markdown())
8585

86+
cash_flow = {"date": [], "cash_change": [], "cash_left": []}
87+
88+
8689
# Get cash from algo
8790
start_cash = sum(exchange.get_start_cash_balance() for exchange in result.trading_algorithm.exchanges.values())
8891
logger.info(f"Starting_cash: {start_cash}")
8992

93+
for transaction_freq in result.perf.transactions:
94+
for transaction in transaction_freq:
95+
print(transaction)
96+
start_cash -= transaction.total_price()
97+
cash_flow["date"].append(transaction.dt)
98+
cash_flow["cash_change"].append(-transaction.total_price())
99+
cash_flow["cash_left"].append(start_cash)
100+
101+
cash_flow_df = pl.DataFrame(data=cash_flow)
102+
print(cash_flow)
90103

91104
if __name__ == "__main__":
92105
configure_logging(level=logging.INFO, file_name="mylog.log")
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import asyncio
2+
import datetime
3+
import logging
4+
import pathlib
5+
6+
import polars as pl
7+
import structlog
8+
9+
from ziplime.utils.bundle_utils import get_bundle_service
10+
from ziplime.utils.logging_utils import configure_logging
11+
12+
from pathlib import Path
13+
14+
import pytz
15+
16+
from ziplime.core.ingest_data import get_asset_service
17+
from ziplime.core.run_simulation import run_simulation_iter
18+
from ziplime.finance.commission import PerShare, DEFAULT_PER_SHARE_COST, DEFAULT_MINIMUM_COST_PER_EQUITY_TRADE
19+
20+
logger = structlog.get_logger(__name__)
21+
22+
23+
async def _run_simulation():
24+
start_date = datetime.datetime(year=2025, month=1, day=3, tzinfo=pytz.timezone("America/New_York"))
25+
end_date = datetime.datetime(year=2025, month=2, day=1, tzinfo=pytz.timezone("America/New_York"))
26+
27+
bundle_service = get_bundle_service()
28+
29+
asset_service = get_asset_service(
30+
clear_asset_db=False,
31+
db_path=str(pathlib.Path(__file__).parent.parent.resolve().joinpath("data", "assets.sqlite"))
32+
)
33+
# Use aggregations if you ingested data of frequnecy less than 1 day
34+
aggregations = [
35+
pl.col("open").first(),
36+
pl.col("high").max(),
37+
pl.col("low").min(),
38+
pl.col("close").last(),
39+
pl.col("volume").sum(),
40+
pl.col("symbol").last()
41+
]
42+
market_data_bundle = await bundle_service.load_bundle(bundle_name="limex_us_minute_data",
43+
bundle_version=None,
44+
frequency=datetime.timedelta(days=1),
45+
start_date=start_date,
46+
end_date=end_date,
47+
symbols=["META", "AAPL", "AMZN", "NFLX", "GOOGL",
48+
],
49+
start_auction_delta=datetime.timedelta(minutes=15),
50+
end_auction_delta=datetime.timedelta(minutes=15),
51+
aggregations=aggregations,
52+
)
53+
54+
custom_data_sources = []
55+
# custom_data_sources.append(
56+
# await bundle_service.load_bundle(bundle_name="limex_us_fundamental_data", bundle_version=None))
57+
58+
equity_commission = PerShare(
59+
cost=DEFAULT_PER_SHARE_COST,
60+
min_trade_cost=DEFAULT_MINIMUM_COST_PER_EQUITY_TRADE,
61+
62+
)
63+
64+
# run daily simulation
65+
async for status in run_simulation_iter(
66+
start_date=start_date,
67+
end_date=end_date,
68+
trading_calendar="NYSE",
69+
algorithm_file=str(Path("algorithms/test_algo/test_algo.py").absolute()),
70+
total_cash=100000.0,
71+
market_data_source=market_data_bundle,
72+
custom_data_sources=custom_data_sources,
73+
config_file=str(Path("algorithms/test_algo/test_algo_config.json").absolute()),
74+
emission_rate=datetime.timedelta(days=1),
75+
benchmark_asset_symbol="AAPL",
76+
benchmark_returns=None,
77+
stop_on_error=True,
78+
asset_service=asset_service,
79+
equity_commission=equity_commission
80+
):
81+
print(status)
82+
if status.errors:
83+
logger.error(status.errors)
84+
if status.result:
85+
logger.info("Algorithm finished")
86+
# print(status.perf.head(n=10).to_markdown())
87+
88+
# Get cash from algo
89+
90+
91+
if __name__ == "__main__":
92+
configure_logging(level=logging.INFO, file_name="mylog.log")
93+
asyncio.run(_run_simulation())

0 commit comments

Comments
 (0)