aboutsummaryrefslogtreecommitdiff
path: root/simulate.py
diff options
context:
space:
mode:
authorloit <michael.foiani@gmail.com>2025-07-30 22:42:32 -0400
committerloit <michael.foiani@gmail.com>2025-07-30 22:42:32 -0400
commit65cba4a565c0546da0baf6b625f4d0fb369cf409 (patch)
tree3657d5ad4754ee3e7df1ebf4f63bcded907d19d5 /simulate.py
parent9e58ec4f60cd42111ed4d5d52830c2402bae263b (diff)
work on expanding api to use periods then create the infrastructure for random trials
Diffstat (limited to 'simulate.py')
-rw-r--r--simulate.py82
1 files changed, 77 insertions, 5 deletions
diff --git a/simulate.py b/simulate.py
index 8d69b3d..7b01c21 100644
--- a/simulate.py
+++ b/simulate.py
@@ -1,8 +1,10 @@
from algo import Algo
from ema_algo import Ema_Algo
-from api import fetch_chart_data
+from api import fetch_chart_data, fetch_chart_data_backtest
import datetime
import json
+import random
+import os
"""
Function that takes in data and returns a buy, sell, or hold singal per interval
@@ -67,7 +69,78 @@ def backtest_algo(algo : Algo, timestamps, prices, init_offset=5, starting_money
# store all algo name, buy, sell, price data, timestamps, into a json so it can be viewed as a trial
# caluclate some metrics (NOW: only how much money gained, how many trades, trades per day... etc)
- pass
+ticker_bank = ['BTC-USD', 'ADA-USD', 'ETH-USD', 'ETC-USD', 'DOGE-USD']
+year_bank = [2020, 2021, 2022, 2023, 2024, 2025]
+# time_bank = [0]
+# max_seconds = 24 * 60 * 60
+# timedelta(seconds=rand_second) + datetime(created with 0 time)
+
+"""
+Runs N trials with random parameters
+"""
+def run_batch(batch_name, algo, num_trials=100):
+ i = 1
+ while i <= num_trials:
+ # pick a random set of parameters
+ rand_ticker = ticker_bank[random.randint(0, len(ticker_bank) - 1)]
+ rand_year = year_bank[random.randint(0, len(year_bank) - 1)]
+ rand_day = random.randint(1, 31)
+ rand_month = random.randint(1, 12)
+
+ # ensure the date is valid
+ rand_date = None
+ try:
+ rand_date = datetime.datetime(rand_year, rand_month, rand_day)
+ except ValueError:
+ # date creation failed
+ continue
+
+ # ensure date is not in future
+ curr_date = datetime.datetime.now()
+ if rand_date > curr_date:
+ continue
+
+ # pull chart data for these params and run the algo
+ data = fetch_chart_data_backtest(rand_ticker, '1m', rand_date)
+ results = backtest_algo(algo, data['timestamps'], data['prices'], 13)
+
+ # TODO: make this generalized
+ url_params = {
+ "ticker" : rand_ticker,
+ "period" : '8d',
+ "interval" : '1m',
+ }
+ # store the results in into a file
+ trial_data = {
+ "chart_data" : data,
+ "url_params" : url_params,
+ "backtest_results" : results
+ }
+
+ # make a new directory for the batch
+ path = f'batches_{algo.name}/{batch_name}'
+ if i == 1:
+ print(path)
+ try:
+ os.makedirs(path)
+ except PermissionError:
+ print(f"Permission denied: Unable to create {path}.")
+ return
+ except Exception as e:
+ print(f"An error occurred: {e}")
+ return
+
+ percent_gain = results['percent_gain']
+ date_format = datetime.datetime.isoformat(rand_date)
+ file_name = f'{path}/{percent_gain}_{rand_ticker}_{date_format}.json'
+ fd = open(file_name, 'w')
+ fd.write(json.dumps(trial_data))
+ fd.close()
+
+ # increment trial num
+ i += 1
+
+run_batch('test', Ema_Algo(), 5)
def test():
print("MAIN simulate.py")
@@ -79,7 +152,8 @@ def test():
interval = '1m'
# get data
- data = fetch_chart_data(ticker, period, interval)
+ # data = fetch_chart_data(ticker, period, interval)
+ data = fetch_chart_data_backtest()
print(data.keys())
url_params = {
@@ -101,5 +175,3 @@ def test():
fd = open('bt-recent.json', 'w')
fd.write(json.dumps(trial_data))
fd.close()
-
-test() \ No newline at end of file