-1

I get stock price data with the following code:

for i in range(25200):

    time.sleep(1)
    with requests.Session() as s:
               data = {'ContractCode' : 'SAFMO98' }
               r = s.post('http://cdn.ime.co.ir/Services/Fut_Live_Loc_Service.asmx/GetContractInfo', json = data ).json()

    for key, value in r.items():
        plt.clf()
        last_prices = (r[key]['LastTradedPrice'])   
        z.append(last_prices)
        plt.figure(1)
        plt.plot(z)

Sometimes my program gets disconnected or stops. Then I must re run the program and I loose all my data and program starts from the beginning. I am seeking a way to save data and reuse it after rerunning the program. How is it possible?

What should I add to my code for doing that?

EDIT: I edited my code like following, but neither of ways worked for me:

try:
    with open('3_tir.pickle', 'rb') as f:    
           last_prices = pickle.load(f)
           print("pickle loaded")
   #f = open("last_prices.txt", 'a+')
   #f.read()


except Exception:
    #f = open("last_prices.txt", 'a+')
    pass

for i in range(25200):

    time.sleep(1)
    with requests.Session() as s:
               data = {'ContractCode' : 'SAFMO98' }
               r = s.post('http://cdn.ime.co.ir/Services/Fut_Live_Loc_Service.asmx/GetContractInfo', json = data ).json()

    for key, value in r.items():
        plt.clf()
        last_prices = (r[key]['LastTradedPrice'])   
        z.append(last_prices)
        plt.figure(1)
        plt.plot(z)

    with open('3_tir.pickle', 'wb') as f:
           pickle.dump(last_prices, f)
    #   f.write(last_prices)
    #   f.close()
Hasani
  • 3,543
  • 14
  • 65
  • 125

2 Answers2

2

You can write your data in a file:

f = open("file.txt", 'w+')
f.write(last_prices)
# write your program here
f.close()

Or append it:

f = open("file.txt", 'a+')
f.write(last_prices)
# write your program here
f.close()

Then you can read from that file.

f = open("file.txt")

You can access to the whole text by .read() method OR you can get the text line by line by .readlines() method.

f.read()
# It returns the whole text in one string
f.readlines()
# It returns a list of the file's lines

More information about reading and writing to a file. If you can add your data to something like database tables, then you can use CSV Files to save your data, too. You can use CSV Library.

Edit: I have no idea what you are trying to do, but obviously you are not loading the file. I can see you loaded from '3_tir.pickle' but you never used it! You loaded the file to 'last_prices' variable, then after 20 lines you reassigned(defining that variable again) it. So i recommend you to read this article and then this, Then you can code your program better.

Miad Abdi
  • 831
  • 10
  • 17
2

You can use pickle to store objects like lists, tuples, classes etc to file and load them back into memory when your program restarts. It works like the json library.

Use pickle.dump() to save the object, pickle.load() to load it back into memory.

DEMO: SAVING TO PICKLE FILE

import pickle

a_list = [2,3,4,5]

with open('pickled_list.pickle', 'wb') as f:
    pickle.dump(a_list, f)

DEMO: LOADING FROM PICKLE FILE

import pickle

with open('pickled_list.pickle', 'rb') as f:    
    list_from_pickle = pickle.load(f)

print(list_from_pickle)

Output:

[2,3,4,5]

Visit this page, from Python Software Foundation, to read more on what can be pickled and what more you can do: https://docs.python.org/3/library/pickle.html

ayivima
  • 98
  • 3
  • Thanks, but how can I append new data when I load a pickle? – Hasani Jun 24 '19 at 04:14
  • 2
    The loaded data from the pickle becomes the original object. Maybe you should ask this question separately, so that we can give a more detailed answer that can help others. – ayivima Jun 24 '19 at 07:09
  • I edited my question, please read the edit part, thanks. – Hasani Jun 24 '19 at 09:01
  • What question do you mean? You mean adding new data to the previous pickle need a new question? – Hasani Jun 24 '19 at 09:03
  • 1
    I wanted you to ask a new question surrounding your unique experience with the current stage of your code since this has been marked as duplicate. Currently, other people cannot contribute because this is marked as duplicate. :) – ayivima Jun 24 '19 at 12:40
  • Thanks, I will do it. – Hasani Jun 24 '19 at 13:12
  • I added this new question: https://stackoverflow.com/questions/56737479/why-my-code-doesnt-save-load-my-data-in-python?noredirect=1#comment100033816_56737479 – Hasani Jun 24 '19 at 13:33
  • That's great. Checking it out. :) – ayivima Jun 24 '19 at 14:55