0% found this document useful (0 votes)
131 views28 pages

Gemini 2 Flash Multimodal Live API Text and Audio

Uploaded by

rebii ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
131 views28 pages

Gemini 2 Flash Multimodal Live API Text and Audio

Uploaded by

rebii ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Gemini_2_Flash_Multimodal_Live_API_text_to_text_and_text_to_audi

January 2, 2025

[1]: !pip install -U -q google-genai

[6]: from google.colab import userdata


import os

os.environ['GOOGLE_API_KEY'] = userdata.get('GEMINI_API_KEY')

[7]: from google import genai


client = genai.Client(http_options= {'api_version': 'v1alpha'})
MODEL = "gemini-2.0-flash-exp"

1 Import lib
[4]: import asyncio
import base64
import contextlib
import datetime
import os
import json
import wave
import itertools

from IPython.display import display, Audio

from google import genai


from google.genai import types

async def async_enumerate(it):


n = 0
async for item in it:
yield n, item
n +=1

1
2 Text to Text
“response_modalities”: [“TEXT”]
From docs api: only one cal ==> no loop.
Have a look on the following cell code to see how I implemented multiple calls
[ ]: config={"generation_config": {"response_modalities": ["TEXT"]}}

async with client.aio.live.connect(model=MODEL, config=config) as session:


user_input = input("Enter your input: ")
print(f"You entered: {user_input}")
await session.send(user_input, end_of_turn=True)

# For text responses, When the model's turn is complete it breaks out of the␣
loop.

turn = session.receive()
async for chunk in turn:
if chunk.text is not None:
print(f'- {chunk.text}')

Enter your input: Hi


You entered: Hi
> Hi

- Hi
- there! How can I help you today?

2.1 Asking Gemini 2.0 for a momentum trading strategy


I asked Gemini 2.0 Flash to propose a momentum trading strategy and its implementation using
Python.
Furthermore, I asked it to save this code in a python file. It noticed that I was using Google Colab,
suggesting a solution tailored for a Colab notebook.
[ ]: # Configuration for the model
config = {
"generation_config": {"response_modalities": ["TEXT"]}
}

# Function to interact with the user


async def chat_with_model():
# Establish a session with the model
async with client.aio.live.connect(model=MODEL, config=config) as session:
print("Chat session started. Type 'exit' to end the conversation.")
while True:
# Prompt the user for input

2
message = input("You: ")

# Check if the user wants to exit


if message.lower() == "exit":
print("Ending the chat session. Goodbye!")
break

# Send the user's message to the model


await session.send(message, end_of_turn=True)

# Receive and print the model's response


turn = session.receive()
async for chunk in turn:
if chunk.text is not None:
print(f"Model: {chunk.text}")

# To run the asynchronous function in Google Colab


import nest_asyncio
import asyncio

nest_asyncio.apply()
await chat_with_model()

Chat session started. Type 'exit' to end the conversation.


You: propose a momentum trading strategy and its implementation using Python
Model: Okay, let'
Model: s craft a momentum trading strategy and its Python implementation. We'll
focus on a relatively
Model: straightforward strategy that's easier to grasp but still demonstrates
core momentum concepts.

**Moment
Model: um Trading Strategy: Relative Strength Index (RSI) with Moving Average
Confirmation**

**Concept:**
This strategy looks for stocks exhibiting strong recent upward price momentum.
We
Model: 'll use the following indicators:

1. **Relative Strength Index (RSI):** The RSI measures the speed and change of
price movements. It's typically
Model: used to identify overbought (RSI above 70) or oversold (RSI below 30)
conditions. For momentum, we'll look for RSI crossing above 50 as an initial
sign of building strength.

2.

3
Model: **Simple Moving Average (SMA):** We'll use a short-term SMA (e.g.,
20-day) and a longer-term SMA (e.g., 50-day). We'll look
Model: for the short-term SMA crossing above the long-term SMA ("golden
cross"), which indicates a potential upward trend confirmation.

**Trading Rules:**

* **Buy Signal:**
* RSI crosses above 50
* Short-term SMA crosses above long-term SMA.
*
Model: A valid buy signal occurs only when both conditions are met.
* **Sell Signal:**
* RSI crosses below 50.
* A simple trailing stop is implemented using the minimum price over the
last 10 bars. This protects against large losses.
* **Position
Model: Sizing:** We'll use a fixed amount of capital per trade (e.g., 10% of
account equity), or a fixed position size (100 shares).
* **No shorting:** This example will be long-only.
* **Historical lookback:** This strategy
Model: is applied to daily stock data.
* **No intraday rebalancing:** Once the positions have been decided, they will
be maintained until a signal to exit.

