<jupyter_start><jupyter_text>사용법1. *런타임 -> 모두 실행* 선택2. 맨 밑 원하는 변수 입력3. 구글 드라이브에서 csv 결과 파일 확인<jupyter_code>from google.colab import drive

drive.mount('/content/drive')
cd /content/drive/MyDrive/Colab_Notebooks

ls
import numpy as np
import pandas as pd
import datetime<jupyter_output><empty_output><jupyter_text>- data: 날짜와 종가가 저장되어 있는 array- start_index: 이번 iteration의 시작- end_index: 종료 날짜의 index- money: 총 투자 비용---이번 interation의- rate: 수익률- sum: 누적 매수 가격- no: 누적 개수- avg_price: 평균단가 이거를 main에서 여러 번 돌리기<jupyter_code>def modifying_data(file_name):
    data = pd.read_csv('./' + file_name, header=None)
    print(data)
    code = data[0][0]
    data1 = data[2:][:]
    

    head = []
    for i in range(data1.shape[1]):
        head.append(data[i][1])
    data1.columns = head
    data1['일자'] = pd.to_datetime(data1['일자'], format="%Y-%m-%d")
    data1 = data1.to_numpy()
    return np.array((data1[:, 0], data1[:, 5])), code

def calculate(num, start_index, end_index, money):
    global outfile
    global data_need

    if(start_index < end_index):
        return -1, 0
        # finish
    rate = 0.0 # 수익률
    sum = 0.0 # 누적 매수 가격
    sell_price = 0.0 # 매도 금액
    no = 0 # 누적 개수
    money_one = money / num # 한 회 투자 금액
  
    for i in range(num):
        count = int(money_one // float(data_need[1, start_index - i]))
        print(count)
        pay = float(data_need[1, start_index - i]) * count
        sum += pay
        no += count
        sell_price = float(data_need[1, start_index - i]) * no
        rate = (sell_price - sum) / sum
         # finish -> return
        #print('{:}, {:}, {:}, {:.2f}, {:.2f}, {:.2f}, {:.2f}\n'.format(str(data_need[0, start_index]), str(data_need[0, start_index - i]), 'ing', sum, sell_price, sell_price - sum, rate))
        if(start_index - i == end_index):
            outfile.write('{:}, {:}, {:}, {:.2f}, {:.2f}, {:.2f}, {:.2f}\n'.format(str(data_need[0, start_index]), str(data_need[0, start_index - i]), 'Finish', sum, sell_price, sell_price - sum, rate))
            print('{:}, {:}, {:}, {:.2f}, {:.2f}, {:.2f}, {:.2f}\n'.format(str(data_need[0, start_index]), str(data_need[0, start_index - i]), 'True', sum, sell_price, sell_price - sum, rate))
            return -1, 0
        if(rate >= 0.1) :
            outfile.write('{:}, {:}, {:}, {:.2f}, {:.2f}, {:.2f}, {:.2f}\n'.format(str(data_need[0, start_index]), str(data_need[0, start_index - i]), 'True', sum, sell_price, sell_price - sum, rate))
            print('{:}, {:}, {:}, {:.2f}, {:.2f}, {:.2f}, {:.2f}\n'.format(str(data_need[0, start_index]), str(data_need[0, start_index - i]), 'True', sum, sell_price, sell_price - sum, rate))
            return (start_index - i), (sell_price - sum)
    print('{:}, {:}, {:}, {:.2f}, {:.2f}, {:.2f}, {:.2f}\n'.format(str(data_need[0, start_index]), str(data_need[0, start_index - num + 1]), 'False', sum, sell_price, sell_price - sum, rate))
    outfile.write('{:}, {:}, {:}, {:.2f}, {:.2f}, {:.2f}, {:.2f}\n'.format(str(data_need[0, start_index]), str(data_need[0, start_index - num + 1]), 'False', sum, sell_price, sell_price - sum, rate))
    return (start_index - num), (sell_price - sum)
            
        
    # over num -> finish -> return
def find_index(date):
    global data_need
    index = np.where(data_need[0, :] == date)

    while(len(index[0]) == 0):
        date = date + datetime.timedelta(days = 1)
        index = np.where(data_need[0, :] == date)
    print('set date to ' + str(date))
    return index[0][0]
def get_user_input():
    start = input('시작 날짜(YYYY-mm-dd): ')
    end = input('종료 날짜(YYYY-mm-dd): ')
    num = int(input('한 iteration에 처리할 개수(ex 40): '))
    welfare = int(input('복리: 1, 단리: 0 - 1/0 중 택: '))
    money = int(input('총 투자금액: '))
    file_name = input('테스트할 파일 이름(확장자까지 포함): ')
    return pd.to_datetime(start), pd.to_datetime(end), num, welfare, money, file_name
start_date, end_date, num, welfare, money, file_name= get_user_input()
'''
start_date = pd.to_datetime('2012-08-18')
end_date = pd.to_datetime('2021-09-10')
num = 40
welfare = 1
money = 40000
'''

data_need, code = modifying_data(file_name)
print(data_need)

outfile = open(code + '_infinite_invest.csv', 'w')
outfile.write('매수 시작날짜, 종료 날짜, 조기종료, 누적매수가격, 매도금액, 손익금, 수익률, \n')

total_money = money
start = find_index(start_date)
print(start)
end = find_index(end_date)
print(end)


while 1:
    print('start index' + str(start))
    next_index, money_change = calculate(num, start, end, money)
    # if earn money
    if(money_change > 0):
        # if welfare, use earn money
        if(welfare == 1):
            money += money_change
    # if lose money
    else:
        money += money_change
    total_money += money_change
    start = next_index
    print("total money: " + str(total_money))
    if(next_index != -1):
        continue
    break
outfile.write('total money: {:.2f}\n'.format(total_money))
outfile.close()
print('finish simulation')<jupyter_output>시작 날짜(YYYY-mm-dd): 2012-08-10
종료 날짜(YYYY-mm-dd): 2021-09-08
한 iteration에 처리할 개수(ex 40): 40
복리: 1, 단리: 0 - 1/0 중 택: 1
총 투자금액: 40000
테스트할 파일 이름(확장자까지 포함): infinite_invest.csv
              0       1       2   ...     8           9              10
0           TQQQ     NaN     NaN  ...    NaN         NaN            NaN
1             일자     기준가      시가  ...    등락률         거래량             금액
2     2021-09-10   148.9   148.9  ...   1.26      48,820      7,346,153
3     2021-09-09  150.51  150.73  ...  -1.07  27,643,379  4,156,233,831
4     2021-09-08  152.07  151.81  ...  -1.03  31,711,510  4,750,943,130
...          ...     ...     ...  ...    ...         ...            ...
2912  2010-02-19   89.76   89.15  ...      0     242,088     21,729,819
2913  2010-02-18   88.09      88  ...    1.9     202,430     18,170,117
2914  2010-02-17   86.62   87.78  ...    1.7      99,878      8,798,253
2915  2010-02-16   83.39   85.35  ...   3.87      50,082      4,338,103
2916  2010-02-12   83.05   80.79  .[...]
{'fraction_non_alphanumeric': 0.18213984835720304, 'fraction_numerical': 0.07245155855096883, 'mean_word_length': 2.4531704479348457, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 14, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '424625', 'license': 'MIT', 'n_tokens_mistral': 2752, 'n_tokens_neox': 2655, 'n_words': 544, 'path': 'infinite_invest.ipynb', 'repo_name': 'dongwon18/Infinite_invest_simulation', 'size': '5935'}