Python Forum
print(data) is suddenly invalid syntax
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
print(data) is suddenly invalid syntax
#1
Hi, my scripts are evolving but I seem to have taken a step backward. The script below works without the print(data) command but not with it. This wasn't the case before but I don't know what script complexity has caused this to start happening.

import yfinance as yf
import pandas as pd
#import sys
from datetime import date
today = date.today()
data = None
for line in open('C:\\Users\\stant\\OneDrive\\Documents\\daxandpython\\tickers.txt'):
    #ticker="MSFT"#yf.Ticker(line.strip("\n\r"))
    line=line.strip("\n\r")
    #ticker=yf.Ticker(line)
    ticker=line
    x = yf.download(ticker, start="2017-01-01", end=today, progress=False).round(2)
    #x["Stock"]=ticker
    #x["Date"]=x.index
    x.insert(0, "Date", x.index)
    x.insert(0, "Ticker", ticker)
    if data is None:
        data = x
    else:
        data = pd.concat((data, x))
    data = data.sort_index()
print(data)
Error:
File "<stdin>", line 16 print(data) ^^^^^ SyntaxError: invalid syntax
Reply
#2
I copied the code and it has no syntax errors.

Why does the error message say "stdin"? Why don't the line numbers match the file? The code you posted is not generating the error message in your post.

Some suggestions:
Stop doing this:
for line in open("C:\\Users\\stant\\OneDrive\\Documents\\daxandpython\\tickers.txt"):
To start with, Python knows about \ and / and will convert to work with the platform you are running on. Save yourself from some headaches and stop using backslashes unless you want a backslash. If you do want a backslash in a string literal, us a raw string.
filename = "C:/Users/stant/OneDrive/Documents/daxandpython/tickers.txt"
or
filename = r"C:\Users\stant\OneDrive\Documents\daxandpython\tickers.txt"
Use relative paths when you can. Most of the time a file is in the current working directory (no path needed) or it is in the same folder as the program file.
If the "tickers.txt" file is in the same folder as the program, you can do this.
import yfinance as yf
import pandas as pd
from datetime import date
from pathlib import Path

folder = Path(__file__).parent  # Gets the folder for the program file.
today = date.today()
data = None
for line in open(folder / "tickers.txt"):
    ticker = line.strip("\n\r")
    x = yf.download(ticker, start="2017-01-01", end=today, progress=False).round(2)
    x.insert(0, "Ticker", ticker)
    data = x if data is None else pd.concat((data, x))

data = data.reset_index().sort_values("Date")  # You can daisy-chain most DataFrame methods.
print(data)
reset_index takes the existing index and turns it into a column. The new index, if none is supplied, is 0, 1, 2...
Reply
#3
This is very interesting, thank you.

STDIN appears to me to be the generic name of the command input prompt "device" (similar to DOS CMD) I am using temporarily when i execute python without an IDE.

I was getting an error in that prompt because i didn't have a blank line between the end of the loop and the print command. I'm guessing that a blank line is some kind of syntax delimiter in python.

The python command prompt environment appears to count all the loop's statements (for statement and all indented commands) as one line. And doesn't seem to count comments as a line. Between that and the missing blank line, I believe the statement lines I posted really do jive with the output in the first post. I'm thinking the missing blank line caused the print statement to be counted as part of the loop statement.

What's most interesting to me is that when I run from the prompt even without the index reset, I get a date column in the output. But I don't get a date column when I run that same way in a power bi connector. When I run in a pbi connector with a blank line followed by the reset at the end of the script, I get the date column.

I'm not too worried because I can insert the date column into "x" using x.index if i dont want the reset. I'm not even sure what the reset does but I'll look it up. I understand the sort. Maybe PBI connectors ignore the index column by default, who knows.
Reply
#4
Please describe how you run a python program. When I run python scripts for the command line, Python reports any errors using the name of the .py file I am running. Python only uses "stdin" as the source "file" when I am typing in the python interpreter. You should not be entering programs in the interpreter.
Reply
#5
thx for your patience Dean. At the moment and until I choose an IDE for future endeavors, this is what I am doing (i dont see how to attach pictures without a url in a reply) ...

1. in my search box i type py and i see the py run command which has a blue and yellow logo
2. clicking it, i get a python 3.11.4 command window prompt >>>>
3. i paste my script after that prompt, get a warning that there are multiple lines
4. i bypass the warning, often hit enter one more time and i see my results in the command window