**Python Implementation**

We'll use the `yfinance` library for stock data and `pandas` for data
manipulation. You might
Model: need to install them:

```bash
pip install yfinance pandas numpy ta
```

Here's the Python code:

```python
import yfinance as yf
import pandas as pd
import numpy as np
import ta # for technical indicators
import matplotlib.pyplot as plt # for visualization

def
Model: fetch_data(ticker, start_date, end_date):
"""Fetches stock data using yfinance."""
try:

4
data = yf.download(ticker, start=start_date, end=end_date)
if data.empty:
print(f"No data
Model: found for ticker {ticker}")
return None
return data
except Exception as e:
print(f"Error fetching data for {ticker}: {e}")
return None

def calculate_indicators(df, short_ma_period=20, long_ma_period=


Model: 50, rsi_period=14):
"""Calculates SMA and RSI indicators."""

df["SMA_short"] = df["Close"].rolling(window=short_ma_period).mean()
df["SMA_long"] = df["Close"].rolling(window=long_ma_
Model: period).mean()
df["RSI"] = ta.momentum.rsi(df["Close"], window=rsi_period)
df["min_price_10"] = df['Low'].rolling(window=10).min()
return df

def generate_signals(df):

Model: """Generates buy and sell signals."""


df["signal"] = 0.0
df["position"] = 0.0

# Buy Signal
buy_condition = (
(df["RSI"].shift(1) < 50) & (df["R
Model: SI"] >= 50) &
(df["SMA_short"].shift(1) <= df["SMA_long"].shift(1)) &
(df["SMA_short"] > df["SMA_long"])
)
df.loc[buy_condition, "signal
Model: "] = 1.0

# Trailing stop sell signal


sell_condition = (
(df['RSI'].shift(1) > 50) & (df["RSI"] <= 50)
)
df.loc[sell_condition, "
Model: signal"] = -1.0

# Build our positions. If we have a buy signal, it will return 1.


# Otherwise it will maintain the position if we are already holding.

5
# If the signal is -1 then sell.
df.loc[0, 'position'] =
Model: 0
for i in range(1, len(df)):
if df['signal'][i] == 1:
df.loc[i, 'position'] = 1
elif df['signal'][i] == -1:
df.loc[i, 'position
Model: '] = 0
else:
df.loc[i, 'position'] = df['position'][i-1]

return df

def backtest(df, initial_capital=10000, risk_pct = 0.1):


"""Performs backtesting.
Model:
df: DataFrame with 'signal' and 'Close' columns
initial_capital: the inital amount of equity to start trading with.
risk_pct: the percentage of capital at risk per trade.
"""
portfolio = initial_capital
cash = initial_capital

Model: positions = 0
trade_log = []

for index, row in df.iterrows():


# Open position
if row['signal'] == 1:
if positions == 0:
position_size = (cash * risk_pct) / row['Close
Model: ']
positions = position_size
cash -= positions*row['Close']
trade_log.append({'date':index, 'action': 'buy', 'price':
row['Close'], 'qty': positions})
# print(f"Buy signal at {row['Close']}.
Model: Holding shares: {positions}")
# Close position
elif row['signal'] == -1 and positions > 0:
cash += positions * row['Close']
positions = 0
trade_log.append({'date':index, 'action': 'sell', 'price': row['
Model: Close']})
# print(f"Sell signal at {row['Close']}")

portfolio = cash + positions * row['Close']

6
#Add the portfolio amount for each day.
df.loc[index, 'portfolio'] = portfolio

return df, trade_log

def
Model: plot_strategy(df, ticker):
"""Plots the trading strategy and portfolio value."""
plt.figure(figsize=(14, 8))

# Plotting the stock price


plt.subplot(3, 1, 1)
plt.plot(df.index, df["
Model: Close"], label="Price", color='blue')
plt.plot(df.index, df["SMA_short"], label="SMA Short", color='orange',
linestyle='--')
plt.plot(df.index, df["SMA_long"], label="SMA Long", color='red',
linestyle='
Model: --')

# Adding buy and sell markers to the price chart


buys = df[df['signal'] == 1]
sells = df[df['signal'] == -1]
plt.scatter(buys.index, buys['Close'], marker='^', color='green
Model: ', label='Buy Signal', s=100)
plt.scatter(sells.index, sells['Close'], marker='v', color='red',
label='Sell Signal', s=100)
plt.title(f"{ticker} Price, SMA and Trading Signals")
plt
Model: .legend()

# Plotting the RSI


plt.subplot(3, 1, 2)
plt.plot(df.index, df["RSI"], label="RSI", color='purple')
plt.axhline(50, color='grey', linestyle='
Model: --', label='RSI 50')
plt.title("RSI")
plt.legend()

# Plotting the portfolio value


plt.subplot(3, 1, 3)
plt.plot(df.index, df["portfolio"], label='Portfolio Value
Model: ', color='black')
plt.title("Portfolio Value")
plt.legend()

7
plt.tight_layout()
plt.show()

def main():
"""Main execution."""
ticker = "AAPL"
start_date = "2020-01-
Model: 01"
end_date = "2024-01-01"

#Fetch data
df = fetch_data(ticker, start_date, end_date)
if df is None:
return

#Calculate indicators
df = calculate_indicators(
Model: df)

#Generate buy and sell signals


df = generate_signals(df)

# Run backtest
df, trade_log = backtest(df)
print(f"Trade log:\n{trade_log}")

# Plot strategy
plot
Model: _strategy(df, ticker)

# Calculate performance metrics (e.g., total return, max drawdown, etc.) can
be added here.
# This requires extending the backtest method

if __name__ == "__main__":
main()
```

