create account

Saving Stocks Data in Microsoft Excel using Python by geekgirl

View this thread on: hive.blogpeakd.comecency.com
· @geekgirl ·
$17.48
Saving Stocks Data in Microsoft Excel using Python
Last week I briefly wrote about automating Stocks data retrieval from Yahoo Finance and storing them in an Excel spreadsheet. The goal is to replace manual look up of stock prices and manually entering them into the spreadsheet. The purpose of the spreadsheet is to keep record of price changes throughout the week for the Stocks I am watching and planning to trade.

To accomplish this goal I split up the project into 3 steps. First step of the project fetches the Stocks Historical Data with a python code from Yahoo Finance. This step has been accomplished. I shared the code in my [Amateur Trader's Diary - Tuesday Updates & Automating with Python](https://leofinance.io/hive-167922/@geekgirl/amateur-trader-s-diary-tuesday-updates-and-automating-with-python) post. 

Second step is to create a spreadsheet or update and existing one with a template and is the subject of this post. Third step will be to combine both codes and enter Stocks price data into the spreadsheet and apply some styles.

Following is the code that helps with creating a template and saves needed data in Excel file.

![automate_2.png](https://images.hive.blog/DQmeionUVuKciQ3GBW6jcD2Q5R9mTA5wyN93XHvXuvUqnzc/automate_2.png)

Let's walk through the code line by line:

`import openpyxl`
`import os`
`from openpyxl.utils import get_column_letter`

Here were are importing dependancies we will need. Main was in **openpyxl**. This will allow us to interact with an Excel file. We can get away without using **os** if we type in an absolute path for the file we will be working with. For some reason I got an error using a relative path, just typing in the file name. Using an absolute path worked. Last dependency **get_column_letter** will help us convert numbers to column names like A, B, C, etc. so it is easy to iterate with a for loop.

`diary_path = os.getcwd() + '/Desktop/'`
`diary_file = 'trading_diary.xlsx'`

I am saving the path to the file and the file name in separate variables, so it is easier to reuse the code for different projects with simply changing the file name. **os.getcwd()** will return current working directory in as a string.

`wb = openpyxl.load_workbook(diary_path + diary_file)`

This code will open our Excel file and store the workbook in variable **wb**, so we can read from it or write data.

`week = 'Week 2'`
`stocks = ['MRNA','DS','PTON','FB','AMD','NKLA','IOVA','CASA','NVTA','IDEX']`
`header_row= ['Stocks', 'TimeFrame', 'Position', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']`

**week** variable will represent the worksheet we will be updating. **stocks** represent this weeks stock picks, and **header_row** is a title for each column. At the beginning of the week I will manually change the variables **week**, and **stocks**.  **header_row** will remain same for all weeks, unless I decide to change the days of the week to actual date. Actual dates probably would be better.

`if week not in wb.sheetnames:`
 `   wb.create_sheet(week)`

This code will check if 'Week 2' sheet exists in the workbook. If it doesn't it will create a worksheet with the name 'Week 2' or whatever the value is for **week** variable.

`sheet = wb[week]`
`row = 1`
`col = 1`

`for i in header_row:`
 `   col_letter = get_column_letter(col)`
`    cell = col_letter + str(row)`
`   sheet[cell] = i`
`    col += 1`

Now, I can assign the proper worksheet to a **sheet** variable and save data in **header_row** in the that worksheet. This is where **get_column_letter()** is being helpful converting numbers to alphabetic representation of the column names. 

`row = 2`
`col = 1`

`for j in stocks:`
`    col_letter = get_column_letter(col)`
`   cell = col_letter + str(row)`
`   sheet[cell] = j`
`    row += 1`

Here we are entering Stock names under the header row and in the first column in a similar fashion as we did with previous for loop. 

`wb.save(diary_path+diary_file)`

Lastly, after everything we need to do with the worksheet is done we need to save the changes.

Simple code, yet saves a lot of time. That is why I like python. Next time I hope to combine both codes, and complete the project with applying some more logic and styles to the Excel spreadsheet.

Posted Using [LeoFinance](https://leofinance.io/@geekgirl/saving-stocks-data-in-microsoft-excel-using-python)
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 125 others
πŸ‘Ž  
properties (23)
authorgeekgirl
permlinksaving-stocks-data-in-microsoft-excel-using-python
categoryhive-167922
json_metadata{"tags":["stocks","python","coding","stem","neoxian","ctp","pal","leofinance"],"image":["https://images.hive.blog/DQmeionUVuKciQ3GBW6jcD2Q5R9mTA5wyN93XHvXuvUqnzc/automate_2.png"],"links":["https://leofinance.io/hive-167922/@geekgirl/amateur-trader-s-diary-tuesday-updates-and-automating-with-python"],"app":"leofinance/0.1","format":"markdown","canonical_url":"https://leofinance.io/@geekgirl/saving-stocks-data-in-microsoft-excel-using-python"}
created2020-06-22 05:01:00
last_update2020-06-22 05:01:00
depth0
children5
last_payout2020-06-29 05:01:00
cashout_time1969-12-31 23:59:59
total_payout_value10.012 HBD
curator_payout_value7.468 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length4,309
author_reputation1,588,017,773,177,039
root_title"Saving Stocks Data in Microsoft Excel using Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,106,278
net_rshares47,798,604,849,135
author_curate_reward""
vote details (190)
@chitty ·
I have picked your post for my daily hive voting initiative, Keep it up and Hive On!!
properties (22)
authorchitty
permlinkre-saving-stocks-data-in-microsoft-excel-using-python-20200623t000652
categoryhive-167922
json_metadata""
created2020-06-23 00:06:54
last_update2020-06-23 00:06:54
depth1
children0
last_payout2020-06-30 00:06:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length86
author_reputation86,901,300,608,582
root_title"Saving Stocks Data in Microsoft Excel using Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,123,176
net_rshares0
@gitplait-mod2 ·
Hello @geekgirl. Thanks for illustrating out all this process. This is the kind of publication we appreciate in our community. Do endeavor to check us out.

<sub> **Your post has been curated with @gitplait community account because this is the kind of publications we like to see in our community.** </sub>

Join our [Community on Hive](https://hive.blog/trending/hive-103590) and Chat with us on [Discord](https://discord.gg/CWCj3rw).

[[Gitplait-Team]](https://gitplait.tech/)

properties (22)
authorgitplait-mod2
permlinkre-geekgirl-qcbdiy
categoryhive-167922
json_metadata{"tags":["hive-167922"],"app":"peakd/2020.05.5"}
created2020-06-22 06:18:36
last_update2020-06-22 06:18:36
depth1
children0
last_payout2020-06-29 06:18:36
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length481
author_reputation28,898,670,427
root_title"Saving Stocks Data in Microsoft Excel using Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,107,164
net_rshares0
@hivebuzz ·
Congratulations @geekgirl! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

<table><tr><td><img src="https://images.hive.blog/60x70/http://hivebuzz.me/@geekgirl/upvoted.png?202006220523"></td><td>You received more than 70000 upvotes. Your next target is to reach 75000 upvotes.</td></tr>
</table>

<sub>_You can view [your badges on your board](https://hivebuzz.me/@geekgirl) And compare to others on the [Ranking](https://hivebuzz.me/ranking)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>


To support your work, I also upvoted your post!


###### Support the HiveBuzz project. [Vote](https://hivesigner.com/sign/update_proposal_votes?proposal_ids=%5B%22109%22%5D&approve=true) for [our proposal](https://peakd.com/me/proposals/109)!
properties (22)
authorhivebuzz
permlinkhivebuzz-notify-geekgirl-20200622t082302000z
categoryhive-167922
json_metadata{"image":["http://hivebuzz.me/notify.t6.png"]}
created2020-06-22 08:23:00
last_update2020-06-22 08:23:00
depth1
children0
last_payout2020-06-29 08:23:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length862
author_reputation370,784,617,093,775
root_title"Saving Stocks Data in Microsoft Excel using Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,108,768
net_rshares0
@powerfulwonders ·
$0.13
This is the kind of really useful project / information / exemplar that I love! Thanks!

I'm making some space in my life to get back into Python after a few years away. Examples like this always cheer me up and make me feel like yes, it might be within my grasp to do this :-)
πŸ‘  
properties (23)
authorpowerfulwonders
permlinkqcbkpz
categoryhive-167922
json_metadata{"app":"hiveblog/0.1"}
created2020-06-22 08:54:00
last_update2020-06-22 08:54:00
depth1
children1
last_payout2020-06-29 08:54:00
cashout_time1969-12-31 23:59:59
total_payout_value0.067 HBD
curator_payout_value0.067 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length277
author_reputation643,151,525,981
root_title"Saving Stocks Data in Microsoft Excel using Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id98,109,120
net_rshares560,362,597,430
author_curate_reward""
vote details (1)
@geekgirl ·
Thank You. Python is fun. I like it because one doesn’t have to be a programmer to use it, to automate daily tasks.
properties (22)
authorgeekgirl
permlinkre-powerfulwonders-qccb0t
categoryhive-167922
json_metadata{"tags":["hive-167922"],"app":"peakd/2020.05.5"}
created2020-06-22 18:22:06
last_update2020-06-22 18:22:06
depth2
children0
last_payout2020-06-29 18:22:06
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length115
author_reputation1,588,017,773,177,039
root_title"Saving Stocks Data in Microsoft Excel using Python"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id98,117,947
net_rshares0