i usually go directly to power bi after that and without the print command try the script out in a python connector to view how power bi will behave on the same script.
Reply
#6
(Jun-14-2023, 01:21 PM)db042190 Wrote: 2. clicking it, i get a python 3.11.4 command window prompt >>>>
3. i paste my script after that prompt, get a warning that there are multiple lines
You can not paste in multiple lines in default python interactive >>> interpreter.
It's more for test of code line by line with Enter after each line of block.
Learn to use the command line eg cmd/powershell,i do not like them at all so i use cmder.
To run your code i first post i named yf_sc.py from command line and also look at files.
G:\div_code\answer
# Run the script
λ python yf_sc.py
           Date Ticker    Open    High     Low   Close  Adj Close    Volume
0    2017-01-03    AAP  170.78  171.36  169.31  170.60     158.06    691300
1622 2017-01-03    WMT   69.24   69.24   68.05   68.66      60.60  10473200
1    2017-01-04    AAP  170.37  173.17  170.37  172.00     159.36    641700
1623 2017-01-04    WMT   68.66   69.63   68.60   69.06      60.95   7918000
2    2017-01-05    AAP  170.87  173.06  170.23  171.88     159.25    861000
...         ...    ...     ...     ...     ...     ...        ...       ...
1619 2023-06-09    AAP   64.65   64.88   63.56   63.58      63.58   3300100
3242 2023-06-12    WMT  153.43  154.30  153.17  154.10     154.10   4904500
1620 2023-06-12    AAP   64.71   67.92   64.20   66.89      66.89   4244100
1621 2023-06-13    AAP   66.97   70.47   66.65   68.66      68.66   5138300
3243 2023-06-13    WMT  154.52  155.51  154.07  155.30     155.30   5244100

[3244 rows x 8 columns]

# Look at code<yf_sc.py>,can use <type> in cmd
G:\div_code\answer
λ rich yf_sc.py
import yfinance as yf
import pandas as pd
from datetime import date
from pathlib import Path

folder = Path(__file__).parent  # Gets the folder for the program file.
today = date.today()
data = None
for line in open(folder / "tickers.txt"):
    ticker = line.strip("\n\r")
    x = yf.download(ticker, start="2017-01-01", end=today, progress=False).round(2)
    x.insert(0, "Ticker", ticker)
    data = x if data is None else pd.concat((data, x))

data = data.reset_index().sort_values("Date")  # You can daisy-chain most DataFrame methods.
print(data)

G:\div_code\answer
# Look at <tickers.txt>
λ type tickers.txt
AAP
WMT

G:\div_code\answer

(Jun-14-2023, 01:21 PM)db042190 Wrote: i usually go directly to power bi after that and without the print command try the script out in a python connector to view how power bi will behave on the same script.
There are many Editors for Python like the big ones VS Code | PyCharm(Free Community),
or simpler ones like PyScripter or Thonny.
Find one that you like and use that,but if you don't know command line very well,i would say that is important to learn.
Many Windows user struggle here,if just used to use a Gui interfaces.
Reply
#7
That explains a lot. Your programming process is all wrong. I'm surprised you can get anything to run. Search for tutorial videos on how to run python programs on windows. Can also find videos for all the major IDE (Interactive Development Environment). Watch them to see if any of them are a good fit for you.
db042190 likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Information subprocess.Popen() suddenly giving me grief? davecotter 3 627 Dec-13-2023, 10:49 PM
Last Post: davecotter
  Python debug suddenly got bad ben1122 3 1,109 Sep-03-2022, 06:20 AM
Last Post: ben1122
  SyntaxError: invalid syntax ?? korenron 15 5,788 Jan-25-2022, 11:46 AM
Last Post: korenron
  Invalid syntax with an f-string Mark17 7 7,864 Jan-14-2022, 04:44 PM
Last Post: Mark17
  invalid syntax in my class CompleteNewb 2 1,921 Dec-13-2021, 09:39 AM
Last Post: Larz60+
Exclamation Invalid syntax error(Predict Ethereum Price) lulu43366 2 3,183 Sep-24-2021, 01:24 PM
Last Post: lulu43366
  Unexplained Invalid syntax Error cybertooth 5 3,283 Aug-02-2021, 10:05 AM
Last Post: cybertooth
  string.format() suddenly causing errors with google drive API zwitrader 0 1,774 Jun-28-2021, 11:38 PM
Last Post: zwitrader
  [split] SyntaxError: invalid syntax Code_X 3 2,773 May-04-2021, 05:15 PM
Last Post: Yoriz
  Invalid syntax error - need help fixing calgk01 3 3,304 Feb-23-2021, 08:41 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020