**How to Use:**

Model: 1. **Save:** Save the code as a Python file (e.g.,


`momentum_trader.py`).
2. **Run:** Execute the script from your terminal: `python momentum_trader.py`
3. **Explore:** It will fetch data for AAPL,
Model: calculate indicators, generate signals, and run a backtest. You will see

8
a plot of the price and signals, the RSI, and your portfolio value.

**Explanation:**

* **`fetch_data(ticker, start_date, end_date)`:** Fetches daily price data for


a given stock
Model: using yfinance.
* **`calculate_indicators(df, short_ma_period, long_ma_period, rsi_period)`:**
Calculates the short-term and long-term Simple Moving Averages and the RSI.
* **`generate_signals(df)`:** Generates
Model: buy (1) and sell (-1) signals based on the strategy's rules.
* **`backtest(df)`:** Runs the trading strategy against historical data,
simulating portfolio returns
* **`plot_strategy(df, ticker)`:** Generates visualisations of the price, sma,
r
Model: si and portfolio value.
* **`main()`:** Sets up the ticker, start/end dates, calls functions and runs
the entire process.

**Important Notes:**

* **Risk Management:** This is a very basic strategy. You must implement


proper risk management (position sizing, stop-losses)
Model: when trading with real money.
* **Parameter Optimization:** The SMA periods, RSI period, and risk percentage
are just examples. You'll need to experiment and optimize these based on your
backtesting results and risk tolerance.
* **Commission/Slippage:** The backtest does not account for transaction
Model: costs (commissions) or slippage (the difference between the expected
execution price and the actual price).
* **Testing and Tuning:** This strategy may not work well in all market
conditions. You need to thoroughly test and tune any strategy on historical
data.
* **Limitations:** Momentum strategies can have periods
Model: of poor performance, especially in choppy markets.
* **Data:** Ensure your historical data is clean and accurate.
* **Real-Time Trading:** If you want to trade live, you need to connect this
code to a brokerage account and handle real-time data streams.
* **Disclaimer:** This
Model: code is for educational purposes only and does not constitute financial
advice. Use it at your own risk.

**Further Enhancements:**

* **Add performance metrics:** Sharpe ratio, maximum drawdown, etc.


* **Dynamic Position Sizing:** Scale positions based on volatility.
* **Stop-Loss:** Incorpor
Model: ate a stop-loss in the backtest for increased risk control.

9
* **Trailing Stop:** Implement a trailing stop mechanism.
* **Multiple Assets:** Extend this to trading multiple assets.
* **Backtesting Improvements:** Add more sophisticated methods for
backtesting (e.g., walk-forward
Model: analysis).
* **Combine Indicators:** Experiment with combining other technical indicators
with this strategy.

This provides a good starting point for you to explore momentum trading.
Remember, real-world trading requires a lot of research, testing, and a strong
understanding of market dynamics. Good luck!

You: plot this stratgey using Nvidia stock prices


Model: Okay, let'
Model: s adapt the code to use Nvidia stock prices (ticker: NVDA) and
Model: then generate the plot. I'll keep most of the code structure the same
but change
Model: the ticker and update the labels for clarity.

Here's the modified `main()` function within the code to plot Nvidia data:
```python
import
Model: yfinance as yf
import pandas as pd
import numpy as np
import ta # for technical indicators
import matplotlib.pyplot as plt # for
Model: visualization

def fetch_data(ticker, start_date, end_date):


"""Fetches stock data using yfinance."""
try:
data = yf.download(ticker, start=start_date, end
Model: =end_date)
if data.empty:
print(f"No data found for ticker {ticker}")
return None
return data
except Exception as e:
print(f"Error fetching data for
Model: {ticker}: {e}")
return None

def calculate_indicators(df, short_ma_period=20, long_ma_period=50,


rsi_period=14):
"""Calculates SMA and RSI indicators."""

10
df["SMA_short"] = df["
Model: Close"].rolling(window=short_ma_period).mean()
df["SMA_long"] = df["Close"].rolling(window=long_ma_period).mean()
df["RSI"] = ta.momentum.rsi(df["Close"], window=rsi_period)

Model: df["min_price_10"] = df['Low'].rolling(window=10).min()


return df

def generate_signals(df):
"""Generates buy and sell signals."""
df["signal"] = 0.0
df["position"] =
Model: 0.0

# Buy Signal
buy_condition = (
(df["RSI"].shift(1) < 50) & (df["RSI"] >= 50) &
(df["SMA_short"].shift(1) <= df["SMA_long"].shift(
Model: 1)) &
(df["SMA_short"] > df["SMA_long"])
)
df.loc[buy_condition, "signal"] = 1.0

# Trailing stop sell signal


sell_condition = (
(df['RSI'].shift(
Model: 1) > 50) & (df["RSI"] <= 50)
)
df.loc[sell_condition, "signal"] = -1.0

# Build our positions. If we have a buy signal, it will return 1.


# Otherwise it will maintain
Model: the position if we are already holding.
# If the signal is -1 then sell.
df.loc[0, 'position'] = 0
for i in range(1, len(df)):
if df['signal'][i] == 1:
df.loc[
Model: i, 'position'] = 1
elif df['signal'][i] == -1:
df.loc[i, 'position'] = 0
else:
df.loc[i, 'position'] = df['position'][i-1]

return df

11
Model: def backtest(df, initial_capital=10000, risk_pct = 0.1):
"""Performs backtesting.
df: DataFrame with 'signal' and 'Close' columns
initial_capital: the inital amount of equity to start trading with.
risk_
Model: pct: the percentage of capital at risk per trade.
"""
portfolio = initial_capital
cash = initial_capital
positions = 0
trade_log = []

for index, row in df.iterrows():


# Open position
if row['signal
Model: '] == 1:
if positions == 0:
position_size = (cash * risk_pct) / row['Close']
positions = position_size
cash -= positions*row['Close']
trade_log.append({'date':index, 'action': '
Model: buy', 'price': row['Close'], 'qty': positions})
# print(f"Buy signal at {row['Close']}. Holding shares:
{positions}")
# Close position
elif row['signal'] == -1 and positions > 0:
cash += positions * row
Model: ['Close']
positions = 0
trade_log.append({'date':index, 'action': 'sell', 'price':
row['Close']})
# print(f"Sell signal at {row['Close']}")

portfolio = cash + positions * row['Close']

#Add the
Model: portfolio amount for each day.
df.loc[index, 'portfolio'] = portfolio

return df, trade_log

def plot_strategy(df, ticker):


"""Plots the trading strategy and portfolio value."""
plt.figure(figsize=(14, 8))

# Plotting

12
Model: the stock price
plt.subplot(3, 1, 1)
plt.plot(df.index, df["Close"], label="Price", color='blue')
plt.plot(df.index, df["SMA_short"], label="SMA Short", color='orange',
Model: linestyle='--')
plt.plot(df.index, df["SMA_long"], label="SMA Long", color='red',
linestyle='--')

# Adding buy and sell markers to the price chart


buys = df[df['signal'] == 1]
sells
Model: = df[df['signal'] == -1]
plt.scatter(buys.index, buys['Close'], marker='^', color='green', label='Buy
Signal', s=100)
plt.scatter(sells.index, sells['Close'], marker='v', color='red
Model: ', label='Sell Signal', s=100)
plt.title(f"{ticker} Price, SMA and Trading Signals")
plt.legend()

# Plotting the RSI


plt.subplot(3, 1, 2)
plt.plot(df.
Model: index, df["RSI"], label="RSI", color='purple')
plt.axhline(50, color='grey', linestyle='--', label='RSI 50')
plt.title("RSI")
plt.legend()

# Plotting the portfolio value


Model:
plt.subplot(3, 1, 3)
plt.plot(df.index, df["portfolio"], label='Portfolio Value', color='black')
plt.title("Portfolio Value")
plt.legend()

plt.tight_layout()
plt.show()
Model:

def main():
"""Main execution."""
ticker = "NVDA" # Changed to Nvidia
start_date = "2020-01-01"
end_date = "2024-01-01"

#Fetch data
df
Model: = fetch_data(ticker, start_date, end_date)

13
if df is None:
return

#Calculate indicators
df = calculate_indicators(df)

#Generate buy and sell signals


df = generate_signals(df)

# Run
Model: backtest
df, trade_log = backtest(df)
print(f"Trade log:\n{trade_log}")

# Plot strategy
plot_strategy(df, ticker)

# Calculate performance metrics (e.g., total return, max drawdown, etc.)


Model: can be added here.
# This requires extending the backtest method

if __name__ == "__main__":
main()
```

**Key Changes:**

1. **`ticker = "NVDA"`:** We've updated the `ticker` variable to "NVDA" within


the `main
Model: ()` function.

**To Run This Code:**

1. **Save:** Make sure to save the code as `momentum_trader.py`.


2. **Run:** Execute it from your terminal: `python momentum_trader.py`

The script will now download Nvidia's stock data,


Model: perform the strategy analysis, and plot the results, just as before, but
using NVDA's data. You'll see the price chart with buy/sell signals, the RSI,
and your portfolio value.

Let me know if you have any other questions.

You: save this implementation in a python file called "momentum_nvidia.py"


Model: Okay, I
Model: will save the implementation in a python file called
"momentum_nvidia.py".
Model:

14
Here's the complete code that you can copy and paste directly into a
Model: file named `momentum_nvidia.py`:

```python
import yfinance as yf
import pandas as pd
import numpy as np
import ta #
Model: for technical indicators
import matplotlib.pyplot as plt # for visualization

def fetch_data(ticker, start_date, end_date):


"""
Model: Fetches stock data using yfinance."""
try:
data = yf.download(ticker, start=start_date, end=end_date)
if data.empty:
print(f"No data
Model: found for ticker {ticker}")
return None
return data
except Exception as e:
print(f"Error fetching data for {ticker}: {e}")
return None

def calculate_indicators(df, short


Model: _ma_period=20, long_ma_period=50, rsi_period=14):
"""Calculates SMA and RSI indicators."""

df["SMA_short"] = df["Close"].rolling(window=short_ma_period).mean()
df["
Model: SMA_long"] = df["Close"].rolling(window=long_ma_period).mean()
df["RSI"] = ta.momentum.rsi(df["Close"], window=rsi_period)
df["min_price_10"] = df['Low'].rolling(window
Model: =10).min()
return df

def generate_signals(df):
"""Generates buy and sell signals."""
df["signal"] = 0.0
df["position"] = 0.0

# Buy Signal
buy_condition = (

15
Model: (df["RSI"].shift(1) < 50) & (df["RSI"] >= 50) &
(df["SMA_short"].shift(1) <= df["SMA_long"].shift(1)) &
(df["SMA_short"] > df["
Model: SMA_long"])
)
df.loc[buy_condition, "signal"] = 1.0

# Trailing stop sell signal


sell_condition = (
(df['RSI'].shift(1) > 50) & (df["RSI"] <=
Model: 50)
)
df.loc[sell_condition, "signal"] = -1.0

# Build our positions. If we have a buy signal, it will return 1.


# Otherwise it will maintain the position if we are already holding.
# If the signal is
Model: -1 then sell.
df.loc[0, 'position'] = 0
for i in range(1, len(df)):
if df['signal'][i] == 1:
df.loc[i, 'position'] = 1
elif df['signal'][
Model: i] == -1:
df.loc[i, 'position'] = 0
else:
df.loc[i, 'position'] = df['position'][i-1]

return df

def backtest(df, initial_capital=10000


Model: , risk_pct = 0.1):
"""Performs backtesting.
df: DataFrame with 'signal' and 'Close' columns
initial_capital: the inital amount of equity to start trading with.
risk_pct: the percentage of capital at risk per trade.

Model: """
portfolio = initial_capital
cash = initial_capital
positions = 0
trade_log = []

for index, row in df.iterrows():


# Open position
if row['signal'] == 1:
if positions == 0
Model: :

16
position_size = (cash * risk_pct) / row['Close']
positions = position_size
cash -= positions*row['Close']
trade_log.append({'date':index, 'action': 'buy', 'price':
row['Close'], 'qty':
Model: positions})
# print(f"Buy signal at {row['Close']}. Holding shares:
{positions}")
# Close position
elif row['signal'] == -1 and positions > 0:
cash += positions * row['Close']
positions = 0

Model: trade_log.append({'date':index, 'action': 'sell', 'price': row['Close']})


# print(f"Sell signal at {row['Close']}")

portfolio = cash + positions * row['Close']

#Add the portfolio amount for each day.

Model: df.loc[index, 'portfolio'] = portfolio

return df, trade_log

def plot_strategy(df, ticker):


"""Plots the trading strategy and portfolio value."""
plt.figure(figsize=(14, 8))

# Plotting the stock price

Model: plt.subplot(3, 1, 1)
plt.plot(df.index, df["Close"], label="Price", color='blue')
plt.plot(df.index, df["SMA_short"], label="SMA Short", color='orange',
linestyle='--')

Model: plt.plot(df.index, df["SMA_long"], label="SMA Long", color='red',


linestyle='--')

# Adding buy and sell markers to the price chart


buys = df[df['signal'] == 1]
sells = df[df['signal'] ==
Model: -1]
plt.scatter(buys.index, buys['Close'], marker='^', color='green', label='Buy
Signal', s=100)
plt.scatter(sells.index, sells['Close'], marker='v', color='red',
label='Sell Signal', s=

17
Model: 100)
plt.title(f"{ticker} Price, SMA and Trading Signals")
plt.legend()

# Plotting the RSI


plt.subplot(3, 1, 2)
plt.plot(df.index, df["RSI"], label="R
Model: SI", color='purple')
plt.axhline(50, color='grey', linestyle='--', label='RSI 50')
plt.title("RSI")
plt.legend()

# Plotting the portfolio value


plt.subplot(3, 1,
Model: 3)
plt.plot(df.index, df["portfolio"], label='Portfolio Value', color='black')
plt.title("Portfolio Value")
plt.legend()

plt.tight_layout()
plt.show()

def main():
"""Main execution."""

Model: ticker = "NVDA" # Changed to Nvidia


start_date = "2020-01-01"
end_date = "2024-01-01"

#Fetch data
df = fetch_data(ticker, start
Model: _date, end_date)
if df is None:
return

#Calculate indicators
df = calculate_indicators(df)

#Generate buy and sell signals


df = generate_signals(df)

# Run backtest
df, trade_log
Model: = backtest(df)
print(f"Trade log:\n{trade_log}")

# Plot strategy

18
plot_strategy(df, ticker)

# Calculate performance metrics (e.g., total return, max drawdown, etc.) can
be added here.
#
Model: This requires extending the backtest method

if __name__ == "__main__":
main()
```

**How to Use:**

1. **Save:** Save the code as a file named `momentum_nvidia.py`.


2. **Run:** Open your terminal or command prompt, navigate to
Model: the directory where you saved the file, and run the script: `python
momentum_nvidia.py`

This will execute the code, and the plots using Nvidia stock data will be
displayed.

You: can you save the file locally in google colab?


Model: Yes
Model: , you can absolutely save the file locally within your Google Colab
environment. Here's
Model: how you can do it directly within your Colab notebook:

**Method 1
Model: : Using `%%writefile` Magic Command (Easiest)**

The `%%writefile` magic command in Colab is the simplest way to create


Model: and write to a file in your Colab environment:

1. **Create a New Code Cell:** In your Colab notebook, add a new code
Model: cell.
2. **Paste the Code:** Paste the entire Python code into this new code cell.
3. **Add `%%writefile momentum_nvidia.py`:** In the first line of this code
cell (
Model: above the `import` statements), add the line:

```python
%%writefile momentum_nvidia.py
```

The full code cell should look something like this:

```python
%%writefile momentum_

19
Model: nvidia.py
import yfinance as yf
import pandas as pd
import numpy as np
import ta
import matplotlib.pyplot as plt

# (Rest of your code here)


def fetch_data(ticker, start_date, end_date):
#
Model: … all your code from the previous response …

if __name__ == "__main__":
main()
```

4. **Run the Cell:** Execute this code cell by clicking the play button (or
pressing Shift + Enter). This will create a file named `momentum_nvidia.py`
Model: in the current working directory of your Colab environment.

**Method 2: Using Python File I/O**

You can also create the file programmatically using Python's file handling:

1. **Create a New Code Cell:** Add a new code cell.


2. **Paste the
Model: Code:** Paste the entire Python code into this new code cell, *without*
the `%%writefile` line.
3. **Add the File Saving Code:** Add the following lines at the end of your
code (or anywhere before the `if __name__ == "__main__":` block) to create
Model: and save the file:

```python
if __name__ == '__main__':

with open("momentum_nvidia.py", "w") as f:


#This is the file that gets saved. It will contain the whole script
above
f.write("""import yfinance as y
Model: f
import pandas as pd
import numpy as np
import ta # for technical indicators
import matplotlib.pyplot as plt # for visualization

def fetch_data(ticker, start_date, end_date):


\"\"\"Fetches stock data using yfinance.\"\"\"
try:

20
Model: data = yf.download(ticker, start=start_date, end=end_date)
if data.empty:
print(f"No data found for ticker {ticker}")
return None
return data
except Exception as e:
print(f"
Model: Error fetching data for {ticker}: {e}")
return None

def calculate_indicators(df, short_ma_period=20, long_ma_period=50,


rsi_period=14):
\"\"\"Calculates SMA and RSI indicators.\"\"\"

df["SMA
Model: _short"] = df["Close"].rolling(window=short_ma_period).mean()
df["SMA_long"] = df["Close"].rolling(window=long_ma_period).mean()
df["RSI"] = ta.momentum.rsi(df["Close"], window
Model: =rsi_period)
df["min_price_10"] = df['Low'].rolling(window=10).min()
return df

def generate_signals(df):
\"\"\"Generates buy and sell signals.\"\"\"
df["signal"] = 0
Model: .0
df["position"] = 0.0

# Buy Signal
buy_condition = (
(df["RSI"].shift(1) < 50) & (df["RSI"] >= 50) &
(df["SMA_short"].shift
Model: (1) <= df["SMA_long"].shift(1)) &
(df["SMA_short"] > df["SMA_long"])
)
df.loc[buy_condition, "signal"] = 1.0

# Trailing stop sell signal


sell
Model: _condition = (
(df['RSI'].shift(1) > 50) & (df["RSI"] <= 50)
)
df.loc[sell_condition, "signal"] = -1.0

# Build our positions. If we have a buy

21
Model: signal, it will return 1.
# Otherwise it will maintain the position if we are already holding.
# If the signal is -1 then sell.
df.loc[0, 'position'] = 0
for i in range(1, len(df)):
if df
Model: ['signal'][i] == 1:
df.loc[i, 'position'] = 1
elif df['signal'][i] == -1:
df.loc[i, 'position'] = 0
else:
df.loc[i, 'position'] = df
Model: ['position'][i-1]

return df

def backtest(df, initial_capital=10000, risk_pct = 0.1):


\"\"\"Performs backtesting.
df: DataFrame with 'signal' and 'Close' columns
initial_
Model: capital: the inital amount of equity to start trading with.
risk_pct: the percentage of capital at risk per trade.
\"\"\"
portfolio = initial_capital
cash = initial_capital
positions = 0
trade_log = []

for index,
Model: row in df.iterrows():
# Open position
if row['signal'] == 1:
if positions == 0:
position_size = (cash * risk_pct) / row['Close']
positions = position_size
cash -= positions*row['Close
Model: ']
trade_log.append({'date':index, 'action': 'buy', 'price':
row['Close'], 'qty': positions})
# print(f"Buy signal at {row['Close']}. Holding shares:
{positions}")
# Close position
elif row['signal
Model: '] == -1 and positions > 0:
cash += positions * row['Close']
positions = 0
trade_log.append({'date':index, 'action': 'sell', 'price':
row['Close']})

22
# print(f"Sell signal at {row
Model: ['Close']}")

portfolio = cash + positions * row['Close']

#Add the portfolio amount for each day.


df.loc[index, 'portfolio'] = portfolio

return df, trade_log

def plot_strategy(df, ticker):


\"\"\"Plots the
Model: trading strategy and portfolio value.\"\"\"
plt.figure(figsize=(14, 8))

# Plotting the stock price


plt.subplot(3, 1, 1)
plt.plot(df.index, df["Close"], label="Price", color='blue')
Model:
plt.plot(df.index, df["SMA_short"], label="SMA Short", color='orange',
linestyle='--')
plt.plot(df.index, df["SMA_long"], label="SMA Long", color='red',
linestyle='--')

# Adding buy and sell markers to


Model: the price chart
buys = df[df['signal'] == 1]
sells = df[df['signal'] == -1]
plt.scatter(buys.index, buys['Close'], marker='^', color='green', label='Buy
Signal', s=1
Model: 00)
plt.scatter(sells.index, sells['Close'], marker='v', color='red',
label='Sell Signal', s=100)
plt.title(f"{ticker} Price, SMA and Trading Signals")
plt.legend()

# Plot
Model: ting the RSI
plt.subplot(3, 1, 2)
plt.plot(df.index, df["RSI"], label="RSI", color='purple')
plt.axhline(50, color='grey', linestyle='--', label='RSI 5
Model: 0')
plt.title("RSI")
plt.legend()

# Plotting the portfolio value

23
plt.subplot(3, 1, 3)
plt.plot(df.index, df["portfolio"], label='Portfolio Value', color='black')
plt.title
Model: ("Portfolio Value")
plt.legend()

plt.tight_layout()
plt.show()

def main():
\"\"\"Main execution.\"\"\"
ticker = \"NVDA\" # Changed to Nvidia
start_date = \"2020-01-
Model: 01\"
end_date = \"2024-01-01\"

#Fetch data
df = fetch_data(ticker, start_date, end_date)
if df is None:
return

#Calculate indicators
df = calculate_
Model: indicators(df)

#Generate buy and sell signals


df = generate_signals(df)

# Run backtest
df, trade_log = backtest(df)
print(f"Trade log:\\n{trade_log}")

# Plot strategy

Model: plot_strategy(df, ticker)

# Calculate performance metrics (e.g., total return, max drawdown, etc.) can
be added here.
# This requires extending the backtest method
""")

# Call main, so you can still see the plots


main()

Model: ```
4. **Run the Cell:** Execute this code cell. It will now create a

24
`momentum_nvidia.py` file, and run the script as usual.

**Choosing a Method:**

* **Method 1 (`%%writefile`):** This is generally the easier and preferred


Model: method for saving a single file. It's more concise and less prone to
errors.
* **Method 2 (Python File I/O):** This is more flexible if you want to
dynamically create a file, or write specific parts of a script.

After either method, the `momentum_nvidia.


Model: py` file will be present in your Colab environment's current working
directory. You can then:
1. Download the file using the file explorer
2. Run the script again in a new code cell `!python momentum_nvidia.py`

Choose either method, run the code cell, and you will
Model: have your python file created locally in your Google Colab environment.

You: exit
Ending the chat session. Goodbye!

3 Simple Text to Audio


“response_modalities”: [“AUDIO”]

3.1 One call


[6]: @contextlib.contextmanager
def wave_file(filename, channels=1, rate=24000, sample_width=2):
with wave.open(filename, "wb") as wf:
wf.setnchannels(channels)
wf.setsampwidth(sample_width)
wf.setframerate(rate)
yield wf

[ ]: config={"generation_config": {"response_modalities": ["AUDIO"]}}

async with client.aio.live.connect(model=MODEL, config=config) as session:


file_name = 'audio.wav'
with wave_file(file_name) as wav:
message = "Hello? Gemini are you there?"
print("> ", message, "\n")
await session.send(message, end_of_turn=True)

turn = session.receive()
async for n,response in async_enumerate(turn):

25
if response.data is not None:
wav.writeframes(response.data)

if n==0:
print(response.server_content.model_turn.parts[0].inline_data.
↪mime_type)

print('.', end='')

display(Audio(file_name, autoplay=True))

> Hello? Gemini are you there?

audio/pcm;rate=24000

<IPython.lib.display.Audio object>

3.2 Multiple calls


[3]: import nest_asyncio
import asyncio
from IPython.display import Audio
import wave

nest_asyncio.apply()

[1]: import time

[8]: @contextlib.contextmanager
def wave_file(filename, channels=1, rate=24000, sample_width=2):
with wave.open(filename, "wb") as wf:
wf.setnchannels(channels)
wf.setsampwidth(sample_width)
wf.setframerate(rate)
yield wf

# Configuration for the model


config = {"generation_config": {"response_modalities": ["AUDIO"]}}

# Function to interact with the user


async def chat_with_model():
# Establish a session with the model
async with client.aio.live.connect(model=MODEL, config=config) as session:
print("Chat session started. Type 'exit' to end the conversation.")
while True:
message = input("You: ")

26
# Check if the user wants to exit
if message.lower() == "exit":
print("Ending the chat session. Goodbye!")
break

await session.send(message, end_of_turn=True)

# Receive and save the model's audio response


turn = session.receive()

file_name = 'audio.wav'
with wave_file(file_name) as wav:

async for n,response in async_enumerate(turn):


if response.data is not None:
wav.writeframes(response.data)

if n==0:
print(response.server_content.model_turn.parts[0].
↪inline_data.mime_type)

print('.', end='')

# Display the audio immediately after saving


print("Model: (Audio response)")
display(Audio(file_name, autoplay=True))
time.sleep(50)

# To run the asynchronous function in Google Colab

await chat_with_model()

# Chat session started. Type 'exit' to end the conversation.


# You: What knowledge do I need to acquire to shift my career to Algorithmic␣
↪Trading?

# audio/pcm;rate=24000
# ..............................................................................
↪.............................................................................

↪...............Model: (Audio response)

# You: Can you create a 4-week plan for me to dive into algorithmic trading,␣
↪considering I’m a beginner?

# audio/pcm;rate=24000
# ..............................................................................
↪...............................................................Model: (Audio␣

↪response)

27
# You: Can you provide more detailed activities and resources for Week 1 of my␣
↪4-week plan to dive into algorithmic trading?

# audio/pcm;rate=24000
# ..............................................................................
↪..........................................................................

↪Model: (Audio response)

# You: exit
# Ending the chat session. Goodbye!

Output hidden; open in https://colab.research.google.com to view.

28

You might also like